commit f231cc5b1f164802b2e2c55d043c8986a74a9dcb Author: WildSoft Date: Tue Oct 6 21:08:12 2026 +0300 Update public source diff --git a/cracklab/client.bat b/cracklab/client.bat new file mode 100644 index 0000000..3e7c193 --- /dev/null +++ b/cracklab/client.bat @@ -0,0 +1,14 @@ +@echo off +setlocal + +cd /d "%~dp0" + +python -m client.main %* + +if errorlevel 1 ( + echo. + echo CrackLab client failed. + pause +) + +endlocal diff --git a/cracklab/client/__init__.py b/cracklab/client/__init__.py new file mode 100644 index 0000000..b27cd18 --- /dev/null +++ b/cracklab/client/__init__.py @@ -0,0 +1 @@ +"""WiFi GPS Mapper CrackLab Windows client.""" diff --git a/cracklab/client/client.py b/cracklab/client/client.py new file mode 100644 index 0000000..e774f35 --- /dev/null +++ b/cracklab/client/client.py @@ -0,0 +1,793 @@ +from __future__ import annotations + +import json +import logging +import traceback +from pathlib import Path +from typing import Any + +from .config import ClientConfig, load_config +from .hashcat import ( + HashcatError, + run_show, + run_step, +) +from .job_package import ( + ImportedJob, + JobPackageError, + JobPackageService, +) +from .client_logging import ( + configure_job_logging, + configure_logging, +) +from .paths import ClientPaths +from .result_package import ( + ResultPackageError, + create_result_package, +) +from .state import ( + JOB_STATUS_COMPLETED, + JOB_STATUS_FAILED, + JOB_STATUS_PARTIAL, + JOB_STATUS_RUNNING, + STEP_STATUS_COMPLETED, + STEP_STATUS_FAILED, + STEP_STATUS_PARTIAL, + STEP_STATUS_RUNNING, + StateError, + get_step_state, + initialize_state, + load_state, + update_job_state, + update_step_state, +) + + +class ClientError(RuntimeError): + pass + + +class CrackLabClient: + def __init__( + self, + script_dir: Path, + ) -> None: + self.script_dir = script_dir.resolve() + + self.config: ClientConfig = load_config( + self.script_dir + ) + + self.config.potfile_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + self.paths = ClientPaths.from_root( + self.config.client_root + ) + self.paths.initialize() + + self.logger = configure_logging( + self.paths.logs / "client.log" + ) + + self.package_service = JobPackageService( + self.paths + ) + + self.logger.info( + "CrackLab client initialized" + ) + self.logger.info( + "Client root: %s", + self.paths.root, + ) + self.logger.info( + "Hashcat: %s", + self.config.hashcat_exe, + ) + self.logger.info( + "Potfile: %s", + self.config.potfile_path, + ) + self.logger.info( + "poll_seconds=%s max_parallel_jobs=%s", + self.config.poll_seconds, + self.config.max_parallel_jobs, + ) + + def import_jobs(self) -> list[ImportedJob]: + imported: list[ImportedJob] = [] + + packages = sorted( + self.paths.inbox.glob( + "JOB-*.zip" + ) + ) + + if not packages: + self.logger.info( + "Inbox is empty." + ) + return imported + + for package in packages: + try: + self.logger.info( + "Importing Job package: %s", + package.name, + ) + + item = ( + self.package_service + .import_package(package) + ) + + imported.append(item) + + if item.idempotent: + self.logger.info( + "Job package already imported: " + "%s", + item.job_id, + ) + else: + self.logger.info( + "Job imported: %s", + item.job_id, + ) + + except JobPackageError as exc: + self.logger.error( + "Job package rejected: %s: %s", + package.name, + exc, + ) + + except Exception: + self.logger.exception( + "Unexpected error importing %s", + package.name, + ) + + return imported + + def _load_job( + self, + job_dir: Path, + ) -> dict[str, Any]: + path = job_dir / "job.json" + + try: + data = json.loads( + path.read_text( + encoding="utf-8" + ) + ) + except (OSError, json.JSONDecodeError) as exc: + raise ClientError( + f"Failed to read {path}: {exc}" + ) from exc + + if not isinstance(data, dict): + raise ClientError( + f"Invalid Job JSON: {path}" + ) + + return data + + def _ensure_state( + self, + job_dir: Path, + job: dict[str, Any], + ) -> dict[str, Any]: + path = job_dir / "state" / "client_state.json" + + if not path.is_file(): + self.logger.info( + "%s: creating client state", + job["job_id"], + ) + return initialize_state( + job_dir, + job, + ) + + try: + state = load_state( + job_dir + ) + except StateError: + self.logger.warning( + "%s: invalid state; rebuilding state", + job["job_id"], + ) + return initialize_state( + job_dir, + job, + ) + + if state.get("job_id") != job["job_id"]: + raise ClientError( + "State job_id does not match job.json." + ) + + expected_steps = { + str(step["step_no"]) + for step in job["steps"] + } + + actual_steps = state.get( + "steps", + {}, + ) + + if not isinstance(actual_steps, dict): + self.logger.warning( + "%s: state has invalid steps; rebuilding", + job["job_id"], + ) + return initialize_state( + job_dir, + job, + ) + + if set(actual_steps) != expected_steps: + self.logger.warning( + "%s: state steps do not match " + "job.json; rebuilding", + job["job_id"], + ) + return initialize_state( + job_dir, + job, + ) + + return state + + def _step_result( + self, + job_dir: Path, + step: dict[str, Any], + ) -> dict[str, Any]: + state = get_step_state( + job_dir, + step["step_no"], + ) + + return { + "step_no": step["step_no"], + "step_id": step["step_id"], + "session_name": step["session_name"], + "status": state["status"], + "started_at": state.get( + "started_at" + ), + "completed_at": state.get( + "completed_at" + ), + "exit_code": state.get( + "exit_code" + ), + "restore_seen": bool( + state.get("restore_seen", False) + ), + "error": state.get("error"), + } + + def _run_step( + self, + job_dir: Path, + job: dict[str, Any], + step: dict[str, Any], + job_logger: logging.Logger, + ) -> bool: + step_no = step["step_no"] + + state = get_step_state( + job_dir, + step_no, + ) + + if ( + state.get("status") + == STEP_STATUS_COMPLETED + ): + job_logger.info( + "Step %s already COMPLETED; skipping.", + step_no, + ) + return True + + restore_file = ( + job_dir + / "state" + / f"step-{step_no:03d}.restore" + ) + + restore_seen = restore_file.is_file() + + mode = ( + "RESTORE" + if restore_seen + else "START" + ) + + job_logger.info( + "Step %s (%s) starting: %s " + "session=%s", + step_no, + step["step_id"], + mode, + step["session_name"], + ) + + if restore_seen: + job_logger.warning( + "Step %s has restore file; " + "resuming existing Hashcat session.", + step_no, + ) + + update_step_state( + job_dir, + step_no, + STEP_STATUS_RUNNING, + restore_seen=restore_seen, + started=True, + ) + + log_path = ( + job_dir + / "logs" + / f"step-{step_no:03d}.log" + ) + + try: + result = run_step( + self.config, + job_dir, + job, + step, + log_path, + restore=restore_seen, + ) + + except HashcatError as exc: + current_restore = ( + restore_file.is_file() + ) + + update_step_state( + job_dir, + step_no, + ( + STEP_STATUS_PARTIAL + if current_restore + else STEP_STATUS_FAILED + ), + exit_code=exc.exit_code, + restore_seen=current_restore, + error=str(exc), + completed=True, + ) + + if current_restore: + job_logger.warning( + "Step %s interrupted/partial: %s", + step_no, + exc, + ) + else: + job_logger.error( + "Step %s failed: %s", + step_no, + exc, + ) + + return False + + except Exception as exc: + update_step_state( + job_dir, + step_no, + STEP_STATUS_FAILED, + restore_seen=restore_file.is_file(), + error=str(exc), + completed=True, + ) + + job_logger.exception( + "Unexpected Step %s error.", + step_no, + ) + + return False + + if result.restore_seen: + update_step_state( + job_dir, + step_no, + STEP_STATUS_PARTIAL, + exit_code=result.exit_code, + restore_seen=True, + error=( + "Hashcat finished while " + "restore file still exists." + ), + completed=True, + ) + + job_logger.warning( + "Step %s remains PARTIAL: " + "restore file exists after Hashcat " + "exit=%s.", + step_no, + result.exit_code, + ) + + return False + + if result.exit_code not in (0, 1): + update_step_state( + job_dir, + step_no, + STEP_STATUS_FAILED, + exit_code=result.exit_code, + restore_seen=False, + error=( + f"Hashcat exited with " + f"code {result.exit_code}." + ), + completed=True, + ) + + job_logger.error( + "Step %s failed: Hashcat exit=%s.", + step_no, + result.exit_code, + ) + + return False + + marker = ( + job_dir + / "state" + / f"step-{step_no:03d}.completed" + ) + + marker.write_text( + "COMPLETED\n", + encoding="utf-8", + ) + + update_step_state( + job_dir, + step_no, + STEP_STATUS_COMPLETED, + exit_code=result.exit_code, + restore_seen=False, + error=None, + completed=True, + ) + + job_logger.info( + "Step %s COMPLETED.", + step_no, + ) + + return True + + def run_job( + self, + job_dir: Path, + ) -> bool: + job = self._load_job( + job_dir + ) + + job_id = job["job_id"] + + job_logger = configure_job_logging( + job_dir / "logs" / "client.log", + job_id, + ) + + job_logger.info( + "Job processing started." + ) + job_logger.info( + "method=%s version=%s hashes=%s " + "handshakes=%s steps=%s", + job["method_id"], + job["method_version"], + job["hash_count"], + job["handshake_count"], + job["step_count"], + ) + + try: + state = self._ensure_state( + job_dir, + job, + ) + + if ( + state.get("status") + == JOB_STATUS_COMPLETED + ): + try: + archived_package = ( + self.package_service.archive_job( + job_dir.name + ) + ) + except JobPackageError as exc: + job_logger.error( + "Job package archival failed: %s", + exc, + ) + return False + except Exception: + job_logger.exception( + "Unexpected Job package archival failure." + ) + return False + + job_logger.info( + "Job already COMPLETED; " + "Job package finalized: %s", + archived_package, + ) + return True + + update_job_state( + job_dir, + JOB_STATUS_RUNNING, + ) + + all_completed = True + + for step in job["steps"]: + if not self._run_step( + job_dir, + job, + step, + job_logger, + ): + all_completed = False + break + + if not all_completed: + update_job_state( + job_dir, + JOB_STATUS_PARTIAL, + ) + + job_logger.warning( + "Job remains PARTIAL." + ) + + return False + + job_logger.info( + "All steps completed; running Hashcat --show." + ) + + show_path = ( + job_dir + / "results" + / "hashcat-show.txt" + ) + + show_log = ( + job_dir + / "logs" + / "show.log" + ) + + try: + show_output = run_show( + self.config, + job_dir, + job, + show_path, + show_log, + ) + + job_logger.info( + "Hashcat --show completed: " + "%s bytes, %s lines.", + show_path.stat().st_size, + len(show_output.splitlines()), + ) + + except HashcatError as exc: + update_job_state( + job_dir, + JOB_STATUS_FAILED, + error=str(exc), + ) + + job_logger.error( + "Hashcat --show failed: %s", + exc, + ) + + return False + + except Exception as exc: + update_job_state( + job_dir, + JOB_STATUS_FAILED, + error=str(exc), + ) + + job_logger.exception( + "Unexpected --show error." + ) + + return False + + step_states = [ + self._step_result( + job_dir, + step, + ) + for step in job["steps"] + ] + + try: + result_package = ( + create_result_package( + job_dir, + job, + step_states, + self.paths.outbox, + logger=job_logger, + ) + ) + + except ResultPackageError as exc: + update_job_state( + job_dir, + JOB_STATUS_FAILED, + error=str(exc), + ) + + job_logger.error( + "Result package creation failed: %s", + exc, + ) + + return False + + except Exception as exc: + update_job_state( + job_dir, + JOB_STATUS_FAILED, + error=str(exc), + ) + + job_logger.exception( + "Unexpected result package error." + ) + + return False + + update_job_state( + job_dir, + JOB_STATUS_COMPLETED, + ) + + try: + archived_package = ( + self.package_service.archive_job( + job_dir.name + ) + ) + except JobPackageError as exc: + job_logger.error( + "Job package archival failed: %s", + exc, + ) + return False + except Exception: + job_logger.exception( + "Unexpected Job package archival failure." + ) + return False + + job_logger.info( + "Job COMPLETED." + ) + job_logger.info( + "Result package: %s", + result_package, + ) + job_logger.info( + "Job package archived: %s", + archived_package, + ) + + return True + + except Exception as exc: + update_job_state( + job_dir, + JOB_STATUS_FAILED, + error=str(exc), + ) + + job_logger.error( + "Job failed: %s", + exc, + ) + job_logger.debug( + "%s", + traceback.format_exc(), + ) + + return False + + def run_once(self) -> list[str]: + imported = self.import_jobs() + + for item in imported: + self.logger.info( + "Queue item: %s idempotent=%s", + item.job_id, + item.idempotent, + ) + + completed: list[str] = [] + + for job_dir in sorted( + self.paths.jobs.glob("JOB-*") + ): + if not job_dir.is_dir(): + continue + + try: + if self.run_job( + job_dir + ): + completed.append( + job_dir.name + ) + + except Exception: + self.logger.exception( + "Unhandled error processing %s", + job_dir.name, + ) + + return completed + + def run_forever(self) -> None: + self.logger.info( + "Client loop started." + ) + + while True: + try: + self.run_once() + + except KeyboardInterrupt: + self.logger.info( + "Client stopped by user." + ) + return + + except Exception: + self.logger.exception( + "Unhandled client loop error." + ) + + import time + + time.sleep( + self.config.poll_seconds + ) diff --git a/cracklab/client/client_logging.py b/cracklab/client/client_logging.py new file mode 100644 index 0000000..85756fc --- /dev/null +++ b/cracklab/client/client_logging.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from pathlib import Path + + +LOGGER_NAME = "cracklab.client" + + +class UTCFormatter(logging.Formatter): + converter = staticmethod( + lambda timestamp: datetime.fromtimestamp( + timestamp, + tz=timezone.utc, + ).timetuple() + ) + + +def _configure( + name: str, + log_path: Path, +) -> logging.Logger: + log_path.parent.mkdir(parents=True, exist_ok=True) + + logger = logging.getLogger(name) + logger.setLevel(logging.INFO) + logger.propagate = False + + if logger.handlers: + return logger + + handler = logging.FileHandler( + log_path, + mode="a", + encoding="utf-8", + ) + handler.setFormatter( + UTCFormatter( + "%(asctime)sZ %(levelname)s %(message)s", + datefmt="%Y-%m-%dT%H:%M:%S", + ) + ) + + logger.addHandler(handler) + + return logger + + +def configure_logging(log_path: Path) -> logging.Logger: + return _configure( + LOGGER_NAME, + log_path, + ) + + +def configure_job_logging( + log_path: Path, + job_id: str, +) -> logging.Logger: + return _configure( + f"{LOGGER_NAME}.{job_id}", + log_path, + ) diff --git a/cracklab/client/config.example.json b/cracklab/client/config.example.json new file mode 100644 index 0000000..8e546da --- /dev/null +++ b/cracklab/client/config.example.json @@ -0,0 +1,12 @@ +{ + "hashcat_exe": "F:\\hashcat\\hashcat.exe", + "potfile_path": "F:\\cracklab\\potfile\\wifi-gps-mapper.potfile", + "client_root": "F:\\cracklab\\client", + "wordlists": { + "insidePRO_WPA": "F:\\hashcat\\my-slovari\\insidePRO_WPA.txt", + "BreachCompilation": "B:\\BIG_SLOVAR\\parser\\BreachCompilation.txt", + "test": "F:\\cracklab\\test-artifacts\\wordlists\\integration-test.txt" + }, + "poll_seconds": 3, + "max_parallel_jobs": 1 +} diff --git a/cracklab/client/config.py b/cracklab/client/config.py new file mode 100644 index 0000000..783338b --- /dev/null +++ b/cracklab/client/config.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path + + +CONFIG_NAME = "config.json" + + +@dataclass(frozen=True) +class ClientConfig: + hashcat_exe: Path + potfile_path: Path + client_root: Path + wordlists: dict[str, Path] + poll_seconds: int + max_parallel_jobs: int + + +def load_config(script_dir: Path) -> ClientConfig: + path = script_dir / CONFIG_NAME + + if not path.is_file(): + raise FileNotFoundError( + f"Missing {path}. " + "Copy config.example.json to config.json and edit it." + ) + + try: + data = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + raise ValueError(f"Invalid JSON in {path}: {exc}") from exc + + if not isinstance(data, dict): + raise ValueError("Client config must contain a JSON object.") + + required = ( + "hashcat_exe", + "potfile_path", + "client_root", + "wordlists", + "poll_seconds", + "max_parallel_jobs", + ) + + missing = [name for name in required if name not in data] + if missing: + raise ValueError( + "Missing required config fields: " + + ", ".join(missing) + ) + + for name in ( + "hashcat_exe", + "potfile_path", + "client_root", + ): + if not isinstance(data[name], str) or not data[name].strip(): + raise ValueError( + f"Config field {name!r} must be a non-empty string." + ) + + if not isinstance(data["wordlists"], dict) or not data["wordlists"]: + raise ValueError( + "Config field 'wordlists' must be a non-empty object." + ) + + for name, path_value in data["wordlists"].items(): + if not isinstance(name, str) or not name.strip(): + raise ValueError( + "Each wordlists key must be a non-empty string." + ) + + if not isinstance(path_value, str) or not path_value.strip(): + raise ValueError( + f"Wordlist {name!r} path must be a non-empty string." + ) + + for name in ( + "poll_seconds", + "max_parallel_jobs", + ): + value = data[name] + + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError( + f"Config field {name!r} must be an integer." + ) + + if value <= 0: + raise ValueError( + f"Config field {name!r} must be greater than zero." + ) + + return ClientConfig( + hashcat_exe=Path(data["hashcat_exe"]).expanduser().resolve(), + potfile_path=Path(data["potfile_path"]).expanduser().resolve(), + client_root=Path(data["client_root"]).expanduser().resolve(), + wordlists={ + name: Path(path_value).expanduser().resolve() + for name, path_value in data["wordlists"].items() + }, + poll_seconds=data["poll_seconds"], + max_parallel_jobs=data["max_parallel_jobs"], + ) diff --git a/cracklab/client/hashcat.py b/cracklab/client/hashcat.py new file mode 100644 index 0000000..60b3b4b --- /dev/null +++ b/cracklab/client/hashcat.py @@ -0,0 +1,673 @@ +from __future__ import annotations + +import hashlib +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + + +class HashcatError(RuntimeError): + def __init__( + self, + message: str, + *, + exit_code: int | None = None, + ) -> None: + super().__init__(message) + self.exit_code = exit_code + + +@dataclass(frozen=True) +class HashcatRunResult: + exit_code: int + restore_seen: bool + + +def restore_path( + job_dir: Path, + step: dict, +) -> Path: + return ( + job_dir + / "state" + / f"step-{step['step_no']:03d}.restore" + ) + + +def completed_marker( + job_dir: Path, + step: dict, +) -> Path: + return ( + job_dir + / "state" + / f"step-{step['step_no']:03d}.completed" + ) + + +def _session_name(step: dict) -> str: + session = step.get("session_name") + + if not isinstance(session, str) or not session: + raise HashcatError( + f"Step {step.get('step_no')} has no session_name." + ) + + return session + +def _resolve_wordlist( + config, + resource: str, + step_no, +) -> Path: + if not isinstance(resource, str) or not resource: + raise HashcatError( + f"Step {step_no} has invalid dictionary resource." + ) + + prefix = "wordlist:" + + if not resource.startswith(prefix): + raise HashcatError( + f"Step {step_no} has unsupported dictionary resource: " + f"{resource}" + ) + + name = resource[len(prefix):] + + if not name or "/" in name or "\\" in name or name in (".", ".."): + raise HashcatError( + f"Step {step_no} has invalid dictionary resource: " + f"{resource}" + ) + + dictionary = config.wordlists.get(name) + + if dictionary is None: + raise HashcatError( + f"Wordlist resource {resource!r} is not configured." + ) + + dictionary = dictionary.resolve() + + if not dictionary.is_file(): + raise HashcatError( + f"Configured wordlist does not exist: {dictionary}" + ) + + return dictionary + +def build_start_command( + config, + job_dir: Path, + job: dict, + step: dict, +) -> list[str]: + exe = config.hashcat_exe.resolve() + + if not exe.is_file(): + raise HashcatError( + f"Hashcat executable does not exist: {exe}" + ) + + hash_file = ( + job_dir + / "hashes" + / job["hash_file_name"] + ).resolve() + + if not hash_file.is_file(): + raise HashcatError( + f"Hash file does not exist: {hash_file}" + ) + + restore = restore_path( + job_dir, + step, + ).resolve() + + session = _session_name(step) + + attack_mode = step.get("definition", {}).get( + "attack_mode" + ) + + if not isinstance(attack_mode, int): + raise HashcatError( + f"Step {step.get('step_no')} has invalid " + "attack_mode." + ) + + definition = step["definition"] + + cmd = [ + str(exe), + "-m", + str(job["hash_mode"]), + "-a", + str(attack_mode), + "--session", + session, + "--restore-file-path", + str(restore), + "--potfile-path", + str(config.potfile_path.resolve()), + "--logfile-disable", + "-w", + str( + definition.get( + "workload_profile", + 1, + ) + ), + ] + + if attack_mode in (0, 1, 6, 7): + dictionary_definition = ( + definition.get( + "dictionaries" + ) + if attack_mode == 1 + else definition.get( + "dictionary" + ) + ) + + if attack_mode == 0: + if not isinstance( + dictionary_definition, + dict, + ): + raise HashcatError( + f"Step {step.get('step_no')} " + "attack mode 0 has no dictionary." + ) + + resources = [ + dictionary_definition.get( + "resource" + ) + ] + + elif attack_mode == 1: + if ( + not isinstance( + dictionary_definition, + list, + ) + or len(dictionary_definition) != 2 + ): + raise HashcatError( + f"Step {step.get('step_no')} " + "attack mode 1 requires exactly " + "two dictionaries." + ) + + resources = [ + item.get("resource") + if isinstance(item, dict) + else None + for item in dictionary_definition + ] + + else: + if not isinstance( + dictionary_definition, + dict, + ): + raise HashcatError( + f"Step {step.get('step_no')} " + f"attack mode {attack_mode} " + "has no dictionary." + ) + + resources = [ + dictionary_definition.get( + "resource" + ) + ] + + dictionaries = [ + _resolve_wordlist( + config, + resource, + step.get("step_no"), + ) + for resource in resources + ] + + induction = ( + job_dir + / "state" + / "induct" + ).resolve() + + outfile_check = ( + job_dir + / "state" + / "outfiles" + ).resolve() + + induction.mkdir( + parents=True, + exist_ok=True, + ) + + outfile_check.mkdir( + parents=True, + exist_ok=True, + ) + + cmd.extend( + [ + "--induction-dir", + str(induction), + "--outfile-check-dir", + str(outfile_check), + str(hash_file), + ] + ) + + cmd.extend( + str(dictionary) + for dictionary in dictionaries + ) + + if attack_mode in (6, 7): + mask = definition.get("mask") + + if not isinstance(mask, str) or not mask: + raise HashcatError( + f"Step {step.get('step_no')} " + f"attack mode {attack_mode} has no mask." + ) + + if attack_mode == 6: + cmd.append(mask) + else: + cmd.insert( + len(cmd) - len(dictionaries), + mask, + ) + + elif attack_mode == 3: + mask = definition.get("mask") + + if not isinstance(mask, str) or not mask: + raise HashcatError( + f"Step {step.get('step_no')} " + "attack mode 3 has no mask." + ) + + cmd.extend( + [ + str(hash_file), + mask, + ] + ) + + else: + raise HashcatError( + f"Unsupported attack mode {attack_mode}. " + "Use a structured adapter for new modes." + ) + + return cmd + + +def build_restore_command( + config, + job_dir: Path, + step: dict, +) -> list[str]: + exe = config.hashcat_exe.resolve() + + if not exe.is_file(): + raise HashcatError( + f"Hashcat executable does not exist: {exe}" + ) + + restore = restore_path( + job_dir, + step, + ).resolve() + + return [ + str(exe), + "--session", + _session_name(step), + "--restore-file-path", + str(restore), + "--restore", + ] + + +def build_show_command( + config, + job_dir: Path, + job: dict, +) -> list[str]: + exe = config.hashcat_exe.resolve() + + if not exe.is_file(): + raise HashcatError( + f"Hashcat executable does not exist: {exe}" + ) + + hash_file = ( + job_dir + / "hashes" + / job["hash_file_name"] + ).resolve() + + if not hash_file.is_file(): + raise HashcatError( + f"Hash file does not exist: {hash_file}" + ) + + return [ + str(exe), + "-m", + str(job["hash_mode"]), + "--potfile-path", + str(config.potfile_path.resolve()), + "--show", + str(hash_file), + ] + + +def command_text(cmd: list[str]) -> str: + return " ".join( + f'"{value}"' if " " in value else value + for value in cmd + ) + + +def run_hashcat( + cmd: list[str], + log_path: Path, + *, + on_output: Callable[[bytes], None] | None = None, +) -> int: + log_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + if not cmd: + raise HashcatError( + "Hashcat command is empty." + ) + + hashcat_dir = ( + Path(cmd[0]) + .resolve() + .parent + ) + + text = command_text(cmd) + + with log_path.open( + "ab", + ) as log: + log.write( + b"\n=== START ===\n" + ) + log.write( + text.encode( + "utf-8", + errors="replace", + ) + ) + log.write(b"\n") + log.flush() + + try: + process = subprocess.Popen( + cmd, + cwd=str(hashcat_dir), + stdin=None, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + bufsize=0, + creationflags=getattr( + subprocess, + "CREATE_NEW_PROCESS_GROUP", + 0, + ), + ) + except OSError as exc: + log.write( + ( + "\n=== PROCESS START ERROR ===\n" + f"{exc}\n" + ).encode( + "utf-8", + errors="replace", + ) + ) + raise HashcatError( + f"Failed to start Hashcat: {exc}" + ) from exc + + try: + if process.stdout is None: + raise HashcatError( + "Hashcat stdout pipe was not created." + ) + + while True: + chunk = process.stdout.read(4096) + + if not chunk: + break + + log.write(chunk) + log.flush() + + if on_output is not None: + on_output(chunk) + + except BaseException: + try: + process.kill() + except OSError: + pass + + raise + + finally: + if process.stdout is not None: + process.stdout.close() + + exit_code = process.wait() + + log.write( + ( + "\n=== END ===\n" + f"exit_code={exit_code}\n" + ).encode( + "utf-8", + errors="replace", + ) + ) + log.flush() + + return exit_code + + +def run_step( + config, + job_dir: Path, + job: dict, + step: dict, + log_path: Path, + *, + restore: bool = False, +) -> HashcatRunResult: + restore_file = restore_path( + job_dir, + step, + ) + + if restore: + if not restore_file.is_file(): + raise HashcatError( + f"Restore requested but restore file " + f"does not exist: {restore_file}" + ) + + cmd = build_restore_command( + config, + job_dir, + step, + ) + else: + cmd = build_start_command( + config, + job_dir, + job, + step, + ) + + exit_code = run_hashcat( + cmd, + log_path, + on_output=lambda chunk: print( + chunk.decode( + "utf-8", + errors="replace", + ), + end="", + flush=True, + ), + ) + + restore_seen = restore_file.is_file() + + if exit_code not in (0, 1): + raise HashcatError( + f"Hashcat exited with unsupported " + f"code {exit_code}.", + exit_code=exit_code, + ) + + return HashcatRunResult( + exit_code=exit_code, + restore_seen=restore_seen, + ) + + +def run_show( + config, + job_dir: Path, + job: dict, + output_path: Path, + log_path: Path, +) -> str: + cmd = build_show_command( + config, + job_dir, + job, + ) + + output_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + log_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + hashcat_dir = ( + Path(cmd[0]) + .resolve() + .parent + ) + + text = command_text(cmd) + + with log_path.open( + "ab", + ) as log: + log.write( + b"\n=== SHOW START ===\n" + ) + log.write( + text.encode( + "utf-8", + errors="replace", + ) + ) + log.write(b"\n") + log.flush() + + try: + process = subprocess.run( + cmd, + cwd=str(hashcat_dir), + stdin=None, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + ) + except OSError as exc: + log.write( + ( + "\n=== SHOW START ERROR ===\n" + f"{exc}\n" + ).encode( + "utf-8", + errors="replace", + ) + ) + raise HashcatError( + f"Failed to start Hashcat --show: {exc}" + ) from exc + + output = process.stdout or b"" + + output_path.write_bytes( + output + ) + + log.write(output) + log.write( + ( + "\n=== SHOW END ===\n" + f"exit_code={process.returncode}\n" + ).encode( + "utf-8", + errors="replace", + ) + ) + log.flush() + + if process.returncode not in (0, 1): + raise HashcatError( + f"Hashcat --show exited with " + f"code {process.returncode}." + ) + + return output.decode( + "utf-8", + errors="replace", + ) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + + with path.open("rb") as handle: + while True: + chunk = handle.read(1024 * 1024) + + if not chunk: + break + + digest.update(chunk) + + return digest.hexdigest() diff --git a/cracklab/client/job_package.py b/cracklab/client/job_package.py new file mode 100644 index 0000000..8dd8950 --- /dev/null +++ b/cracklab/client/job_package.py @@ -0,0 +1,1065 @@ +from __future__ import annotations + +import hashlib +import json +import re +import shutil +import tempfile +import zipfile +from dataclasses import dataclass +from pathlib import Path + +from .state import initialize_state + +JOB_ID_RE = re.compile(r"^JOB-[0-9A-F]{12}$") + + +class JobPackageError(RuntimeError): + pass + + +@dataclass(frozen=True) +class ImportedJob: + job_id: str + job_path: Path + package_path: Path + idempotent: bool + + +@dataclass(frozen=True) +class _ValidatedPackage: + job: dict + hash_content: bytes + job_bytes: bytes + hash_path: str + + +class JobPackageService: + def __init__(self, paths) -> None: + self._paths = paths + + def import_package( + self, + package_path: str | Path, + ) -> ImportedJob: + package_path = Path(package_path).resolve() + + if not package_path.is_file(): + raise JobPackageError( + f"Job package not found: {package_path}" + ) + + validated = self._read_and_validate( + package_path + ) + + job_id = validated.job["job_id"] + job_path = ( + self._paths.jobs + / package_path.stem + ) + + if job_path.exists(): + idempotent = self._validate_existing_job( + job_path, + validated, + ) + + pending_path = ( + self._paths.pending + / package_path.name + ) + + self._move_package( + package_path, + pending_path, + ) + + return ImportedJob( + job_id=job_id, + job_path=job_path, + package_path=pending_path, + idempotent=idempotent, + ) + + self._install_new_job( + job_path, + validated, + ) + + pending_path = ( + self._paths.pending + / package_path.name + ) + + self._move_package( + package_path, + pending_path, + ) + + return ImportedJob( + job_id=job_id, + job_path=job_path, + package_path=pending_path, + idempotent=False, + ) + + def _read_and_validate( + self, + package_path: Path, + ) -> _ValidatedPackage: + try: + with zipfile.ZipFile( + package_path, + "r", + ) as archive: + self._validate_zip_members( + archive + ) + + names = set( + archive.namelist() + ) + + job_bytes = archive.read( + "job.json" + ) + hash_name = next( + name + for name in names + if name.startswith("hashes/") + ) + hash_bytes = archive.read( + hash_name + ) + manifest_bytes = archive.read( + "manifest.json" + ) + except ( + zipfile.BadZipFile, + KeyError, + StopIteration, + OSError, + ) as exc: + raise JobPackageError( + f"Invalid job package: {package_path}" + ) from exc + + job = self._load_json_object( + job_bytes, + "job.json", + ) + + manifest = self._load_json_object( + manifest_bytes, + "manifest.json", + ) + + self._validate_job( + job, + hash_name, + hash_bytes, + ) + + self._validate_manifest( + manifest, + job, + package_path.name, + job_bytes, + hash_bytes, + hash_name, + ) + + return _ValidatedPackage( + job=job, + hash_content=hash_bytes, + job_bytes=job_bytes, + hash_path=hash_name, + ) + + @staticmethod + def _validate_zip_members( + archive: zipfile.ZipFile, + ) -> None: + infos = archive.infolist() + names = [info.filename for info in infos] + + if len(names) != len(set(names)): + raise JobPackageError( + "Job package contains duplicate ZIP members" + ) + + expected_fixed = { + "job.json", + "manifest.json", + } + + hash_members = [ + name + for name in names + if name.startswith("hashes/") + ] + + if len(names) != 3: + raise JobPackageError( + "Job package must contain exactly three files" + ) + + if not expected_fixed.issubset( + set(names) + ): + raise JobPackageError( + "Job package is missing job.json " + "or manifest.json" + ) + + if len(hash_members) != 1: + raise JobPackageError( + "Job package must contain exactly one hash file" + ) + + expected = expected_fixed | set( + hash_members + ) + + if set(names) != expected: + raise JobPackageError( + "Job package contains unexpected files" + ) + + for info in infos: + name = info.filename + + if not name: + raise JobPackageError( + "Job package contains an empty member name" + ) + + if name.startswith("/"): + raise JobPackageError( + f"Absolute ZIP member path: {name}" + ) + + parts = Path(name).parts + + if ".." in parts: + raise JobPackageError( + f"Path traversal in ZIP member: {name}" + ) + + if "\\" in name: + raise JobPackageError( + f"Invalid ZIP member path: {name}" + ) + + if name.endswith("/"): + raise JobPackageError( + f"Directories are not allowed: {name}" + ) + + if info.is_dir(): + raise JobPackageError( + f"Directory member is not allowed: {name}" + ) + + unix_mode = ( + info.external_attr >> 16 + ) & 0xFFFF + + if unix_mode: + file_type = unix_mode & 0o170000 + + if file_type == 0o120000: + raise JobPackageError( + f"Symlink member is not allowed: {name}" + ) + + @staticmethod + def _load_json_object( + content: bytes, + name: str, + ) -> dict: + try: + value = json.loads( + content.decode("utf-8") + ) + except ( + UnicodeDecodeError, + json.JSONDecodeError, + ) as exc: + raise JobPackageError( + f"Invalid JSON: {name}" + ) from exc + + if not isinstance(value, dict): + raise JobPackageError( + f"{name} must contain a JSON object" + ) + + return value + + @staticmethod + def _require_string( + data: dict, + name: str, + ) -> str: + value = data.get(name) + + if not isinstance(value, str): + raise JobPackageError( + f"{name} must be a string" + ) + + if not value: + raise JobPackageError( + f"{name} must not be empty" + ) + + return value + + @staticmethod + def _require_int( + data: dict, + name: str, + ) -> int: + value = data.get(name) + + if ( + isinstance(value, bool) + or not isinstance(value, int) + ): + raise JobPackageError( + f"{name} must be an integer" + ) + + return value + + def _validate_job( + self, + job: dict, + hash_path: str, + hash_bytes: bytes, + ) -> None: + required = ( + "job_id", + "created_at", + "method_id", + "method_version", + "hash_mode", + "hash_file_name", + "hash_file_sha256", + "hash_count", + "handshake_count", + "step_count", + "handshakes", + "steps", + ) + + for name in required: + if name not in job: + raise JobPackageError( + f"job.json is missing field: {name}" + ) + + job_id = self._require_string( + job, + "job_id", + ) + + if not JOB_ID_RE.fullmatch(job_id): + raise JobPackageError( + f"Invalid Job ID: {job_id}" + ) + + self._require_string( + job, + "created_at", + ) + + self._require_string( + job, + "method_id", + ) + + method_version = self._require_int( + job, + "method_version", + ) + hash_mode = self._require_int( + job, + "hash_mode", + ) + hash_count = self._require_int( + job, + "hash_count", + ) + handshake_count = self._require_int( + job, + "handshake_count", + ) + step_count = self._require_int( + job, + "step_count", + ) + + if method_version < 1: + raise JobPackageError( + "method_version must be positive" + ) + + if hash_mode < 0: + raise JobPackageError( + "hash_mode must not be negative" + ) + + if hash_count <= 0: + raise JobPackageError( + "hash_count must be greater than zero" + ) + + if handshake_count <= 0: + raise JobPackageError( + "handshake_count must be greater than zero" + ) + + if step_count <= 0: + raise JobPackageError( + "step_count must be greater than zero" + ) + + hash_file_name = self._require_string( + job, + "hash_file_name", + ) + + expected_hash_name = ( + f"{job_id}.22000" + ) + + if hash_file_name != expected_hash_name: + raise JobPackageError( + "hash_file_name does not match " + "the Job ID" + ) + + expected_zip_path = ( + f"hashes/{hash_file_name}" + ) + + if hash_path != expected_zip_path: + raise JobPackageError( + "Hash file path does not match " + "job.json" + ) + + hash_sha256 = self._require_string( + job, + "hash_file_sha256", + ) + + if not re.fullmatch( + r"[0-9a-fA-F]{64}", + hash_sha256, + ): + raise JobPackageError( + "hash_file_sha256 must be a " + "64-character hexadecimal SHA-256" + ) + + calculated_hash_sha256 = ( + hashlib.sha256( + hash_bytes + ).hexdigest() + ) + + if ( + calculated_hash_sha256 + != hash_sha256.lower() + ): + raise JobPackageError( + "Hash file SHA-256 mismatch" + ) + + lines = hash_bytes.decode( + "utf-8" + ).splitlines() + + if len(lines) != hash_count: + raise JobPackageError( + "hash_count does not match " + "the hash file" + ) + + if any( + not line.strip() + for line in lines + ): + raise JobPackageError( + "Hash file contains an empty line" + ) + + if len(set(lines)) != hash_count: + raise JobPackageError( + "Hash file contains duplicate hashes" + ) + + handshakes = job["handshakes"] + + if not isinstance( + handshakes, + list, + ): + raise JobPackageError( + "handshakes must be a list" + ) + + if len(handshakes) != handshake_count: + raise JobPackageError( + "handshake_count does not match " + "handshakes" + ) + + handshake_ids: set[int] = set() + + for item in handshakes: + if not isinstance( + item, + dict, + ): + raise JobPackageError( + "Each handshake must be an object" + ) + + handshake_id = item.get( + "handshake_id" + ) + + if ( + isinstance(handshake_id, bool) + or not isinstance( + handshake_id, + int, + ) + ): + raise JobPackageError( + "handshake_id must be an integer" + ) + + if handshake_id <= 0: + raise JobPackageError( + "handshake_id must be positive" + ) + + if handshake_id in handshake_ids: + raise JobPackageError( + "Duplicate handshake_id" + ) + + handshake_ids.add( + handshake_id + ) + + hash22000 = item.get( + "hash22000" + ) + + if ( + not isinstance( + hash22000, + str, + ) + or not hash22000 + ): + raise JobPackageError( + "handshake hash22000 must be " + "a non-empty string" + ) + + if item.get( + "access_point_id" + ) is not None: + access_point_id = item[ + "access_point_id" + ] + + if ( + isinstance( + access_point_id, + bool, + ) + or not isinstance( + access_point_id, + int, + ) + or access_point_id <= 0 + ): + raise JobPackageError( + "access_point_id must be " + "a positive integer or null" + ) + + steps = job["steps"] + + if not isinstance( + steps, + list, + ): + raise JobPackageError( + "steps must be a list" + ) + + if len(steps) != step_count: + raise JobPackageError( + "step_count does not match steps" + ) + + step_numbers: set[int] = set() + step_ids: set[str] = set() + + for item in steps: + if not isinstance( + item, + dict, + ): + raise JobPackageError( + "Each step must be an object" + ) + + step_no = item.get( + "step_no" + ) + + if ( + isinstance(step_no, bool) + or not isinstance( + step_no, + int, + ) + ): + raise JobPackageError( + "step_no must be an integer" + ) + + if step_no <= 0: + raise JobPackageError( + "step_no must be positive" + ) + + if step_no in step_numbers: + raise JobPackageError( + "Duplicate step_no" + ) + + step_numbers.add( + step_no + ) + + step_id = item.get( + "step_id" + ) + + if ( + not isinstance( + step_id, + str, + ) + or not step_id + ): + raise JobPackageError( + "step_id must be a " + "non-empty string" + ) + + if step_id in step_ids: + raise JobPackageError( + "Duplicate step_id" + ) + + step_ids.add( + step_id + ) + + session_name = item.get( + "session_name" + ) + + if ( + not isinstance( + session_name, + str, + ) + or not session_name + ): + raise JobPackageError( + "session_name must be a " + "non-empty string" + ) + + if "definition" not in item: + raise JobPackageError( + "Step is missing definition" + ) + + if not isinstance( + item["definition"], + dict, + ): + raise JobPackageError( + "Step definition must be " + "an object" + ) + + def _validate_manifest( + self, + manifest: dict, + job: dict, + zip_filename: str, + job_bytes: bytes, + hash_bytes: bytes, + hash_path: str, + ) -> None: + if manifest.get( + "format_version" + ) != 1: + raise JobPackageError( + "Unsupported manifest format_version" + ) + + if manifest.get( + "job_id" + ) != job["job_id"]: + raise JobPackageError( + "Manifest Job ID mismatch" + ) + + if manifest.get( + "created_at" + ) != job["created_at"]: + raise JobPackageError( + "Manifest created_at mismatch" + ) + + if manifest.get( + "zip_filename" + ) != zip_filename: + raise JobPackageError( + "Manifest zip_filename mismatch" + ) + + files = manifest.get( + "files" + ) + + if not isinstance( + files, + list, + ): + raise JobPackageError( + "Manifest files must be a list" + ) + + if len(files) != 2: + raise JobPackageError( + "Manifest must contain exactly two files" + ) + + expected = { + "job.json": job_bytes, + hash_path: hash_bytes, + } + + seen: set[str] = set() + + for item in files: + if not isinstance( + item, + dict, + ): + raise JobPackageError( + "Manifest file entry must be an object" + ) + + path = item.get( + "path" + ) + + if ( + not isinstance( + path, + str, + ) + or not path + ): + raise JobPackageError( + "Manifest file path must be a " + "non-empty string" + ) + + if path in seen: + raise JobPackageError( + "Duplicate manifest file path" + ) + + seen.add(path) + + if path not in expected: + raise JobPackageError( + f"Unexpected manifest file: {path}" + ) + + size = item.get( + "size" + ) + + if ( + isinstance(size, bool) + or not isinstance(size, int) + or size < 0 + ): + raise JobPackageError( + f"Invalid manifest size: {path}" + ) + + sha256 = item.get( + "sha256" + ) + + if ( + not isinstance( + sha256, + str, + ) + or not re.fullmatch( + r"[0-9a-fA-F]{64}", + sha256, + ) + ): + raise JobPackageError( + f"Invalid manifest SHA-256: {path}" + ) + + content = expected[path] + + if size != len(content): + raise JobPackageError( + f"Manifest size mismatch: {path}" + ) + + calculated = hashlib.sha256( + content + ).hexdigest() + + if calculated != sha256.lower(): + raise JobPackageError( + f"Manifest SHA-256 mismatch: {path}" + ) + + if seen != set(expected): + raise JobPackageError( + "Manifest does not describe " + "exactly the package files" + ) + + def _validate_existing_job( + self, + job_path: Path, + package: _ValidatedPackage, + ) -> bool: + if not job_path.is_dir(): + raise JobPackageError( + f"Existing Job path is not a directory: " + f"{job_path}" + ) + + job_json_path = ( + job_path / "job.json" + ) + + hash_path = ( + job_path + / "hashes" + / package.job["hash_file_name"] + ) + + if not job_json_path.is_file(): + raise JobPackageError( + f"Existing Job is incomplete: {job_path}" + ) + + if not hash_path.is_file(): + raise JobPackageError( + f"Existing Job hash file is missing: " + f"{job_path}" + ) + + try: + existing_job_bytes = ( + job_json_path.read_bytes() + ) + existing_hash_bytes = ( + hash_path.read_bytes() + ) + except OSError as exc: + raise JobPackageError( + f"Failed to read existing Job: " + f"{job_path}" + ) from exc + + if existing_job_bytes != package.job_bytes: + raise JobPackageError( + f"Existing Job snapshot conflicts: " + f"{package.job['job_id']}" + ) + + if existing_hash_bytes != package.hash_content: + raise JobPackageError( + f"Existing Job hash snapshot conflicts: " + f"{package.job['job_id']}" + ) + + return True + + def _install_new_job( + self, + job_path: Path, + package: _ValidatedPackage, + ) -> None: + self._paths.jobs.mkdir( + parents=True, + exist_ok=True, + ) + + temporary_path = Path( + tempfile.mkdtemp( + prefix=f".{package.job['job_id']}.", + dir=self._paths.jobs, + ) + ) + + try: + (temporary_path / "hashes").mkdir() + (temporary_path / "state").mkdir() + (temporary_path / "logs").mkdir() + (temporary_path / "results").mkdir() + + (temporary_path / "job.json").write_bytes( + package.job_bytes + ) + + ( + temporary_path + / "hashes" + / package.job["hash_file_name"] + ).write_bytes( + package.hash_content + ) + + initialize_state( + temporary_path, + package.job, + ) + + temporary_path.replace( + job_path + ) + + except Exception: + shutil.rmtree( + temporary_path, + ignore_errors=True, + ) + raise + + def archive_job( + self, + job_name: str, + ) -> Path: + package_name = f"{job_name}.zip" + + pending_path = ( + self._paths.pending + / package_name + ) + + archive_path = ( + self._paths.archive + / package_name + ) + + if not pending_path.exists(): + if archive_path.is_file(): + return archive_path + + raise JobPackageError( + f"Pending Job package not found: " + f"{pending_path}" + ) + + if not pending_path.is_file(): + raise JobPackageError( + f"Pending Job package is not a file: " + f"{pending_path}" + ) + + self._move_package( + pending_path, + archive_path, + ) + + return archive_path + + def _move_package( + self, + package_path: Path, + destination: Path, + ) -> None: + destination.parent.mkdir( + parents=True, + exist_ok=True, + ) + + if destination.exists(): + if not destination.is_file(): + raise JobPackageError( + f"Package destination is not a file: " + f"{destination}" + ) + + if self._sha256_file( + destination + ) != self._sha256_file( + package_path + ): + raise JobPackageError( + f"Package destination already exists " + f"with different content: " + f"{destination.name}" + ) + + package_path.unlink() + return + + package_path.replace( + destination + ) + + @staticmethod + def _sha256_file( + path: Path, + ) -> str: + digest = hashlib.sha256() + + with path.open( + "rb" + ) as fp: + while True: + chunk = fp.read( + 1024 * 1024 + ) + + if not chunk: + break + + digest.update(chunk) + + return digest.hexdigest() diff --git a/cracklab/client/main.py b/cracklab/client/main.py new file mode 100644 index 0000000..e8ac7c2 --- /dev/null +++ b/cracklab/client/main.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import argparse +from pathlib import Path + +from .client import CrackLabClient + + +def main() -> int: + parser = argparse.ArgumentParser( + description="WiFi GPS Mapper CrackLab client" + ) + + parser.add_argument( + "--once", + action="store_true", + help="Import and process jobs once, then exit.", + ) + + args = parser.parse_args() + + script_dir = Path( + __file__ + ).resolve().parent + + client = CrackLabClient( + script_dir + ) + + if args.once: + client.run_once() + return 0 + + client.run_forever() + return 0 + + +if __name__ == "__main__": + raise SystemExit( + main() + ) diff --git a/cracklab/client/paths.py b/cracklab/client/paths.py new file mode 100644 index 0000000..5928ebe --- /dev/null +++ b/cracklab/client/paths.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + + +CLIENT_DIRECTORIES = ( + "inbox", + "pending", + "jobs", + "outbox", + "logs", + "archive", +) + + +@dataclass(frozen=True) +class ClientPaths: + root: Path + inbox: Path + pending: Path + jobs: Path + outbox: Path + logs: Path + archive: Path + + @classmethod + def from_root(cls, root: Path) -> "ClientPaths": + root = root.resolve() + + return cls( + root=root, + inbox=root / "inbox", + pending=root / "pending", + jobs=root / "jobs", + outbox=root / "outbox", + logs=root / "logs", + archive=root / "archive", + ) + + def initialize(self) -> None: + for name in CLIENT_DIRECTORIES: + (self.root / name).mkdir( + parents=True, + exist_ok=True, + ) diff --git a/cracklab/client/result_package.py b/cracklab/client/result_package.py new file mode 100644 index 0000000..30f9111 --- /dev/null +++ b/cracklab/client/result_package.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +import zipfile +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +class ResultPackageError(RuntimeError): + pass + + +def utc_now() -> str: + return ( + datetime.now(timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z") + ) + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + + with path.open("rb") as handle: + while True: + chunk = handle.read(1024 * 1024) + + if not chunk: + break + + digest.update(chunk) + + return digest.hexdigest() + + +def _json_bytes(data: dict[str, Any]) -> bytes: + return ( + json.dumps( + data, + ensure_ascii=False, + indent=2, + ) + + "\n" + ).encode("utf-8") + + +def _atomic_write( + path: Path, + data: bytes, +) -> None: + path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + fd, temporary = tempfile.mkstemp( + prefix=f".{path.name}.", + suffix=".tmp", + dir=str(path.parent), + ) + + temporary_path = Path(temporary) + + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + + temporary_path.replace(path) + except BaseException: + temporary_path.unlink( + missing_ok=True + ) + raise + + +def _validate_result_steps( + job: dict[str, Any], + step_states: list[dict[str, Any]], +) -> None: + job_steps = job.get("steps") + + if not isinstance(job_steps, list): + raise ResultPackageError( + "Job has no valid steps list." + ) + + if len(job_steps) != len(step_states): + raise ResultPackageError( + "Result step count does not match Job step count." + ) + + for job_step, result_step in zip( + job_steps, + step_states, + ): + if ( + result_step.get("step_no") + != job_step.get("step_no") + ): + raise ResultPackageError( + "Result step_no does not match Job." + ) + + if ( + result_step.get("step_id") + != job_step.get("step_id") + ): + raise ResultPackageError( + "Result step_id does not match Job." + ) + + if ( + result_step.get("session_name") + != job_step.get("session_name") + ): + raise ResultPackageError( + "Result session_name does not match Job." + ) + + if result_step.get("status") != "COMPLETED": + raise ResultPackageError( + f"Step {job_step.get('step_no')} " + "is not COMPLETED." + ) + + if result_step.get("exit_code") not in (0, 1): + raise ResultPackageError( + f"Step {job_step.get('step_no')} " + "has unsupported exit_code." + ) + + if result_step.get("restore_seen"): + raise ResultPackageError( + f"Step {job_step.get('step_no')} " + "still has an active restore state." + ) + + +def build_result( + job: dict[str, Any], + step_states: list[dict[str, Any]], + *, + completed_at: str | None = None, +) -> tuple[dict[str, Any], bytes]: + job_id = job.get("job_id") + + if not isinstance(job_id, str) or not job_id: + raise ResultPackageError( + "Job has no valid job_id." + ) + + method_id = job.get("method_id") + method_version = job.get("method_version") + + if not isinstance(method_id, str) or not method_id: + raise ResultPackageError( + "Job has no valid method_id." + ) + + if ( + isinstance(method_version, bool) + or not isinstance(method_version, int) + ): + raise ResultPackageError( + "Job has no valid method_version." + ) + + _validate_result_steps( + job, + step_states, + ) + + result = { + "schema_version": 1, + "job_id": job_id, + "status": "COMPLETED", + "completed_at": completed_at or utc_now(), + "hash_file_sha256": job["hash_file_sha256"], + "hash_count": job["hash_count"], + "method": { + "id": method_id, + "version": method_version, + }, + "steps": step_states, + "show_file": "hashcat-show.txt", + } + + unsigned_bytes = _json_bytes(result) + + result["result_sha256"] = _sha256_bytes( + unsigned_bytes + ) + + return result, _json_bytes(result) + + +def create_result_package( + job_dir: Path, + job: dict[str, Any], + step_states: list[dict[str, Any]], + outbox: Path, + *, + logger=None, +) -> Path: + results_dir = job_dir / "results" + + show_path = results_dir / "hashcat-show.txt" + + if not show_path.is_file(): + raise ResultPackageError( + f"Missing Hashcat show output: {show_path}" + ) + + result, result_bytes = build_result( + job, + step_states, + ) + + result_path = results_dir / "result.json" + + _atomic_write( + result_path, + result_bytes, + ) + + result_sha256 = _sha256_file( + result_path + ) + + if result_sha256 != _sha256_bytes( + result_bytes + ): + raise ResultPackageError( + "Written result.json SHA-256 mismatch." + ) + + outbox.mkdir( + parents=True, + exist_ok=True, + ) + + job_id = job["job_id"] + + destination = ( + outbox / f"RESULT-{job_dir.name}.zip" + ) + + if destination.exists(): + raise ResultPackageError( + f"Result package already exists: " + f"{destination}" + ) + + fd, temporary = tempfile.mkstemp( + prefix=f".RESULT-{job_dir.name}.", + suffix=".zip.tmp", + dir=str(outbox), + ) + + temporary_path = Path(temporary) + + try: + os.close(fd) + + with zipfile.ZipFile( + temporary_path, + mode="w", + compression=zipfile.ZIP_DEFLATED, + ) as archive: + archive.write( + result_path, + "result.json", + ) + archive.write( + show_path, + "hashcat-show.txt", + ) + + temporary_path.replace( + destination + ) + + except BaseException: + temporary_path.unlink( + missing_ok=True + ) + raise + + if logger is not None: + logger.info( + "Result package created: %s " + "result_sha256=%s " + "show_sha256=%s", + destination.name, + result["result_sha256"], + _sha256_file(show_path), + ) + + return destination diff --git a/cracklab/client/state.py b/cracklab/client/state.py new file mode 100644 index 0000000..b4553e3 --- /dev/null +++ b/cracklab/client/state.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +JOB_STATUS_QUEUED = "QUEUED" +JOB_STATUS_RUNNING = "RUNNING" +JOB_STATUS_COMPLETED = "COMPLETED" +JOB_STATUS_PARTIAL = "PARTIAL" +JOB_STATUS_FAILED = "FAILED" + +STEP_STATUS_PENDING = "PENDING" +STEP_STATUS_RUNNING = "RUNNING" +STEP_STATUS_COMPLETED = "COMPLETED" +STEP_STATUS_PARTIAL = "PARTIAL" +STEP_STATUS_FAILED = "FAILED" + + +def utc_now() -> str: + return ( + datetime.now(timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z") + ) + + +class StateError(RuntimeError): + pass + + +def _atomic_write_json( + path: Path, + data: dict[str, Any], +) -> None: + path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + temp_path = path.with_name( + f".{path.name}.tmp" + ) + + payload = json.dumps( + data, + ensure_ascii=False, + indent=2, + ) + "\n" + + temp_path.write_text( + payload, + encoding="utf-8", + ) + + temp_path.replace(path) + + +def _load_json(path: Path) -> dict[str, Any]: + try: + data = json.loads( + path.read_text( + encoding="utf-8", + ) + ) + except FileNotFoundError as exc: + raise StateError( + f"Missing state file: {path}" + ) from exc + except json.JSONDecodeError as exc: + raise StateError( + f"Invalid JSON in state file {path}: {exc}" + ) from exc + + if not isinstance(data, dict): + raise StateError( + f"State file must contain an object: {path}" + ) + + return data + + +def state_path(job_dir: Path) -> Path: + return job_dir / "state" / "client_state.json" + + +def load_state(job_dir: Path) -> dict[str, Any]: + return _load_json( + state_path(job_dir) + ) + + +def save_state( + job_dir: Path, + state: dict[str, Any], +) -> None: + _atomic_write_json( + state_path(job_dir), + state, + ) + + +def initialize_state( + job_dir: Path, + job: dict[str, Any], +) -> dict[str, Any]: + job_id = job.get("job_id") + + if not isinstance(job_id, str) or not job_id: + raise StateError( + "Job is missing a valid job_id." + ) + + steps = job.get("steps") + + if not isinstance(steps, list) or not steps: + raise StateError( + f"Job {job_id} has no steps." + ) + + now = utc_now() + + state: dict[str, Any] = { + "job_id": job_id, + "status": JOB_STATUS_QUEUED, + "created_at": now, + "updated_at": now, + "steps": {}, + } + + for step in steps: + step_no = step.get("step_no") + + if not isinstance(step_no, int): + raise StateError( + f"Job {job_id} contains invalid step_no." + ) + + state["steps"][str(step_no)] = { + "step_no": step_no, + "step_id": step.get("step_id"), + "session_name": step.get("session_name"), + "status": STEP_STATUS_PENDING, + "started_at": None, + "completed_at": None, + "exit_code": None, + "restore_seen": False, + "error": None, + } + + save_state( + job_dir, + state, + ) + + return state + + +def update_job_state( + job_dir: Path, + status: str, + *, + error: str | None = None, +) -> dict[str, Any]: + state = load_state(job_dir) + + state["status"] = status + state["updated_at"] = utc_now() + + if error is not None: + state["error"] = error + elif status != JOB_STATUS_FAILED: + state.pop("error", None) + + save_state( + job_dir, + state, + ) + + return state + + +def update_step_state( + job_dir: Path, + step_no: int, + status: str, + *, + exit_code: int | None = None, + restore_seen: bool | None = None, + error: str | None = None, + started: bool = False, + completed: bool = False, +) -> dict[str, Any]: + state = load_state(job_dir) + + key = str(step_no) + steps = state.get("steps") + + if not isinstance(steps, dict) or key not in steps: + raise StateError( + f"Unknown step {step_no}." + ) + + step_state = steps[key] + + step_state["status"] = status + + if started: + step_state["started_at"] = utc_now() + + if completed: + step_state["completed_at"] = utc_now() + + if exit_code is not None: + step_state["exit_code"] = exit_code + + if restore_seen is not None: + step_state["restore_seen"] = restore_seen + + if error is not None: + step_state["error"] = error + elif status != STEP_STATUS_FAILED: + step_state["error"] = None + + state["updated_at"] = utc_now() + + save_state( + job_dir, + state, + ) + + return state + + +def get_step_state( + job_dir: Path, + step_no: int, +) -> dict[str, Any]: + state = load_state(job_dir) + + steps = state.get("steps") + + if not isinstance(steps, dict): + raise StateError( + f"Invalid steps state in {job_dir}." + ) + + step = steps.get(str(step_no)) + + if not isinstance(step, dict): + raise StateError( + f"Unknown step {step_no}." + ) + + return step diff --git a/cracklab/gui.bat b/cracklab/gui.bat new file mode 100644 index 0000000..7df2799 --- /dev/null +++ b/cracklab/gui.bat @@ -0,0 +1,12 @@ +@echo off +setlocal + +cd /d "%~dp0" + +echo CrackLab GUI is not implemented yet. +echo The client is currently available through client.bat. +echo. + +pause + +endlocal diff --git a/cracklab/server/db/__init__.py b/cracklab/server/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/cracklab/server/db/connection.py b/cracklab/server/db/connection.py new file mode 100644 index 0000000..b16bc61 --- /dev/null +++ b/cracklab/server/db/connection.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import sqlite3 +from pathlib import Path + + +PROJECT_ROOT = Path(__file__).resolve().parents[3] +DEFAULT_DATABASE_PATH = PROJECT_ROOT / "database" / "wifi.sqlite3" + + +def connect_database(path: Path | None = None) -> sqlite3.Connection: + database_path = path or DEFAULT_DATABASE_PATH + + if not database_path.is_file(): + raise FileNotFoundError(f"Database not found: {database_path}") + + conn = sqlite3.connect(database_path) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys=ON") + conn.execute("PRAGMA busy_timeout=5000") + return conn diff --git a/cracklab/server/db/migrations.py b/cracklab/server/db/migrations.py new file mode 100644 index 0000000..d95ff7e --- /dev/null +++ b/cracklab/server/db/migrations.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import hashlib +import sqlite3 +from pathlib import Path + +from .connection import DEFAULT_DATABASE_PATH, connect_database + + +MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" + + +def _migration_checksum(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as fh: + for chunk in iter(lambda: fh.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _ensure_migrations_table(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS cracklab_migrations ( + id TEXT PRIMARY KEY, + checksum TEXT NOT NULL, + applied_at TEXT NOT NULL + ) + """ + ) + + +def _load_applied_migrations( + conn: sqlite3.Connection, +) -> dict[str, tuple[str, str]]: + rows = conn.execute( + """ + SELECT id, checksum, applied_at + FROM cracklab_migrations + """ + ).fetchall() + + return { + migration_id: (checksum, applied_at) + for migration_id, checksum, applied_at in rows + } + + +def _migration_files(migrations_dir: Path) -> list[Path]: + return sorted( + path + for path in migrations_dir.glob("*.sql") + if path.is_file() + ) + + +def migrate_database( + path: Path | None = None, + migrations_dir: Path | None = None, +) -> list[str]: + conn = connect_database(path) + + try: + _ensure_migrations_table(conn) + conn.commit() + + applied = _load_applied_migrations(conn) + migration_directory = migrations_dir or MIGRATIONS_DIR + migrations = _migration_files(migration_directory) + newly_applied: list[str] = [] + + for migration_path in migrations: + migration_id = migration_path.name + checksum = _migration_checksum(migration_path) + + if migration_id in applied: + stored_checksum, _ = applied[migration_id] + + if stored_checksum != checksum: + raise RuntimeError( + f"Migration checksum mismatch: {migration_id}" + ) + + continue + + sql = migration_path.read_text(encoding="utf-8") + + transaction_sql = f""" +BEGIN; +{sql} +INSERT INTO cracklab_migrations ( + id, + checksum, + applied_at +) +VALUES ( + '{migration_id.replace("'", "''")}', + '{checksum}', + strftime('%Y-%m-%dT%H:%M:%fZ', 'now') +); +COMMIT; +""" + + try: + conn.executescript(transaction_sql) + except Exception: + conn.rollback() + raise + + applied[migration_id] = ( + checksum, + "", + ) + newly_applied.append(migration_id) + + return newly_applied + + finally: + conn.close() + + +def main() -> int: + applied = migrate_database(DEFAULT_DATABASE_PATH) + + for migration_id in applied: + print(migration_id) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cracklab/server/migrations/001_cracklab_v1.sql b/cracklab/server/migrations/001_cracklab_v1.sql new file mode 100644 index 0000000..8760cf6 --- /dev/null +++ b/cracklab/server/migrations/001_cracklab_v1.sql @@ -0,0 +1,248 @@ +PRAGMA foreign_keys = ON; + +CREATE TABLE IF NOT EXISTS crack_methods ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT, + created_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS crack_method_versions ( + method_id TEXT NOT NULL, + version INTEGER NOT NULL, + definition_json TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (method_id, version), + FOREIGN KEY (method_id) + REFERENCES crack_methods(id), + CHECK (version > 0) +); + +CREATE TABLE IF NOT EXISTS crack_clients ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + token_hash TEXT, + status TEXT NOT NULL, + created_at TEXT NOT NULL, + last_seen_at TEXT, + metadata_json TEXT, + CHECK (status IN ('ACTIVE', 'DISABLED')) +); + +CREATE TABLE IF NOT EXISTS crack_jobs ( + id TEXT PRIMARY KEY, + method_id TEXT NOT NULL, + method_version INTEGER NOT NULL, + status TEXT NOT NULL, + created_at TEXT NOT NULL, + queued_at TEXT, + started_at TEXT, + completed_at TEXT, + cancelled_at TEXT, + imported_at TEXT, + client_id TEXT, + hash_file_name TEXT NOT NULL, + hash_file_sha256 TEXT NOT NULL, + hash_count INTEGER NOT NULL, + step_count INTEGER NOT NULL, + result_sha256 TEXT, + error TEXT, + FOREIGN KEY (method_id, method_version) + REFERENCES crack_method_versions(method_id, version), + FOREIGN KEY (client_id) + REFERENCES crack_clients(id), + CHECK ( + status IN ( + 'CREATED', + 'QUEUED', + 'RUNNING', + 'PARTIAL', + 'COMPLETED', + 'FAILED', + 'CANCELLED' + ) + ), + CHECK (hash_count >= 0), + CHECK (step_count > 0) +); + +CREATE TABLE IF NOT EXISTS crack_job_handshakes ( + job_id TEXT NOT NULL, + handshake_id INTEGER NOT NULL, + hash22000 TEXT NOT NULL, + access_point_id INTEGER, + PRIMARY KEY (job_id, handshake_id), + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + FOREIGN KEY (handshake_id) + REFERENCES handshakes(id), + FOREIGN KEY (access_point_id) + REFERENCES access_points(id) +); + +CREATE TABLE IF NOT EXISTS crack_job_steps ( + job_id TEXT NOT NULL, + step_no INTEGER NOT NULL, + step_id TEXT NOT NULL, + status TEXT NOT NULL, + session_name TEXT NOT NULL, + definition_json TEXT NOT NULL, + started_at TEXT, + completed_at TEXT, + exit_code INTEGER, + restore_seen INTEGER NOT NULL DEFAULT 0, + error TEXT, + PRIMARY KEY (job_id, step_no), + UNIQUE (job_id, step_id), + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + CHECK (step_no > 0), + CHECK ( + status IN ( + 'PENDING', + 'RUNNING', + 'COMPLETED', + 'FAILED', + 'SKIPPED' + ) + ), + CHECK (restore_seen IN (0, 1)) +); + +CREATE TABLE IF NOT EXISTS crack_reservations ( + id TEXT PRIMARY KEY, + handshake_id INTEGER NOT NULL, + method_id TEXT NOT NULL, + method_version INTEGER NOT NULL, + job_id TEXT NOT NULL, + client_id TEXT, + status TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT, + released_at TEXT, + FOREIGN KEY (handshake_id) + REFERENCES handshakes(id), + FOREIGN KEY (method_id, method_version) + REFERENCES crack_method_versions(method_id, version), + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + FOREIGN KEY (client_id) + REFERENCES crack_clients(id), + CHECK ( + status IN ( + 'ACTIVE', + 'RELEASED', + 'EXPIRED', + 'CANCELLED' + ) + ) +); + +CREATE TABLE IF NOT EXISTS crack_attempts ( + handshake_id INTEGER NOT NULL, + method_id TEXT NOT NULL, + method_version INTEGER NOT NULL, + job_id TEXT NOT NULL, + status TEXT NOT NULL, + completed_at TEXT, + PRIMARY KEY (handshake_id, method_id, method_version), + FOREIGN KEY (handshake_id) + REFERENCES handshakes(id), + FOREIGN KEY (method_id, method_version) + REFERENCES crack_method_versions(method_id, version), + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + CHECK (status = 'COMPLETED') +); + +CREATE TABLE IF NOT EXISTS crack_results ( + job_id TEXT PRIMARY KEY, + status TEXT NOT NULL, + result_json TEXT NOT NULL, + imported_at TEXT NOT NULL, + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + CHECK ( + status IN ( + 'COMPLETED', + 'PARTIAL', + 'FAILED', + 'CANCELLED' + ) + ) +); + +CREATE TABLE IF NOT EXISTS crack_audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + event_type TEXT NOT NULL, + job_id TEXT, + client_id TEXT, + handshake_id INTEGER, + method_id TEXT, + method_version INTEGER, + details_json TEXT, + FOREIGN KEY (job_id) + REFERENCES crack_jobs(id), + FOREIGN KEY (client_id) + REFERENCES crack_clients(id), + FOREIGN KEY (handshake_id) + REFERENCES handshakes(id), + FOREIGN KEY (method_id, method_version) + REFERENCES crack_method_versions(method_id, version) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_crack_reservations_active +ON crack_reservations(handshake_id, method_id, method_version) +WHERE status = 'ACTIVE'; + +CREATE INDEX IF NOT EXISTS idx_crack_method_versions_method +ON crack_method_versions(method_id, version); + +CREATE INDEX IF NOT EXISTS idx_crack_jobs_status +ON crack_jobs(status); + +CREATE INDEX IF NOT EXISTS idx_crack_jobs_method_status +ON crack_jobs(method_id, method_version, status); + +CREATE INDEX IF NOT EXISTS idx_crack_jobs_client_status +ON crack_jobs(client_id, status); + +CREATE INDEX IF NOT EXISTS idx_crack_job_handshakes_handshake +ON crack_job_handshakes(handshake_id); + +CREATE INDEX IF NOT EXISTS idx_crack_job_handshakes_job +ON crack_job_handshakes(job_id); + +CREATE INDEX IF NOT EXISTS idx_crack_job_steps_status +ON crack_job_steps(job_id, status); + +CREATE INDEX IF NOT EXISTS idx_crack_reservations_handshake +ON crack_reservations(handshake_id, method_id, method_version); + +CREATE INDEX IF NOT EXISTS idx_crack_reservations_job +ON crack_reservations(job_id, status); + +CREATE INDEX IF NOT EXISTS idx_crack_reservations_client +ON crack_reservations(client_id, status); + +CREATE INDEX IF NOT EXISTS idx_crack_attempts_method +ON crack_attempts(method_id, method_version, status); + +CREATE INDEX IF NOT EXISTS idx_crack_attempts_job +ON crack_attempts(job_id); + +CREATE INDEX IF NOT EXISTS idx_crack_attempts_handshake +ON crack_attempts(handshake_id); + +CREATE INDEX IF NOT EXISTS idx_crack_audit_job +ON crack_audit_log(job_id, created_at); + +CREATE INDEX IF NOT EXISTS idx_crack_audit_client +ON crack_audit_log(client_id, created_at); + +CREATE INDEX IF NOT EXISTS idx_crack_audit_handshake +ON crack_audit_log(handshake_id, created_at); + +CREATE INDEX IF NOT EXISTS idx_crack_audit_event +ON crack_audit_log(event_type, created_at); diff --git a/cracklab/server/repositories/__init__.py b/cracklab/server/repositories/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/cracklab/server/repositories/attempts.py b/cracklab/server/repositories/attempts.py new file mode 100644 index 0000000..b9a4554 --- /dev/null +++ b/cracklab/server/repositories/attempts.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +import sqlite3 +from datetime import datetime, timezone + + +class AttemptsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_attempt( + self, + handshake_id: int, + method_id: str, + method_version: int, + job_id: str, + completed_at: str | None = None, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_attempts ( + handshake_id, + method_id, + method_version, + job_id, + status, + completed_at + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + handshake_id, + method_id, + method_version, + job_id, + "COMPLETED", + completed_at or self._now(), + ), + ) + + def get_attempt( + self, + handshake_id: int, + method_id: str, + method_version: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + handshake_id, + method_id, + method_version, + job_id, + status, + completed_at + FROM crack_attempts + WHERE handshake_id = ? + AND method_id = ? + AND method_version = ? + """, + ( + handshake_id, + method_id, + method_version, + ), + ).fetchone() + + def has_completed( + self, + handshake_id: int, + method_id: str, + method_version: int, + ) -> bool: + row = self._conn.execute( + """ + SELECT 1 + FROM crack_attempts + WHERE handshake_id = ? + AND method_id = ? + AND method_version = ? + AND status = 'COMPLETED' + """, + ( + handshake_id, + method_id, + method_version, + ), + ).fetchone() + + return row is not None + + def list_handshake_attempts( + self, + handshake_id: int, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + handshake_id, + method_id, + method_version, + job_id, + status, + completed_at + FROM crack_attempts + WHERE handshake_id = ? + ORDER BY method_id, method_version + """, + (handshake_id,), + ).fetchall() + + def list_job_attempts( + self, + job_id: str, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + handshake_id, + method_id, + method_version, + job_id, + status, + completed_at + FROM crack_attempts + WHERE job_id = ? + ORDER BY handshake_id, method_id, method_version + """, + (job_id,), + ).fetchall() + + def list_method_attempts( + self, + method_id: str, + method_version: int, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + handshake_id, + method_id, + method_version, + job_id, + status, + completed_at + FROM crack_attempts + WHERE method_id = ? + AND method_version = ? + ORDER BY handshake_id + """, + ( + method_id, + method_version, + ), + ).fetchall() diff --git a/cracklab/server/repositories/audit.py b/cracklab/server/repositories/audit.py new file mode 100644 index 0000000..4d17a7b --- /dev/null +++ b/cracklab/server/repositories/audit.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timezone +from typing import Any + + +class AuditRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_event( + self, + event_type: str, + job_id: str | None = None, + client_id: str | None = None, + handshake_id: int | None = None, + method_id: str | None = None, + method_version: int | None = None, + details: dict[str, Any] | None = None, + created_at: str | None = None, + ) -> int: + cursor = self._conn.execute( + """ + INSERT INTO crack_audit_log ( + created_at, + event_type, + job_id, + client_id, + handshake_id, + method_id, + method_version, + details_json + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + created_at or self._now(), + event_type, + job_id, + client_id, + handshake_id, + method_id, + method_version, + ( + json.dumps( + details, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + if details is not None + else None + ), + ), + ) + + return int(cursor.lastrowid) + + def get_event( + self, + event_id: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + created_at, + event_type, + job_id, + client_id, + handshake_id, + method_id, + method_version, + details_json + FROM crack_audit_log + WHERE id = ? + """, + (event_id,), + ).fetchone() + + def list_events( + self, + event_type: str | None = None, + job_id: str | None = None, + client_id: str | None = None, + handshake_id: int | None = None, + method_id: str | None = None, + method_version: int | None = None, + ) -> list[sqlite3.Row]: + query = """ + SELECT + id, + created_at, + event_type, + job_id, + client_id, + handshake_id, + method_id, + method_version, + details_json + FROM crack_audit_log + WHERE 1 = 1 + """ + params: list[Any] = [] + + if event_type is not None: + query += "\n AND event_type = ?" + params.append(event_type) + + if job_id is not None: + query += "\n AND job_id = ?" + params.append(job_id) + + if client_id is not None: + query += "\n AND client_id = ?" + params.append(client_id) + + if handshake_id is not None: + query += "\n AND handshake_id = ?" + params.append(handshake_id) + + if method_id is not None: + query += "\n AND method_id = ?" + params.append(method_id) + + if method_version is not None: + query += "\n AND method_version = ?" + params.append(method_version) + + query += "\n ORDER BY created_at DESC, id DESC" + + return self._conn.execute(query, params).fetchall() + + @staticmethod + def decode_details(row: sqlite3.Row) -> dict[str, Any] | None: + if row["details_json"] is None: + return None + + return json.loads(row["details_json"]) diff --git a/cracklab/server/repositories/clients.py b/cracklab/server/repositories/clients.py new file mode 100644 index 0000000..bbccd18 --- /dev/null +++ b/cracklab/server/repositories/clients.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timezone +from typing import Any + + +class ClientsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_client( + self, + client_id: str, + name: str, + token_hash: str | None = None, + status: str = "ACTIVE", + metadata: dict[str, Any] | None = None, + ) -> None: + metadata_json = ( + json.dumps( + metadata, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + if metadata is not None + else None + ) + + self._conn.execute( + """ + INSERT INTO crack_clients ( + id, + name, + token_hash, + status, + created_at, + last_seen_at, + metadata_json + ) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, + ( + client_id, + name, + token_hash, + status, + self._now(), + None, + metadata_json, + ), + ) + + def get_client(self, client_id: str) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + name, + token_hash, + status, + created_at, + last_seen_at, + metadata_json + FROM crack_clients + WHERE id = ? + """, + (client_id,), + ).fetchone() + + def list_clients(self) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + id, + name, + token_hash, + status, + created_at, + last_seen_at, + metadata_json + FROM crack_clients + ORDER BY id + """ + ).fetchall() + + def update_last_seen(self, client_id: str) -> None: + self._conn.execute( + """ + UPDATE crack_clients + SET last_seen_at = ? + WHERE id = ? + """, + ( + self._now(), + client_id, + ), + ) + + def update_status(self, client_id: str, status: str) -> None: + self._conn.execute( + """ + UPDATE crack_clients + SET status = ? + WHERE id = ? + """, + ( + status, + client_id, + ), + ) diff --git a/cracklab/server/repositories/credentials.py b/cracklab/server/repositories/credentials.py new file mode 100644 index 0000000..b9fb51e --- /dev/null +++ b/cracklab/server/repositories/credentials.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import sqlite3 +from datetime import datetime, timezone + + +class CredentialsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def get_credential( + self, + access_point_id: int, + handshake_id: int, + password: str, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + access_point_id, + handshake_id, + password, + source, + created_at, + verified + FROM credentials + WHERE access_point_id = ? + AND handshake_id = ? + AND password = ? + LIMIT 1 + """, + ( + access_point_id, + handshake_id, + password, + ), + ).fetchone() + + def create_hashcat_credential( + self, + access_point_id: int, + handshake_id: int, + password: str, + ) -> int: + cursor = self._conn.execute( + """ + INSERT INTO credentials ( + access_point_id, + handshake_id, + password, + source, + created_at, + verified + ) + VALUES (?, ?, ?, 'hashcat', ?, 0) + """, + ( + access_point_id, + handshake_id, + password, + self._now(), + ), + ) + + self._conn.execute( + """ + UPDATE access_points + SET is_cracked = 1 + WHERE id = ? + """, + (access_point_id,), + ) + + return int(cursor.lastrowid) + + def mark_access_point_cracked( + self, + access_point_id: int, + ) -> None: + self._conn.execute( + """ + UPDATE access_points + SET is_cracked = 1 + WHERE id = ? + """, + (access_point_id,), + ) diff --git a/cracklab/server/repositories/handshakes.py b/cracklab/server/repositories/handshakes.py new file mode 100644 index 0000000..ae9c7c4 --- /dev/null +++ b/cracklab/server/repositories/handshakes.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import sqlite3 +from typing import Any + + +class HandshakesRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + def list_eligible( + self, + method_id: str, + method_version: int, + limit: int, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + h.id AS handshake_id, + h.hash22000, + h.access_point_id, + h.captured_at + FROM handshakes AS h + WHERE h.hash22000 IS NOT NULL + AND TRIM(h.hash22000) <> '' + AND NOT EXISTS ( + SELECT 1 + FROM credentials AS c + WHERE c.handshake_id = h.id + ) + AND NOT EXISTS ( + SELECT 1 + FROM crack_attempts AS a + WHERE a.handshake_id = h.id + AND a.method_id = ? + AND a.method_version = ? + AND a.status = 'COMPLETED' + ) + AND NOT EXISTS ( + SELECT 1 + FROM crack_reservations AS r + WHERE r.handshake_id = h.id + AND r.method_id = ? + AND r.method_version = ? + AND r.status = 'ACTIVE' + ) + ORDER BY h.id + LIMIT ? + """, + ( + method_id, + method_version, + method_id, + method_version, + limit, + ), + ).fetchall() diff --git a/cracklab/server/repositories/jobs.py b/cracklab/server/repositories/jobs.py new file mode 100644 index 0000000..9ca31e1 --- /dev/null +++ b/cracklab/server/repositories/jobs.py @@ -0,0 +1,452 @@ +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timezone +from typing import Any + + +class JobsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_job( + self, + job_id: str, + method_id: str, + method_version: int, + status: str, + hash_file_name: str, + hash_file_sha256: str, + hash_count: int, + step_count: int, + client_id: str | None = None, + ) -> str: + created_at = self._now() + queued_at = created_at if status == "QUEUED" else None + + self._conn.execute( + """ + INSERT INTO crack_jobs ( + id, + method_id, + method_version, + status, + created_at, + queued_at, + started_at, + completed_at, + cancelled_at, + imported_at, + client_id, + hash_file_name, + hash_file_sha256, + hash_count, + step_count, + result_sha256, + error + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + job_id, + method_id, + method_version, + status, + created_at, + queued_at, + None, + None, + None, + None, + client_id, + hash_file_name, + hash_file_sha256, + hash_count, + step_count, + None, + None, + ), + ) + + return created_at + + def get_job(self, job_id: str) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + method_id, + method_version, + status, + created_at, + queued_at, + started_at, + completed_at, + cancelled_at, + imported_at, + client_id, + hash_file_name, + hash_file_sha256, + hash_count, + step_count, + result_sha256, + error + FROM crack_jobs + WHERE id = ? + """, + (job_id,), + ).fetchone() + + def list_jobs( + self, + status: str | None = None, + method_id: str | None = None, + client_id: str | None = None, + ) -> list[sqlite3.Row]: + query = """ + SELECT + id, + method_id, + method_version, + status, + created_at, + queued_at, + started_at, + completed_at, + cancelled_at, + imported_at, + client_id, + hash_file_name, + hash_file_sha256, + hash_count, + step_count, + result_sha256, + error + FROM crack_jobs + WHERE 1 = 1 + """ + params: list[Any] = [] + + if status is not None: + query += "\n AND status = ?" + params.append(status) + + if method_id is not None: + query += "\n AND method_id = ?" + params.append(method_id) + + if client_id is not None: + query += "\n AND client_id = ?" + params.append(client_id) + + query += "\n ORDER BY created_at DESC, id DESC" + + return self._conn.execute(query, params).fetchall() + + def update_job_status( + self, + job_id: str, + status: str, + ) -> None: + now = self._now() + + timestamp_column = { + "QUEUED": "queued_at", + "RUNNING": "started_at", + "COMPLETED": "completed_at", + "CANCELLED": "cancelled_at", + }.get(status) + + if timestamp_column is None: + self._conn.execute( + """ + UPDATE crack_jobs + SET status = ? + WHERE id = ? + """, + ( + status, + job_id, + ), + ) + return + + self._conn.execute( + f""" + UPDATE crack_jobs + SET status = ?, + {timestamp_column} = ? + WHERE id = ? + """, + ( + status, + now, + job_id, + ), + ) + + def assign_client( + self, + job_id: str, + client_id: str | None, + ) -> None: + self._conn.execute( + """ + UPDATE crack_jobs + SET client_id = ? + WHERE id = ? + """, + ( + client_id, + job_id, + ), + ) + + def update_job_result( + self, + job_id: str, + result_sha256: str | None = None, + error: str | None = None, + imported_at: str | None = None, + ) -> None: + self._conn.execute( + """ + UPDATE crack_jobs + SET result_sha256 = ?, + error = ?, + imported_at = ? + WHERE id = ? + """, + ( + result_sha256, + error, + imported_at, + job_id, + ), + ) + + def add_job_handshake( + self, + job_id: str, + handshake_id: int, + hash22000: str, + access_point_id: int | None = None, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_job_handshakes ( + job_id, + handshake_id, + hash22000, + access_point_id + ) + VALUES (?, ?, ?, ?) + """, + ( + job_id, + handshake_id, + hash22000, + access_point_id, + ), + ) + + def get_job_handshake( + self, + job_id: str, + handshake_id: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + job_id, + handshake_id, + hash22000, + access_point_id + FROM crack_job_handshakes + WHERE job_id = ? + AND handshake_id = ? + """, + ( + job_id, + handshake_id, + ), + ).fetchone() + + def list_job_handshakes( + self, + job_id: str, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + job_id, + handshake_id, + hash22000, + access_point_id + FROM crack_job_handshakes + WHERE job_id = ? + ORDER BY handshake_id + """, + (job_id,), + ).fetchall() + + def create_job_step( + self, + job_id: str, + step_no: int, + step_id: str, + status: str, + session_name: str, + definition: dict[str, Any], + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_job_steps ( + job_id, + step_no, + step_id, + status, + session_name, + definition_json, + started_at, + completed_at, + exit_code, + restore_seen, + error + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + job_id, + step_no, + step_id, + status, + session_name, + json.dumps( + definition, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ), + None, + None, + None, + 0, + None, + ), + ) + + def get_job_step( + self, + job_id: str, + step_no: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + job_id, + step_no, + step_id, + status, + session_name, + definition_json, + started_at, + completed_at, + exit_code, + restore_seen, + error + FROM crack_job_steps + WHERE job_id = ? + AND step_no = ? + """, + ( + job_id, + step_no, + ), + ).fetchone() + + def list_job_steps( + self, + job_id: str, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + job_id, + step_no, + step_id, + status, + session_name, + definition_json, + started_at, + completed_at, + exit_code, + restore_seen, + error + FROM crack_job_steps + WHERE job_id = ? + ORDER BY step_no + """, + (job_id,), + ).fetchall() + + def update_job_step( + self, + job_id: str, + step_no: int, + status: str | None = None, + started_at: str | None = None, + completed_at: str | None = None, + exit_code: int | None = None, + restore_seen: bool | None = None, + error: str | None = None, + ) -> None: + fields: list[str] = [] + params: list[Any] = [] + + if status is not None: + fields.append("status = ?") + params.append(status) + + if started_at is not None: + fields.append("started_at = ?") + params.append(started_at) + + if completed_at is not None: + fields.append("completed_at = ?") + params.append(completed_at) + + if exit_code is not None: + fields.append("exit_code = ?") + params.append(exit_code) + + if restore_seen is not None: + fields.append("restore_seen = ?") + params.append(int(restore_seen)) + + if error is not None: + fields.append("error = ?") + params.append(error) + + if not fields: + return + + params.extend((job_id, step_no)) + + self._conn.execute( + f""" + UPDATE crack_job_steps + SET {", ".join(fields)} + WHERE job_id = ? + AND step_no = ? + """, + params, + ) diff --git a/cracklab/server/repositories/methods.py b/cracklab/server/repositories/methods.py new file mode 100644 index 0000000..240e773 --- /dev/null +++ b/cracklab/server/repositories/methods.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timezone +from typing import Any + + +class MethodsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_method( + self, + method_id: str, + name: str, + description: str | None = None, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_methods ( + id, + name, + description, + created_at + ) + VALUES (?, ?, ?, ?) + """, + ( + method_id, + name, + description, + self._now(), + ), + ) + + def get_method(self, method_id: str) -> sqlite3.Row | None: + row = self._conn.execute( + """ + SELECT + id, + name, + description, + created_at + FROM crack_methods + WHERE id = ? + """, + (method_id,), + ).fetchone() + + return row + + def list_methods(self) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + id, + name, + description, + created_at + FROM crack_methods + ORDER BY id + """ + ).fetchall() + + def create_method_version( + self, + method_id: str, + version: int, + definition: dict[str, Any], + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_method_versions ( + method_id, + version, + definition_json, + created_at + ) + VALUES (?, ?, ?, ?) + """, + ( + method_id, + version, + json.dumps( + definition, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ), + self._now(), + ), + ) + + def get_method_version( + self, + method_id: str, + version: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + method_id, + version, + definition_json, + created_at + FROM crack_method_versions + WHERE method_id = ? + AND version = ? + """, + (method_id, version), + ).fetchone() + + def list_method_versions( + self, + method_id: str, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + method_id, + version, + definition_json, + created_at + FROM crack_method_versions + WHERE method_id = ? + ORDER BY version + """, + (method_id,), + ).fetchall() + + def get_next_method_version(self, method_id: str) -> int: + row = self._conn.execute( + """ + SELECT COALESCE(MAX(version), 0) + 1 + FROM crack_method_versions + WHERE method_id = ? + """, + (method_id,), + ).fetchone() + + return int(row[0]) diff --git a/cracklab/server/repositories/reservations.py b/cracklab/server/repositories/reservations.py new file mode 100644 index 0000000..cdb5395 --- /dev/null +++ b/cracklab/server/repositories/reservations.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +import sqlite3 +from datetime import datetime, timezone + + +class ReservationsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_reservation( + self, + reservation_id: str, + handshake_id: int, + method_id: str, + method_version: int, + job_id: str, + client_id: str | None = None, + expires_at: str | None = None, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_reservations ( + id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + status, + created_at, + expires_at, + released_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + reservation_id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + "ACTIVE", + self._now(), + expires_at, + None, + ), + ) + + def get_reservation( + self, + reservation_id: str, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + status, + created_at, + expires_at, + released_at + FROM crack_reservations + WHERE id = ? + """, + (reservation_id,), + ).fetchone() + + def get_active_reservation( + self, + handshake_id: int, + method_id: str, + method_version: int, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + status, + created_at, + expires_at, + released_at + FROM crack_reservations + WHERE handshake_id = ? + AND method_id = ? + AND method_version = ? + AND status = 'ACTIVE' + """, + ( + handshake_id, + method_id, + method_version, + ), + ).fetchone() + + def list_job_reservations( + self, + job_id: str, + ) -> list[sqlite3.Row]: + return self._conn.execute( + """ + SELECT + id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + status, + created_at, + expires_at, + released_at + FROM crack_reservations + WHERE job_id = ? + ORDER BY created_at, id + """, + (job_id,), + ).fetchall() + + def list_client_reservations( + self, + client_id: str, + status: str | None = None, + ) -> list[sqlite3.Row]: + query = """ + SELECT + id, + handshake_id, + method_id, + method_version, + job_id, + client_id, + status, + created_at, + expires_at, + released_at + FROM crack_reservations + WHERE client_id = ? + """ + params: list[object] = [client_id] + + if status is not None: + query += "\n AND status = ?" + params.append(status) + + query += "\n ORDER BY created_at, id" + + return self._conn.execute(query, params).fetchall() + + def update_status( + self, + reservation_id: str, + status: str, + released_at: str | None = None, + ) -> None: + if released_at is None and status in { + "RELEASED", + "EXPIRED", + "CANCELLED", + }: + released_at = self._now() + + self._conn.execute( + """ + UPDATE crack_reservations + SET status = ?, + released_at = ? + WHERE id = ? + """, + ( + status, + released_at, + reservation_id, + ), + ) + + def update_expires_at( + self, + reservation_id: str, + expires_at: str | None, + ) -> None: + self._conn.execute( + """ + UPDATE crack_reservations + SET expires_at = ? + WHERE id = ? + """, + ( + expires_at, + reservation_id, + ), + ) diff --git a/cracklab/server/repositories/results.py b/cracklab/server/repositories/results.py new file mode 100644 index 0000000..aa6a381 --- /dev/null +++ b/cracklab/server/repositories/results.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timezone +from typing import Any + + +class ResultsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace( + "+00:00", + "Z", + ) + + def create_result( + self, + job_id: str, + status: str, + result: dict[str, Any], + imported_at: str | None = None, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_results ( + job_id, + status, + result_json, + imported_at + ) + VALUES (?, ?, ?, ?) + """, + ( + job_id, + status, + json.dumps( + result, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ), + imported_at or self._now(), + ), + ) + + def get_result( + self, + job_id: str, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + job_id, + status, + result_json, + imported_at + FROM crack_results + WHERE job_id = ? + """, + (job_id,), + ).fetchone() + + def list_results( + self, + status: str | None = None, + ) -> list[sqlite3.Row]: + query = """ + SELECT + job_id, + status, + result_json, + imported_at + FROM crack_results + WHERE 1 = 1 + """ + params: list[Any] = [] + + if status is not None: + query += "\n AND status = ?" + params.append(status) + + query += "\n ORDER BY imported_at DESC, job_id DESC" + + return self._conn.execute(query, params).fetchall() + + @staticmethod + def decode_result(row: sqlite3.Row) -> dict[str, Any]: + return json.loads(row["result_json"]) diff --git a/cracklab/server/services/__init__.py b/cracklab/server/services/__init__.py new file mode 100644 index 0000000..b97ba3b --- /dev/null +++ b/cracklab/server/services/__init__.py @@ -0,0 +1,12 @@ +from .job_issuance import JobIssuanceService, IssuedJob +from .job_result import JobResultError, JobResultService +from .methods import MethodService, MethodServiceError + +__all__ = [ + "IssuedJob", + "JobIssuanceService", + "JobResultError", + "JobResultService", + "MethodService", + "MethodServiceError", +] diff --git a/cracklab/server/services/job_export.py b/cracklab/server/services/job_export.py new file mode 100644 index 0000000..fcd968b --- /dev/null +++ b/cracklab/server/services/job_export.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import hashlib +import json +import tempfile +import zipfile +from datetime import datetime, timezone +from pathlib import Path +from zoneinfo import ZoneInfo + +import yaml + +from cracklab.server.repositories.jobs import JobsRepository +from cracklab.server.repositories.methods import MethodsRepository +from cracklab.server.services.method_definition import ( + validate_method_definition, +) + + +PROJECT_ROOT = Path(__file__).resolve().parents[3] +CONFIG_FILE = PROJECT_ROOT / "config" / "config.yaml" + + +class JobExportError(RuntimeError): + pass + + +class JobExportService: + def __init__( + self, + conn, + timezone_name: str | None = None, + ) -> None: + self._conn = conn + self._jobs = JobsRepository(conn) + self._methods = MethodsRepository(conn) + self._timezone_name = ( + timezone_name + if timezone_name is not None + else self._load_timezone() + ) + + try: + self._timezone = ZoneInfo(self._timezone_name) + except Exception as exc: + raise JobExportError( + f"Invalid timezone: {self._timezone_name}" + ) from exc + + @staticmethod + def _load_timezone() -> str: + if not CONFIG_FILE.is_file(): + raise JobExportError( + f"Configuration file not found: {CONFIG_FILE}" + ) + + try: + with CONFIG_FILE.open( + "r", + encoding="utf-8", + ) as fp: + config = yaml.safe_load(fp) or {} + except Exception as exc: + raise JobExportError( + f"Failed to load configuration: {CONFIG_FILE}" + ) from exc + + timezone_name = config.get( + "timezone", + "Europe/Moscow", + ) + + if not isinstance(timezone_name, str) or not timezone_name: + raise JobExportError( + "Configuration timezone must be a non-empty string" + ) + + return timezone_name + + @staticmethod + def _parse_utc(text: str) -> datetime: + try: + value = datetime.fromisoformat(text) + except ValueError as exc: + raise JobExportError( + f"Invalid job created_at: {text}" + ) from exc + + if value.tzinfo is None: + raise JobExportError( + f"Job timestamp is not timezone-aware: {text}" + ) + + value = value.astimezone(timezone.utc) + + return value + + @staticmethod + def _unique_hash_content(rows) -> tuple[str, int]: + unique_hashes: list[str] = [] + seen: set[str] = set() + + for row in rows: + hash22000 = str(row["hash22000"]).strip() + + if not hash22000: + raise JobExportError( + "Job contains an empty hash22000 value" + ) + + if hash22000 in seen: + continue + + seen.add(hash22000) + unique_hashes.append(hash22000) + + content = "\n".join(unique_hashes) + "\n" + + return content, len(unique_hashes) + + @staticmethod + def _sha256_text(content: str) -> str: + return hashlib.sha256( + content.encode("utf-8") + ).hexdigest() + + @staticmethod + def _json_bytes(data: dict) -> bytes: + return ( + json.dumps( + data, + ensure_ascii=False, + indent=2, + ) + + "\n" + ).encode("utf-8") + + def export_job( + self, + job_id: str, + output_dir: str | Path, + ) -> Path: + job = self._jobs.get_job(job_id) + + if job is None: + raise JobExportError( + f"Job not found: {job_id}" + ) + + method_version = self._methods.get_method_version( + str(job["method_id"]), + int(job["method_version"]), + ) + + if method_version is None: + raise JobExportError( + "Method version not found: " + f"{job['method_id']} v{job['method_version']}" + ) + + try: + method_definition = json.loads( + method_version["definition_json"] + ) + validate_method_definition( + method_definition + ) + except (json.JSONDecodeError, TypeError, ValueError) as exc: + raise JobExportError( + "Invalid method version definition: " + f"{job['method_id']} v{job['method_version']}" + ) from exc + + hash_mode = int( + method_definition["hash_mode"] + ) + + handshake_rows = self._jobs.list_job_handshakes( + job_id + ) + step_rows = self._jobs.list_job_steps( + job_id + ) + + hash_content, hash_count = self._unique_hash_content( + handshake_rows + ) + + hash_sha256 = self._sha256_text( + hash_content + ) + + if hash_sha256 != job["hash_file_sha256"]: + raise JobExportError( + "Job hash snapshot SHA-256 mismatch: " + f"expected {job['hash_file_sha256']}, " + f"calculated {hash_sha256}" + ) + + if hash_count != int(job["hash_count"]): + raise JobExportError( + "Job hash count mismatch: " + f"expected {job['hash_count']}, " + f"calculated {hash_count}" + ) + + if len(handshake_rows) == 0: + raise JobExportError( + f"Job contains no handshake snapshot: {job_id}" + ) + + if len(step_rows) != int(job["step_count"]): + raise JobExportError( + "Job step count mismatch: " + f"expected {job['step_count']}, " + f"calculated {len(step_rows)}" + ) + + created_at = self._parse_utc( + str(job["created_at"]) + ) + + local_created_at = created_at.astimezone( + self._timezone + ) + + zip_filename = ( + "JOB-" + + local_created_at.strftime( + "%d-%m-%Y_%H%M%S" + ) + + "-" + + str(job["id"]).removeprefix("JOB-") + + ".zip" + ) + + job_json = { + "job_id": str(job["id"]), + "created_at": str(job["created_at"]), + "method_id": str(job["method_id"]), + "method_version": int(job["method_version"]), + "hash_mode": hash_mode, + "hash_file_name": str(job["hash_file_name"]), + "hash_file_sha256": str(job["hash_file_sha256"]), + "hash_count": int(job["hash_count"]), + "handshake_count": len(handshake_rows), + "step_count": int(job["step_count"]), + "handshakes": [ + { + "handshake_id": int(row["handshake_id"]), + "hash22000": str(row["hash22000"]), + "access_point_id": ( + int(row["access_point_id"]) + if row["access_point_id"] is not None + else None + ), + } + for row in handshake_rows + ], + "steps": [ + { + "step_no": int(row["step_no"]), + "step_id": str(row["step_id"]), + "session_name": str(row["session_name"]), + "definition": json.loads( + row["definition_json"] + ), + } + for row in step_rows + ], + } + + job_bytes = self._json_bytes(job_json) + hash_bytes = hash_content.encode("utf-8") + + manifest_files = [ + { + "path": "job.json", + "size": len(job_bytes), + "sha256": hashlib.sha256( + job_bytes + ).hexdigest(), + }, + { + "path": f"hashes/{job['hash_file_name']}", + "size": len(hash_bytes), + "sha256": hashlib.sha256( + hash_bytes + ).hexdigest(), + }, + ] + + manifest = { + "format_version": 1, + "job_id": str(job["id"]), + "created_at": str(job["created_at"]), + "zip_filename": zip_filename, + "files": manifest_files, + } + + manifest_bytes = self._json_bytes( + manifest + ) + + output_path = Path(output_dir) + output_path.mkdir( + parents=True, + exist_ok=True, + ) + + final_path = output_path / zip_filename + + with tempfile.NamedTemporaryFile( + mode="wb", + suffix=".zip", + dir=output_path, + delete=False, + ) as tmp: + temporary_path = Path(tmp.name) + + try: + with zipfile.ZipFile( + temporary_path, + mode="w", + compression=zipfile.ZIP_DEFLATED, + ) as archive: + archive.writestr( + "job.json", + job_bytes, + ) + archive.writestr( + f"hashes/{job['hash_file_name']}", + hash_bytes, + ) + archive.writestr( + "manifest.json", + manifest_bytes, + ) + + temporary_path.replace(final_path) + + except Exception: + temporary_path.unlink( + missing_ok=True + ) + raise + + return final_path diff --git a/cracklab/server/services/job_issuance.py b/cracklab/server/services/job_issuance.py new file mode 100644 index 0000000..4cf9331 --- /dev/null +++ b/cracklab/server/services/job_issuance.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import hashlib +import json +import sqlite3 +import uuid +from dataclasses import dataclass +from typing import Any + +from cracklab.server.repositories.audit import AuditRepository +from cracklab.server.repositories.handshakes import HandshakesRepository +from cracklab.server.repositories.jobs import JobsRepository +from cracklab.server.repositories.methods import MethodsRepository +from cracklab.server.repositories.reservations import ReservationsRepository +from cracklab.server.services.method_definition import ( + MethodDefinitionError, + validate_method_definition, +) + + +class JobIssuanceError(ValueError): + pass + + +@dataclass(frozen=True) +class IssuedJob: + job_id: str + method_id: str + method_version: int + status: str + created_at: str + hash_file_name: str + hash_file_sha256: str + hash_count: int + handshake_count: int + step_count: int + hash_content: str + handshake_ids: tuple[int, ...] + steps: tuple[dict[str, Any], ...] + + +class JobIssuanceService: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + self._methods = MethodsRepository(conn) + self._handshakes = HandshakesRepository(conn) + self._jobs = JobsRepository(conn) + self._reservations = ReservationsRepository(conn) + self._audit = AuditRepository(conn) + + def issue_job( + self, + method_id: str, + method_version: int, + limit: int, + client_id: str | None = None, + ) -> IssuedJob | None: + if limit <= 0: + raise ValueError("limit must be greater than zero") + + method_version_row = self._methods.get_method_version( + method_id, + method_version, + ) + if method_version_row is None: + raise JobIssuanceError( + f"Method version not found: {method_id} v{method_version}" + ) + + definition = self._decode_method_definition( + method_version_row["definition_json"], + ) + steps = self._build_steps( + method_id, + method_version, + definition, + ) + + self._conn.execute("BEGIN IMMEDIATE") + + try: + handshake_rows = self._handshakes.list_eligible( + method_id, + method_version, + limit, + ) + + if not handshake_rows: + self._conn.rollback() + return None + + job_id = f"JOB-{uuid.uuid4().hex[:12].upper()}" + hash_file_name = f"{job_id}.22000" + + handshake_ids = tuple( + int(row["handshake_id"]) + for row in handshake_rows + ) + + unique_hashes: list[str] = [] + seen_hashes: set[str] = set() + + for row in handshake_rows: + hash22000 = str(row["hash22000"]).strip() + + if hash22000 not in seen_hashes: + seen_hashes.add(hash22000) + unique_hashes.append(hash22000) + + hash_content = "\n".join(unique_hashes) + "\n" + hash_file_sha256 = hashlib.sha256( + hash_content.encode("utf-8"), + ).hexdigest() + + created_at = self._jobs.create_job( + job_id=job_id, + method_id=method_id, + method_version=method_version, + status="QUEUED", + hash_file_name=hash_file_name, + hash_file_sha256=hash_file_sha256, + hash_count=len(unique_hashes), + step_count=len(steps), + client_id=client_id, + ) + + for row in handshake_rows: + self._jobs.add_job_handshake( + job_id=job_id, + handshake_id=int(row["handshake_id"]), + hash22000=str(row["hash22000"]).strip(), + access_point_id=( + int(row["access_point_id"]) + if row["access_point_id"] is not None + else None + ), + ) + + self._reservations.create_reservation( + reservation_id=uuid.uuid4().hex, + handshake_id=int(row["handshake_id"]), + method_id=method_id, + method_version=method_version, + job_id=job_id, + client_id=client_id, + ) + + for step_no, step in enumerate(steps, start=1): + self._jobs.create_job_step( + job_id=job_id, + step_no=step_no, + step_id=step["step_id"], + status="PENDING", + session_name=self._session_name( + job_id, + step["step_id"], + ), + definition=step, + ) + + self._audit.create_event( + event_type="JOB_ISSUED", + job_id=job_id, + client_id=client_id, + method_id=method_id, + method_version=method_version, + details={ + "handshake_count": len(handshake_rows), + "hash_count": len(unique_hashes), + "step_count": len(steps), + "hash_file_name": hash_file_name, + }, + ) + + self._conn.commit() + + except Exception: + self._conn.rollback() + raise + + return IssuedJob( + job_id=job_id, + method_id=method_id, + method_version=method_version, + status="QUEUED", + created_at=created_at, + hash_file_name=hash_file_name, + hash_file_sha256=hash_file_sha256, + hash_count=len(unique_hashes), + handshake_count=len(handshake_rows), + step_count=len(steps), + hash_content=hash_content, + handshake_ids=handshake_ids, + steps=tuple(steps), + ) + + @staticmethod + def _decode_method_definition( + definition_json: str, + ) -> dict[str, Any]: + try: + definition = json.loads(definition_json) + except json.JSONDecodeError as exc: + raise JobIssuanceError( + "Method version contains invalid definition JSON" + ) from exc + + try: + return validate_method_definition(definition) + except MethodDefinitionError as exc: + raise JobIssuanceError(str(exc)) from exc + + @staticmethod + def _build_steps( + method_id: str, + method_version: int, + definition: dict[str, Any], + ) -> list[dict[str, Any]]: + del method_id + del method_version + + source_steps = definition["steps"] + result: list[dict[str, Any]] = [] + seen_step_ids: set[str] = set() + + for step in source_steps: + if not isinstance(step, dict): + raise JobIssuanceError( + "Each method step must be a JSON object" + ) + + step_id = step.get("step_id") + + if not isinstance(step_id, str) or not step_id: + raise JobIssuanceError( + "Each method step must have a non-empty step_id" + ) + + if step_id in seen_step_ids: + raise JobIssuanceError( + f"Duplicate step_id: {step_id}" + ) + + seen_step_ids.add(step_id) + + attack_mode = step.get("attack_mode") + + if not isinstance(attack_mode, int) or attack_mode < 0: + raise JobIssuanceError( + f"Invalid attack_mode for step: {step_id}" + ) + + result.append(dict(step)) + + return result + + @staticmethod + def _session_name( + job_id: str, + step_id: str, + ) -> str: + return f"cl_{job_id[:12]}_{step_id}" diff --git a/cracklab/server/services/job_result.py b/cracklab/server/services/job_result.py new file mode 100644 index 0000000..65a971c --- /dev/null +++ b/cracklab/server/services/job_result.py @@ -0,0 +1,740 @@ +from __future__ import annotations + +import hashlib +import json +import tempfile +import zipfile +from collections import defaultdict +from pathlib import Path +from typing import Any + +from cracklab.server.repositories.attempts import AttemptsRepository +from cracklab.server.repositories.audit import AuditRepository +from cracklab.server.repositories.credentials import CredentialsRepository +from cracklab.server.repositories.jobs import JobsRepository +from cracklab.server.repositories.reservations import ReservationsRepository +from cracklab.server.repositories.results import ResultsRepository + + +class JobResultError(ValueError): + pass + + +class JobResultService: + def __init__(self, conn) -> None: + self._conn = conn + self._attempts = AttemptsRepository(conn) + self._audit = AuditRepository(conn) + self._credentials = CredentialsRepository(conn) + self._jobs = JobsRepository(conn) + self._reservations = ReservationsRepository(conn) + self._results = ResultsRepository(conn) + + def import_result(self, package_path: Path | str) -> dict[str, Any]: + package = Path(package_path) + + if not package.is_file(): + raise JobResultError(f"Result package not found: {package}") + + with tempfile.TemporaryDirectory(prefix="cracklab-result-") as tmp: + root = Path(tmp) + + try: + with zipfile.ZipFile(package, "r") as zf: + self._safe_extract(zf, root) + except zipfile.BadZipFile as exc: + raise JobResultError( + f"Invalid result package: {package}" + ) from exc + + result_path, show_path = self._find_result_files(root) + result = self._read_json(result_path) + + self._validate_result_sha256(result) + + job_id = result.get("job_id") + if not isinstance(job_id, str) or not job_id: + raise JobResultError("Result is missing job_id") + + self._conn.execute("BEGIN IMMEDIATE") + + try: + job = self._jobs.get_job(job_id) + + if job is None: + raise JobResultError(f"Unknown Job: {job_id}") + + idempotent = self._check_idempotency(job, result) + + if idempotent: + self._conn.rollback() + return { + "job_id": job_id, + "status": "ALREADY_IMPORTED", + "result_sha256": result["result_sha256"], + } + + self._validate_job_contract(job, result) + + job_handshakes = self._load_job_handshakes(job_id) + + unique_hashes = { + row["hash22000"] + for row in job_handshakes + } + + if len(unique_hashes) != job["hash_count"]: + raise JobResultError( + "Job hash_count does not match unique " + "crack_job_handshakes hash22000 values" + ) + + found = self._parse_show_file( + show_path, + job_handshakes, + ) + + credential_stats = self._import_credentials( + found, + job_handshakes, + ) + + attempt_count = self._register_attempts( + job, + result, + job_handshakes, + ) + + self._update_steps(job_id, result["steps"]) + + released = self._release_reservations(job_id) + + imported_at = self._now() + + self._jobs.update_job_status( + job_id, + "COMPLETED", + ) + + self._jobs.update_job_result( + job_id, + result_sha256=result["result_sha256"], + imported_at=imported_at, + ) + + self._results.create_result( + job_id, + "COMPLETED", + result, + imported_at=imported_at, + ) + + self._audit.create_event( + event_type="JOB_RESULT_IMPORTED", + job_id=job_id, + client_id=job["client_id"], + method_id=job["method_id"], + method_version=job["method_version"], + details={ + "result_sha256": result["result_sha256"], + "credentials_imported": credential_stats["imported"], + "credentials_already_present": ( + credential_stats["already_present"] + ), + "attempts_completed": attempt_count, + "reservations_released": released, + }, + ) + + self._conn.commit() + + return { + "job_id": job_id, + "status": "COMPLETED", + "result_sha256": result["result_sha256"], + "credentials_imported": credential_stats["imported"], + "credentials_already_present": ( + credential_stats["already_present"] + ), + "attempts_completed": attempt_count, + "reservations_released": released, + } + + except Exception: + self._conn.rollback() + raise + + @staticmethod + def _now() -> str: + from datetime import datetime, timezone + + return datetime.now(timezone.utc).isoformat( + timespec="milliseconds" + ).replace("+00:00", "Z") + + @staticmethod + def _read_json(path: Path) -> dict[str, Any]: + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise JobResultError( + f"Invalid result.json: {path}" + ) from exc + + if not isinstance(value, dict): + raise JobResultError("result.json must contain a JSON object") + + return value + + @staticmethod + def _safe_extract( + zf: zipfile.ZipFile, + destination: Path, + ) -> None: + destination = destination.resolve() + + for member in zf.infolist(): + target = (destination / member.filename).resolve() + + try: + target.relative_to(destination) + except ValueError as exc: + raise JobResultError( + f"Unsafe path in result package: {member.filename}" + ) from exc + + if member.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + + target.parent.mkdir(parents=True, exist_ok=True) + + with zf.open(member) as src, target.open("wb") as dst: + while True: + chunk = src.read(1024 * 1024) + + if not chunk: + break + + dst.write(chunk) + + @staticmethod + def _find_result_files( + root: Path, + ) -> tuple[Path, Path]: + manifests = list(root.rglob("result.json")) + + if len(manifests) != 1: + raise JobResultError( + "Result package must contain exactly one result.json" + ) + + show_files = list(root.rglob("hashcat-show.txt")) + + if len(show_files) != 1: + raise JobResultError( + "Result package must contain exactly one hashcat-show.txt" + ) + + return manifests[0], show_files[0] + + @staticmethod + def _validate_result_sha256(result: dict[str, Any]) -> None: + expected = result.get("result_sha256") + + if not isinstance(expected, str) or not expected: + raise JobResultError( + "Result is missing result_sha256" + ) + + payload = dict(result) + payload.pop("result_sha256", None) + + payload_bytes = json.dumps( + payload, + ensure_ascii=False, + indent=2, + ).encode("utf-8") + + actual = hashlib.sha256(payload_bytes).hexdigest() + + if actual != expected: + raise JobResultError( + "Invalid result_sha256: " + f"expected {expected}, calculated {actual}" + ) + + def _check_idempotency( + self, + job, + result: dict[str, Any], + ) -> bool: + result_sha256 = result["result_sha256"] + + stored_job_sha = job["result_sha256"] + stored_result = self._results.get_result(job["id"]) + + if stored_job_sha is not None: + if stored_job_sha != result_sha256: + raise JobResultError( + f"Job {job['id']} already has a different result_sha256" + ) + + return True + + if stored_result is not None: + stored_payload = self._results.decode_result(stored_result) + stored_sha = stored_payload.get("result_sha256") + + if stored_sha != result_sha256: + raise JobResultError( + f"Job {job['id']} already has a different imported result" + ) + + return True + + if job["imported_at"] is not None: + raise JobResultError( + f"Job {job['id']} is marked imported without a stored result" + ) + + if job["status"] == "COMPLETED": + raise JobResultError( + f"Job {job['id']} is already COMPLETED without an imported result" + ) + + return False + + def _validate_job_contract( + self, + job, + result: dict[str, Any], + ) -> None: + if result.get("schema_version") != 1: + raise JobResultError( + "Unsupported result schema_version: " + f"{result.get('schema_version')!r}" + ) + + if result.get("job_id") != job["id"]: + raise JobResultError( + "Result Job ID does not match the database Job" + ) + + if result.get("status") != "COMPLETED": + raise JobResultError( + "Only COMPLETED results can be imported" + ) + + if result.get("hash_file_sha256") != job["hash_file_sha256"]: + raise JobResultError( + "Result hash_file_sha256 does not match the Job" + ) + + if result.get("hash_count") != job["hash_count"]: + raise JobResultError( + "Result hash_count does not match the Job" + ) + + method = result.get("method") + + if not isinstance(method, dict): + raise JobResultError( + "Result is missing method object" + ) + + if method.get("id") != job["method_id"]: + raise JobResultError( + "Result method id does not match the Job" + ) + + if method.get("version") != job["method_version"]: + raise JobResultError( + "Result method version does not match the Job" + ) + + completed_at = result.get("completed_at") + + if not isinstance(completed_at, str) or not completed_at: + raise JobResultError( + "Result is missing completed_at" + ) + + result_steps = result.get("steps") + + if not isinstance(result_steps, list): + raise JobResultError( + "Result is missing steps list" + ) + + if len(result_steps) != job["step_count"]: + raise JobResultError( + "Result step count does not match the Job" + ) + + db_steps = self._jobs.list_job_steps(job["id"]) + + if len(db_steps) != job["step_count"]: + raise JobResultError( + "Database Job step count does not match crack_job_steps" + ) + + db_by_no = { + row["step_no"]: row + for row in db_steps + } + + seen_step_numbers: set[int] = set() + + for step in result_steps: + if not isinstance(step, dict): + raise JobResultError( + "Each result step must be an object" + ) + + step_no = step.get("step_no") + + if not isinstance(step_no, int): + raise JobResultError( + f"Invalid result step_no: {step_no!r}" + ) + + if step_no in seen_step_numbers: + raise JobResultError( + f"Duplicate result step_no: {step_no}" + ) + + seen_step_numbers.add(step_no) + + db_step = db_by_no.get(step_no) + + if db_step is None: + raise JobResultError( + f"Result contains unknown step_no: {step_no}" + ) + + if step.get("step_id") != db_step["step_id"]: + raise JobResultError( + f"Step {step_no}: step_id does not match the Job" + ) + + if step.get("session") != db_step["session_name"]: + raise JobResultError( + f"Step {step_no}: session does not match the Job" + ) + + if step.get("status") != "COMPLETED": + raise JobResultError( + f"Step {step_no}: result status must be COMPLETED" + ) + + def _load_job_handshakes( + self, + job_id: str, + ) -> list[dict[str, Any]]: + rows = self._jobs.list_job_handshakes(job_id) + + if not rows: + raise JobResultError( + f"Job {job_id} contains no handshakes" + ) + + result = [] + + for row in rows: + result.append( + { + "handshake_id": row["handshake_id"], + "hash22000": row["hash22000"], + "access_point_id": row["access_point_id"], + } + ) + + return result + + @staticmethod + def _normalize_mac(value: str) -> str: + normalized = value.strip().lower().replace(":", "").replace("-", "") + + if len(normalized) != 12: + raise JobResultError( + f"Invalid MAC address: {value!r}" + ) + + try: + int(normalized, 16) + except ValueError as exc: + raise JobResultError( + f"Invalid MAC address: {value!r}" + ) from exc + + return normalized + + @classmethod + def _hash_identity( + cls, + hash22000: str, + ) -> tuple[str, str, str]: + parts = hash22000.split("*") + + if len(parts) < 6 or parts[0] != "WPA": + raise JobResultError( + f"Unsupported hash22000 format: {hash22000}" + ) + + if parts[1] not in {"01", "02"}: + raise JobResultError( + f"Unsupported WPA hash type: {parts[1]}" + ) + + hash_value = parts[2].strip().lower() + ap_mac = cls._normalize_mac(parts[3]) + client_mac = cls._normalize_mac(parts[4]) + + if not hash_value: + raise JobResultError( + f"Invalid hash22000 hash value: {hash22000}" + ) + + return ( + hash_value, + ap_mac, + client_mac, + ) + + @classmethod + def _parse_show_identity( + cls, + line: str, + ) -> tuple[str, str, str, str]: + fields = line.split(":", 4) + + if len(fields) != 5: + raise JobResultError( + f"Invalid Hashcat --show line: {line}" + ) + + hash_value = fields[0].strip().lower() + ap_mac = cls._normalize_mac(fields[1]) + client_mac = cls._normalize_mac(fields[2]) + password = fields[4] + + if not hash_value: + raise JobResultError( + f"Invalid Hashcat --show hash: {line}" + ) + + return ( + hash_value, + ap_mac, + client_mac, + password, + ) + + def _parse_show_file( + self, + path: Path, + job_handshakes: list[dict[str, Any]], + ) -> list[tuple[str, str]]: + identity_to_hashes: dict[ + tuple[str, str, str], + list[str], + ] = defaultdict(list) + + for row in job_handshakes: + identity = self._hash_identity(row["hash22000"]) + hashes = identity_to_hashes[identity] + + if row["hash22000"] not in hashes: + hashes.append(row["hash22000"]) + + found: list[tuple[str, str]] = [] + seen: set[tuple[str, str]] = set() + + for line_no, raw_line in enumerate( + path.read_text(encoding="utf-8").splitlines(), + start=1, + ): + line = raw_line.strip() + + if not line: + continue + + hash_value, ap_mac, client_mac, password = ( + self._parse_show_identity(line) + ) + + identity = ( + hash_value, + ap_mac, + client_mac, + ) + + hashes = identity_to_hashes.get(identity) + + if not hashes: + raise JobResultError( + "Result contains an unknown Hashcat --show line " + f"{line_no}: {line}" + ) + + for hash22000 in hashes: + item = (hash22000, password) + + if item not in seen: + seen.add(item) + found.append(item) + + return found + + def _import_credentials( + self, + found: list[tuple[str, str]], + job_handshakes: list[dict[str, Any]], + ) -> dict[str, int]: + by_hash: dict[str, list[dict[str, Any]]] = defaultdict(list) + + for row in job_handshakes: + by_hash[row["hash22000"]].append(row) + + imported = 0 + already_present = 0 + + for hash22000, password in found: + mappings = by_hash.get(hash22000) + + if not mappings: + raise JobResultError( + "Hashcat --show contains a hash that is not part " + f"of the Job: {hash22000}" + ) + + for mapping in mappings: + handshake_id = mapping["handshake_id"] + access_point_id = mapping["access_point_id"] + + if access_point_id is None: + raise JobResultError( + "Cannot import credential for handshake " + f"{handshake_id}: access_point_id is NULL" + ) + + existing = self._credentials.get_credential( + access_point_id, + handshake_id, + password, + ) + + if existing is not None: + already_present += 1 + self._credentials.mark_access_point_cracked( + access_point_id, + ) + continue + + self._credentials.create_hashcat_credential( + access_point_id, + handshake_id, + password, + ) + imported += 1 + + return { + "imported": imported, + "already_present": already_present, + } + + def _register_attempts( + self, + job, + result: dict[str, Any], + job_handshakes: list[dict[str, Any]], + ) -> int: + if result["status"] != "COMPLETED": + return 0 + + completed_at = result["completed_at"] + count = 0 + + for row in job_handshakes: + existing = self._attempts.get_attempt( + row["handshake_id"], + job["method_id"], + job["method_version"], + ) + + if existing is not None: + if ( + existing["job_id"] != job["id"] + or existing["status"] != "COMPLETED" + ): + raise JobResultError( + "Handshake " + f"{row['handshake_id']} already has a " + "conflicting attempt for this method/version" + ) + + continue + + self._attempts.create_attempt( + handshake_id=row["handshake_id"], + method_id=job["method_id"], + method_version=job["method_version"], + job_id=job["id"], + completed_at=completed_at, + ) + count += 1 + + return count + + def _update_steps( + self, + job_id: str, + result_steps: list[dict[str, Any]], + ) -> None: + for step in result_steps: + step_no = step["step_no"] + + self._jobs.update_job_step( + job_id=job_id, + step_no=step_no, + status="COMPLETED", + started_at=step.get("started_at"), + completed_at=step.get("completed_at"), + exit_code=step.get("exit_code"), + restore_seen=( + 1 if step.get("restore_seen") else 0 + ), + error=step.get("error"), + ) + + updated = self._jobs.get_job_step( + job_id, + step_no, + ) + + if updated is None: + raise JobResultError( + f"Job step disappeared during result import: " + f"{step_no}" + ) + + def _release_reservations( + self, + job_id: str, + ) -> int: + released = 0 + + for reservation in self._reservations.list_job_reservations( + job_id + ): + if reservation["status"] != "ACTIVE": + continue + + self._reservations.update_status( + reservation["id"], + "RELEASED", + ) + released += 1 + + return released diff --git a/cracklab/server/services/method_definition.py b/cracklab/server/services/method_definition.py new file mode 100644 index 0000000..93ceacc --- /dev/null +++ b/cracklab/server/services/method_definition.py @@ -0,0 +1,251 @@ +from __future__ import annotations + +import re +from typing import Any + + +class MethodDefinitionError(ValueError): + pass + + +_RESOURCE_RE = re.compile(r"^[a-z][a-z0-9_-]*:[A-Za-z0-9][A-Za-z0-9._-]*$") +_STEP_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") +_MASK_CHARSET_SIZES = { + "?l": 26, + "?u": 26, + "?d": 10, + "?s": 33, + "?a": 95, + "?b": 256, +} +_MASK_MIN_LENGTH = 8 + + +def validate_method_definition( + definition: dict[str, Any], +) -> dict[str, Any]: + if not isinstance(definition, dict): + raise MethodDefinitionError( + "Method definition must be a JSON object" + ) + + if definition.get("schema_version") != 1: + raise MethodDefinitionError( + "Unsupported method definition schema version" + ) + + hash_mode = definition.get("hash_mode") + + if not isinstance(hash_mode, int) or isinstance(hash_mode, bool): + raise MethodDefinitionError( + "Method definition hash_mode must be a non-negative integer" + ) + + if hash_mode < 0: + raise MethodDefinitionError( + "Method definition hash_mode must be a non-negative integer" + ) + + steps = definition.get("steps") + + if not isinstance(steps, list) or not steps: + raise MethodDefinitionError( + "Method definition must contain a non-empty steps list" + ) + + seen_step_ids: set[str] = set() + + for step in steps: + _validate_step(step, seen_step_ids) + + return definition + + +def _validate_step( + step: Any, + seen_step_ids: set[str], +) -> None: + if not isinstance(step, dict): + raise MethodDefinitionError( + "Each method step must be a JSON object" + ) + + step_id = step.get("step_id") + + if not isinstance(step_id, str) or not _STEP_ID_RE.fullmatch(step_id): + raise MethodDefinitionError( + "Each method step must have a valid step_id" + ) + + if step_id in seen_step_ids: + raise MethodDefinitionError( + f"Duplicate step_id: {step_id}" + ) + + seen_step_ids.add(step_id) + + attack_mode = step.get("attack_mode") + + if not isinstance(attack_mode, int) or isinstance(attack_mode, bool): + raise MethodDefinitionError( + f"Invalid attack_mode for step: {step_id}" + ) + + if attack_mode < 0: + raise MethodDefinitionError( + f"Invalid attack_mode for step: {step_id}" + ) + + if attack_mode == 0: + _require_dictionary(step, step_id) + + elif attack_mode == 1: + _require_dictionaries(step, step_id) + + elif attack_mode == 3: + _require_mask( + step, + step_id, + minimum_length=_MASK_MIN_LENGTH, + ) + + elif attack_mode == 6: + _require_dictionary(step, step_id) + _require_mask( + step, + step_id, + minimum_length=_MASK_MIN_LENGTH, + ) + + elif attack_mode == 7: + _require_mask( + step, + step_id, + minimum_length=_MASK_MIN_LENGTH, + ) + _require_dictionary(step, step_id) + + if "rules" in step: + _validate_resource_object( + step["rules"], + "rules", + step_id, + ) + + +def _require_dictionary( + step: dict[str, Any], + step_id: str, +) -> None: + if "dictionary" not in step: + raise MethodDefinitionError( + f"Step {step_id} requires dictionary" + ) + + _validate_resource_object( + step["dictionary"], + "dictionary", + step_id, + ) + + +def _require_dictionaries( + step: dict[str, Any], + step_id: str, +) -> None: + dictionaries = step.get("dictionaries") + + if not isinstance(dictionaries, list) or len(dictionaries) != 2: + raise MethodDefinitionError( + f"Step {step_id} requires exactly two dictionaries" + ) + + for dictionary in dictionaries: + _validate_resource_object( + dictionary, + "dictionary", + step_id, + ) + + +def _require_mask( + step: dict[str, Any], + step_id: str, + minimum_length: int | None = None, +) -> None: + mask = step.get("mask") + + if not isinstance(mask, str) or not mask: + raise MethodDefinitionError( + f"Step {step_id} requires a non-empty mask" + ) + + length = 0 + index = 0 + + while index < len(mask): + if mask[index] != "?": + length += 1 + index += 1 + continue + + if index + 1 >= len(mask): + raise MethodDefinitionError( + f"Step {step_id} mask contains a lone '?' " + f"at position {index + 1}" + ) + + token = mask[index:index + 2] + + if token == "??": + length += 1 + index += 2 + continue + + if token not in _MASK_CHARSET_SIZES: + raise MethodDefinitionError( + f"Step {step_id} contains unsupported mask token " + f"{token!r} at position {index + 1}" + ) + + length += 1 + index += 2 + + if ( + minimum_length is not None + and length < minimum_length + ): + raise MethodDefinitionError( + f"Step {step_id} mask must produce at least " + f"{minimum_length} characters; got {length}" + ) + +def _validate_resource_object( + value: Any, + resource_type: str, + step_id: str, +) -> None: + if not isinstance(value, dict): + raise MethodDefinitionError( + f"Step {step_id} {resource_type} must be an object" + ) + + resource = value.get("resource") + + if not isinstance(resource, str) or not _RESOURCE_RE.fullmatch(resource): + raise MethodDefinitionError( + f"Step {step_id} {resource_type}.resource must be " + "a valid logical resource ID" + ) + + expected_prefix = ( + "wordlist:" + if resource_type == "dictionary" + else f"{resource_type}:" + ) + + if not resource.startswith(expected_prefix): + raise MethodDefinitionError( + f"Step {step_id} {resource_type}.resource must start " + f"with {expected_prefix!r}" + ) diff --git a/cracklab/server/services/methods.py b/cracklab/server/services/methods.py new file mode 100644 index 0000000..81306ce --- /dev/null +++ b/cracklab/server/services/methods.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import sqlite3 +import uuid +from typing import Any + +from cracklab.server.repositories.methods import MethodsRepository +from cracklab.server.services.method_definition import ( + MethodDefinitionError, + validate_method_definition, +) + + +class MethodServiceError(ValueError): + pass + + +class MethodService: + def __init__(self, conn: sqlite3.Connection) -> None: + self._methods = MethodsRepository(conn) + + def create_method( + self, + name: str, + description: str | None = None, + method_id: str | None = None, + ) -> str: + if not name or not name.strip(): + raise MethodServiceError("Method name must not be empty") + + if method_id is None: + method_id = f"MTH-{uuid.uuid4().hex}" + + if not method_id: + raise MethodServiceError("Method ID must not be empty") + + self._methods.create_method( + method_id=method_id, + name=name.strip(), + description=description.strip() if description else None, + ) + + return method_id + + def create_method_version( + self, + method_id: str, + version: int, + definition: dict[str, Any], + ) -> None: + if version <= 0: + raise MethodServiceError( + "Method version must be greater than zero" + ) + + try: + validate_method_definition(definition) + except MethodDefinitionError as exc: + raise MethodServiceError(str(exc)) from exc + + self._methods.create_method_version( + method_id=method_id, + version=version, + definition=definition, + ) + + def create_next_method_version( + self, + method_id: str, + definition: dict[str, Any], + ) -> int: + try: + validate_method_definition(definition) + except MethodDefinitionError as exc: + raise MethodServiceError(str(exc)) from exc + + version = self._methods.get_next_method_version(method_id) + + self._methods.create_method_version( + method_id=method_id, + version=version, + definition=definition, + ) + + return version + + def get_method(self, method_id: str) -> sqlite3.Row | None: + return self._methods.get_method(method_id) + + def list_methods(self) -> list[sqlite3.Row]: + return self._methods.list_methods() + + def get_method_version( + self, + method_id: str, + version: int, + ) -> sqlite3.Row | None: + return self._methods.get_method_version( + method_id, + version, + ) + + def list_method_versions( + self, + method_id: str, + ) -> list[sqlite3.Row]: + return self._methods.list_method_versions(method_id) + + def get_latest_method_version( + self, + method_id: str, + ) -> sqlite3.Row | None: + versions = self._methods.list_method_versions(method_id) + + if not versions: + return None + + return versions[-1] diff --git a/cracklab/server/services/stock_methods.py b/cracklab/server/services/stock_methods.py new file mode 100644 index 0000000..245ae8b --- /dev/null +++ b/cracklab/server/services/stock_methods.py @@ -0,0 +1,914 @@ +from __future__ import annotations + +import sqlite3 +from dataclasses import dataclass +from typing import Any + +from cracklab.server.services.methods import MethodService + + +@dataclass(frozen=True) +class StockMethod: + method_id: str + name: str + description: str + definition: dict[str, Any] | None + + +STOCK_METHODS = ( + StockMethod( + method_id="mobile_oper_spb_plus_79", + name="MobileOperSpb+79", + description="Перебор мобильных номеров Санкт-Петербурга с префиксом +79.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "+791100?d?d?d?d?d", + "+791101?d?d?d?d?d", + "+791102?d?d?d?d?d", + "+791103?d?d?d?d?d", + "+791108?d?d?d?d?d", + "+791109?d?d?d?d?d", + "+791110?d?d?d?d?d", + "+791111?d?d?d?d?d", + "+791112?d?d?d?d?d", + "+791117?d?d?d?d?d", + "+791119?d?d?d?d?d", + "+79811?d?d?d?d?d?d", + "+79817?d?d?d?d?d?d", + "+79818?d?d?d?d?d?d", + "+79819?d?d?d?d?d?d", + "+798986?d?d?d?d?d", + "+798686?d?d?d?d?d", + "+798687?d?d?d?d?d", + "+798688?d?d?d?d?d", + "+792118?d?d?d?d?d", + "+792119?d?d?d?d?d", + "+79213?d?d?d?d?d?d", + "+79214?d?d?d?d?d?d", + "+79215?d?d?d?d?d?d", + "+79216?d?d?d?d?d?d", + "+79217?d?d?d?d?d?d", + "+79218?d?d?d?d?d?d", + "+79219?d?d?d?d?d?d", + "+793110?d?d?d?d?d", + "+793111?d?d?d?d?d", + "+793112?d?d?d?d?d", + "+793113?d?d?d?d?d", + "+79312?d?d?d?d?d?d", + "+79313?d?d?d?d?d?d", + "+79315?d?d?d?d?d?d", + "+79319?d?d?d?d?d?d", + "+79291?d?d?d?d?d?d", + "+799923?d?d?d?d?d", + "+799924?d?d?d?d?d", + "+799925?d?d?d?d?d", + "+7963241?d?d?d?d", + "+7963242?d?d?d?d", + "+7963243?d?d?d?d", + "+7963244?d?d?d?d", + "+7963245?d?d?d?d", + "+7963246?d?d?d?d", + "+7963247?d?d?d?d", + "+7963248?d?d?d?d", + "+7963249?d?d?d?d", + "+796330?d?d?d?d?d", + "+796331?d?d?d?d?d", + "+796332?d?d?d?d?d", + "+796334?d?d?d?d?d", + "+79650?d?d?d?d?d?d", + "+79651?d?d?d?d?d?d", + "+79652?d?d?d?d?d?d", + "+79653?d?d?d?d?d?d", + "+79654?d?d?d?d?d?d", + "+79655?d?d?d?d?d?d", + "+79656?d?d?d?d?d?d", + "+79657?d?d?d?d?d?d", + "+79658?d?d?d?d?d?d", + "+79659?d?d?d?d?d?d", + "+790520?d?d?d?d?d", + "+790521?d?d?d?d?d", + "+790522?d?d?d?d?d", + "+790523?d?d?d?d?d", + "+790524?d?d?d?d?d", + "+790525?d?d?d?d?d", + "+790526?d?d?d?d?d", + "+790527?d?d?d?d?d", + "+790528?d?d?d?d?d", + "+790624?d?d?d?d?d", + "+790625?d?d?d?d?d", + "+790626?d?d?d?d?d", + "+790627?d?d?d?d?d", + "+790958?d?d?d?d?d", + "+790959?d?d?d?d?d", + "+796023?d?d?d?d?d", + "+796024?d?d?d?d?d", + "+796025?d?d?d?d?d", + "+796026?d?d?d?d?d", + "+796027?d?d?d?d?d", + "+796028?d?d?d?d?d", + "+796434?d?d?d?d?d", + "+79500?d?d?d?d?d?d", + "+79502?d?d?d?d?d?d", + "+79516?d?d?d?d?d?d", + "+79517?d?d?d?d?d?d", + "+79518?d?d?d?d?d?d", + "+79522?d?d?d?d?d?d", + "+79523?d?d?d?d?d?d", + "+79531?d?d?d?d?d?d", + "+79533?d?d?d?d?d?d", + "+790433?d?d?d?d?d", + "+790451?d?d?d?d?d", + "+790455?d?d?d?d?d", + "+790460?d?d?d?d?d", + "+790461?d?d?d?d?d", + "+790462?d?d?d?d?d", + "+790463?d?d?d?d?d", + "+790464?d?d?d?d?d", + "+799100?d?d?d?d?d", + "+799101?d?d?d?d?d", + "+799102?d?d?d?d?d", + "+790062?d?d?d?d?d", + "+790063?d?d?d?d?d", + "+790064?d?d?d?d?d", + "+790065?d?d?d?d?d", + "+799900?d?d?d?d?d", + "+799901?d?d?d?d?d", + "+799902?d?d?d?d?d", + "+799903?d?d?d?d?d", + "+799904?d?d?d?d?d", + "+799909?d?d?d?d?d", + "+79991?d?d?d?d?d?d", + "+79992?d?d?d?d?d?d", + "+799322?d?d?d?d?d", + "+799343?d?d?d?d?d", + "+799344?d?d?d?d?d", + "+799555?d?d?d?d?d", + "+799559?d?d?d?d?d", + "+799560?d?d?d?d?d", + "+799590?d?d?d?d?d", + "+795840?d?d?d?d?d", + "+795856?d?d?d?d?d", + "+799511?d?d?d?d?d", + "+799512?d?d?d?d?d", + "+7999944?d?d?d?d", + "+7999945?d?d?d?d", + "+7999946?d?d?d?d", + "+7999947?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_spb_89", + name="MobileOperSpb_89", + description="Перебор мобильных номеров Санкт-Петербурга с префиксом 89.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "891100?d?d?d?d?d", + "891101?d?d?d?d?d", + "891102?d?d?d?d?d", + "891103?d?d?d?d?d", + "891108?d?d?d?d?d", + "891109?d?d?d?d?d", + "891110?d?d?d?d?d", + "891111?d?d?d?d?d", + "891112?d?d?d?d?d", + "891117?d?d?d?d?d", + "891119?d?d?d?d?d", + "89811?d?d?d?d?d?d", + "89817?d?d?d?d?d?d", + "89818?d?d?d?d?d?d", + "89819?d?d?d?d?d?d", + "898986?d?d?d?d?d", + "898686?d?d?d?d?d", + "898687?d?d?d?d?d", + "898688?d?d?d?d?d", + "892118?d?d?d?d?d", + "892119?d?d?d?d?d", + "89213?d?d?d?d?d?d", + "89214?d?d?d?d?d?d", + "89215?d?d?d?d?d?d", + "89216?d?d?d?d?d?d", + "89217?d?d?d?d?d?d", + "89218?d?d?d?d?d?d", + "89219?d?d?d?d?d?d", + "893110?d?d?d?d?d", + "893111?d?d?d?d?d", + "893112?d?d?d?d?d", + "893113?d?d?d?d?d", + "89312?d?d?d?d?d?d", + "89313?d?d?d?d?d?d", + "89315?d?d?d?d?d?d", + "89319?d?d?d?d?d?d", + "89291?d?d?d?d?d?d", + "899923?d?d?d?d?d", + "899924?d?d?d?d?d", + "899925?d?d?d?d?d", + "8963241?d?d?d?d", + "8963242?d?d?d?d", + "8963243?d?d?d?d", + "8963244?d?d?d?d", + "8963245?d?d?d?d", + "8963246?d?d?d?d", + "8963247?d?d?d?d", + "8963248?d?d?d?d", + "8963249?d?d?d?d", + "896330?d?d?d?d?d", + "896331?d?d?d?d?d", + "896332?d?d?d?d?d", + "896334?d?d?d?d?d", + "89650?d?d?d?d?d?d", + "89651?d?d?d?d?d?d", + "89652?d?d?d?d?d?d", + "89653?d?d?d?d?d?d", + "89654?d?d?d?d?d?d", + "89655?d?d?d?d?d?d", + "89656?d?d?d?d?d?d", + "89657?d?d?d?d?d?d", + "89658?d?d?d?d?d?d", + "89659?d?d?d?d?d?d", + "890520?d?d?d?d?d", + "890521?d?d?d?d?d", + "890522?d?d?d?d?d", + "890523?d?d?d?d?d", + "890524?d?d?d?d?d", + "890525?d?d?d?d?d", + "890526?d?d?d?d?d", + "890527?d?d?d?d?d", + "890528?d?d?d?d?d", + "890624?d?d?d?d?d", + "890625?d?d?d?d?d", + "890626?d?d?d?d?d", + "890627?d?d?d?d?d", + "890958?d?d?d?d?d", + "890959?d?d?d?d?d", + "896023?d?d?d?d?d", + "896024?d?d?d?d?d", + "896025?d?d?d?d?d", + "896026?d?d?d?d?d", + "896027?d?d?d?d?d", + "896028?d?d?d?d?d", + "896434?d?d?d?d?d", + "89500?d?d?d?d?d?d", + "89502?d?d?d?d?d?d", + "89516?d?d?d?d?d?d", + "89517?d?d?d?d?d?d", + "89518?d?d?d?d?d?d", + "89522?d?d?d?d?d?d", + "89523?d?d?d?d?d?d", + "89531?d?d?d?d?d?d", + "89533?d?d?d?d?d?d", + "890433?d?d?d?d?d", + "890451?d?d?d?d?d", + "890455?d?d?d?d?d", + "890460?d?d?d?d?d", + "890461?d?d?d?d?d", + "890462?d?d?d?d?d", + "890463?d?d?d?d?d", + "890464?d?d?d?d?d", + "899100?d?d?d?d?d", + "899101?d?d?d?d?d", + "899102?d?d?d?d?d", + "890062?d?d?d?d?d", + "890063?d?d?d?d?d", + "890064?d?d?d?d?d", + "890065?d?d?d?d?d", + "899900?d?d?d?d?d", + "899901?d?d?d?d?d", + "899902?d?d?d?d?d", + "899903?d?d?d?d?d", + "899904?d?d?d?d?d", + "899909?d?d?d?d?d", + "89991?d?d?d?d?d?d", + "89992?d?d?d?d?d?d", + "899322?d?d?d?d?d", + "899343?d?d?d?d?d", + "899344?d?d?d?d?d", + "899555?d?d?d?d?d", + "899559?d?d?d?d?d", + "899560?d?d?d?d?d", + "899590?d?d?d?d?d", + "895840?d?d?d?d?d", + "895856?d?d?d?d?d", + "899511?d?d?d?d?d", + "899512?d?d?d?d?d", + "8999944?d?d?d?d", + "8999945?d?d?d?d", + "8999946?d?d?d?d", + "8999947?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_spb_79", + name="MobileOperSpb_79", + description="Перебор мобильных номеров Санкт-Петербурга без знака +.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "791100?d?d?d?d?d", + "791101?d?d?d?d?d", + "791102?d?d?d?d?d", + "791103?d?d?d?d?d", + "791108?d?d?d?d?d", + "791109?d?d?d?d?d", + "791110?d?d?d?d?d", + "791111?d?d?d?d?d", + "791112?d?d?d?d?d", + "791117?d?d?d?d?d", + "791119?d?d?d?d?d", + "79811?d?d?d?d?d?d", + "79817?d?d?d?d?d?d", + "79818?d?d?d?d?d?d", + "79819?d?d?d?d?d?d", + "798986?d?d?d?d?d", + "798686?d?d?d?d?d", + "798687?d?d?d?d?d", + "798688?d?d?d?d?d", + "792118?d?d?d?d?d", + "792119?d?d?d?d?d", + "79213?d?d?d?d?d?d", + "79214?d?d?d?d?d?d", + "79215?d?d?d?d?d?d", + "79216?d?d?d?d?d?d", + "79217?d?d?d?d?d?d", + "79218?d?d?d?d?d?d", + "79219?d?d?d?d?d?d", + "793110?d?d?d?d?d", + "793111?d?d?d?d?d", + "793112?d?d?d?d?d", + "793113?d?d?d?d?d", + "79312?d?d?d?d?d?d", + "79313?d?d?d?d?d?d", + "79315?d?d?d?d?d?d", + "79319?d?d?d?d?d?d", + "79291?d?d?d?d?d?d", + "799923?d?d?d?d?d", + "799924?d?d?d?d?d", + "799925?d?d?d?d?d", + "7963241?d?d?d?d", + "7963242?d?d?d?d", + "7963243?d?d?d?d", + "7963244?d?d?d?d", + "7963245?d?d?d?d", + "7963246?d?d?d?d", + "7963247?d?d?d?d", + "7963248?d?d?d?d", + "7963249?d?d?d?d", + "796330?d?d?d?d?d", + "796331?d?d?d?d?d", + "796332?d?d?d?d?d", + "796334?d?d?d?d?d", + "79650?d?d?d?d?d?d", + "79651?d?d?d?d?d?d", + "79652?d?d?d?d?d?d", + "79653?d?d?d?d?d?d", + "79654?d?d?d?d?d?d", + "79655?d?d?d?d?d?d", + "79656?d?d?d?d?d?d", + "79657?d?d?d?d?d?d", + "79658?d?d?d?d?d?d", + "79659?d?d?d?d?d?d", + "790520?d?d?d?d?d", + "790521?d?d?d?d?d", + "790522?d?d?d?d?d", + "790523?d?d?d?d?d", + "790524?d?d?d?d?d", + "790525?d?d?d?d?d", + "790526?d?d?d?d?d", + "790527?d?d?d?d?d", + "790528?d?d?d?d?d", + "790624?d?d?d?d?d", + "790625?d?d?d?d?d", + "790626?d?d?d?d?d", + "790627?d?d?d?d?d", + "790958?d?d?d?d?d", + "790959?d?d?d?d?d", + "796023?d?d?d?d?d", + "796024?d?d?d?d?d", + "796025?d?d?d?d?d", + "796026?d?d?d?d?d", + "796027?d?d?d?d?d", + "796028?d?d?d?d?d", + "796434?d?d?d?d?d", + "79500?d?d?d?d?d?d", + "79502?d?d?d?d?d?d", + "79516?d?d?d?d?d?d", + "79517?d?d?d?d?d?d", + "79518?d?d?d?d?d?d", + "79522?d?d?d?d?d?d", + "79523?d?d?d?d?d?d", + "79531?d?d?d?d?d?d", + "79533?d?d?d?d?d?d", + "790433?d?d?d?d?d", + "790451?d?d?d?d?d", + "790455?d?d?d?d?d", + "790460?d?d?d?d?d", + "790461?d?d?d?d?d", + "790462?d?d?d?d?d", + "790463?d?d?d?d?d", + "790464?d?d?d?d?d", + "799100?d?d?d?d?d", + "799101?d?d?d?d?d", + "799102?d?d?d?d?d", + "790062?d?d?d?d?d", + "790063?d?d?d?d?d", + "790064?d?d?d?d?d", + "790065?d?d?d?d?d", + "799900?d?d?d?d?d", + "799901?d?d?d?d?d", + "799902?d?d?d?d?d", + "799903?d?d?d?d?d", + "799904?d?d?d?d?d", + "799909?d?d?d?d?d", + "79991?d?d?d?d?d?d", + "79992?d?d?d?d?d?d", + "799322?d?d?d?d?d", + "799343?d?d?d?d?d", + "799344?d?d?d?d?d", + "799555?d?d?d?d?d", + "799559?d?d?d?d?d", + "799560?d?d?d?d?d", + "799590?d?d?d?d?d", + "795840?d?d?d?d?d", + "795856?d?d?d?d?d", + "799511?d?d?d?d?d", + "799512?d?d?d?d?d", + "7999944?d?d?d?d", + "7999945?d?d?d?d", + "7999946?d?d?d?d", + "7999947?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_spb_9", + name="MobileOperSpb_9", + description="Перебор мобильных номеров Санкт-Петербурга без 7 и знака +.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "91100?d?d?d?d?d", + "91101?d?d?d?d?d", + "91102?d?d?d?d?d", + "91103?d?d?d?d?d", + "91108?d?d?d?d?d", + "91109?d?d?d?d?d", + "91110?d?d?d?d?d", + "91111?d?d?d?d?d", + "91112?d?d?d?d?d", + "91117?d?d?d?d?d", + "91119?d?d?d?d?d", + "9811?d?d?d?d?d?d", + "9817?d?d?d?d?d?d", + "9818?d?d?d?d?d?d", + "9819?d?d?d?d?d?d", + "98986?d?d?d?d?d", + "98686?d?d?d?d?d", + "98687?d?d?d?d?d", + "98688?d?d?d?d?d", + "92118?d?d?d?d?d", + "92119?d?d?d?d?d", + "9213?d?d?d?d?d?d", + "9214?d?d?d?d?d?d", + "9215?d?d?d?d?d?d", + "9216?d?d?d?d?d?d", + "9217?d?d?d?d?d?d", + "9218?d?d?d?d?d?d", + "9219?d?d?d?d?d?d", + "93110?d?d?d?d?d", + "93111?d?d?d?d?d", + "93112?d?d?d?d?d", + "93113?d?d?d?d?d", + "9312?d?d?d?d?d?d", + "9313?d?d?d?d?d?d", + "9315?d?d?d?d?d?d", + "9319?d?d?d?d?d?d", + "9291?d?d?d?d?d?d", + "99923?d?d?d?d?d", + "99924?d?d?d?d?d", + "99925?d?d?d?d?d", + "963241?d?d?d?d", + "963242?d?d?d?d", + "963243?d?d?d?d", + "963244?d?d?d?d", + "963245?d?d?d?d", + "963246?d?d?d?d", + "963247?d?d?d?d", + "963248?d?d?d?d", + "963249?d?d?d?d", + "96330?d?d?d?d?d", + "96331?d?d?d?d?d", + "96332?d?d?d?d?d", + "96334?d?d?d?d?d", + "9650?d?d?d?d?d?d", + "9651?d?d?d?d?d?d", + "9652?d?d?d?d?d?d", + "9653?d?d?d?d?d?d", + "9654?d?d?d?d?d?d", + "9655?d?d?d?d?d?d", + "9656?d?d?d?d?d?d", + "9657?d?d?d?d?d?d", + "9658?d?d?d?d?d?d", + "9659?d?d?d?d?d?d", + "90520?d?d?d?d?d", + "90521?d?d?d?d?d", + "90522?d?d?d?d?d", + "90523?d?d?d?d?d", + "90524?d?d?d?d?d", + "90525?d?d?d?d?d", + "90526?d?d?d?d?d", + "90527?d?d?d?d?d", + "90528?d?d?d?d?d", + "90624?d?d?d?d?d", + "90625?d?d?d?d?d", + "90626?d?d?d?d?d", + "90627?d?d?d?d?d", + "90958?d?d?d?d?d", + "90959?d?d?d?d?d", + "96023?d?d?d?d?d", + "96024?d?d?d?d?d", + "96025?d?d?d?d?d", + "96026?d?d?d?d?d", + "96027?d?d?d?d?d", + "96028?d?d?d?d?d", + "96434?d?d?d?d?d", + "9500?d?d?d?d?d?d", + "9502?d?d?d?d?d?d", + "9516?d?d?d?d?d?d", + "9517?d?d?d?d?d?d", + "9518?d?d?d?d?d?d", + "9522?d?d?d?d?d?d", + "9523?d?d?d?d?d?d", + "9531?d?d?d?d?d?d", + "9533?d?d?d?d?d?d", + "90433?d?d?d?d?d", + "90451?d?d?d?d?d", + "90455?d?d?d?d?d", + "90460?d?d?d?d?d", + "90461?d?d?d?d?d", + "90462?d?d?d?d?d", + "90463?d?d?d?d?d", + "90464?d?d?d?d?d", + "99100?d?d?d?d?d", + "99101?d?d?d?d?d", + "99102?d?d?d?d?d", + "90062?d?d?d?d?d", + "90063?d?d?d?d?d", + "90064?d?d?d?d?d", + "90065?d?d?d?d?d", + "99900?d?d?d?d?d", + "99901?d?d?d?d?d", + "99902?d?d?d?d?d", + "99903?d?d?d?d?d", + "99904?d?d?d?d?d", + "99909?d?d?d?d?d", + "9991?d?d?d?d?d?d", + "9992?d?d?d?d?d?d", + "99322?d?d?d?d?d", + "99343?d?d?d?d?d", + "99344?d?d?d?d?d", + "99555?d?d?d?d?d", + "99559?d?d?d?d?d", + "99560?d?d?d?d?d", + "99590?d?d?d?d?d", + "95840?d?d?d?d?d", + "95856?d?d?d?d?d", + "99511?d?d?d?d?d", + "99512?d?d?d?d?d", + "999944?d?d?d?d", + "999945?d?d?d?d", + "999946?d?d?d?d", + "999947?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_plus_79", + name="MobileOper+79", + description="Перебор мобильных номеров с префиксом +79.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "+7911?d?d?d?d?d?d?d", + "+7904?d?d?d?d?d?d?d", + "+7931?d?d?d?d?d?d?d", + "+7921?d?d?d?d?d?d?d", + "+7999?d?d?d?d?d?d?d", + "+7905?d?d?d?d?d?d?d", + "+7951?d?d?d?d?d?d?d", + "+7952?d?d?d?d?d?d?d", + "+7953?d?d?d?d?d?d?d", + "+7901?d?d?d?d?d?d?d", + "+7903?d?d?d?d?d?d?d", + "+7950?d?d?d?d?d?d?d", + "+7906?d?d?d?d?d?d?d", + "+7909?d?d?d?d?d?d?d", + "+7929?d?d?d?d?d?d?d", + "+7960?d?d?d?d?d?d?d", + "+7961?d?d?d?d?d?d?d", + "+7962?d?d?d?d?d?d?d", + "+7963?d?d?d?d?d?d?d", + "+7965?d?d?d?d?d?d?d", + "+7966?d?d?d?d?d?d?d", + "+7981?d?d?d?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_89", + name="MobileOper_89", + description="Перебор мобильных номеров с префиксом 89.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "8911?d?d?d?d?d?d?d", + "8904?d?d?d?d?d?d?d", + "8931?d?d?d?d?d?d?d", + "8921?d?d?d?d?d?d?d", + "8999?d?d?d?d?d?d?d", + "8905?d?d?d?d?d?d?d", + "8951?d?d?d?d?d?d?d", + "8952?d?d?d?d?d?d?d", + "8953?d?d?d?d?d?d?d", + "8901?d?d?d?d?d?d?d", + "8903?d?d?d?d?d?d?d", + "8950?d?d?d?d?d?d?d", + "8906?d?d?d?d?d?d?d", + "8909?d?d?d?d?d?d?d", + "8929?d?d?d?d?d?d?d", + "8960?d?d?d?d?d?d?d", + "8961?d?d?d?d?d?d?d", + "8962?d?d?d?d?d?d?d", + "8963?d?d?d?d?d?d?d", + "8965?d?d?d?d?d?d?d", + "8966?d?d?d?d?d?d?d", + "8981?d?d?d?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_79", + name="MobileOper_79", + description="Перебор мобильных номеров без знака +.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "7911?d?d?d?d?d?d?d", + "7904?d?d?d?d?d?d?d", + "7931?d?d?d?d?d?d?d", + "7921?d?d?d?d?d?d?d", + "7999?d?d?d?d?d?d?d", + "7905?d?d?d?d?d?d?d", + "7951?d?d?d?d?d?d?d", + "7952?d?d?d?d?d?d?d", + "7953?d?d?d?d?d?d?d", + "7901?d?d?d?d?d?d?d", + "7903?d?d?d?d?d?d?d", + "7950?d?d?d?d?d?d?d", + "7906?d?d?d?d?d?d?d", + "7909?d?d?d?d?d?d?d", + "7929?d?d?d?d?d?d?d", + "7960?d?d?d?d?d?d?d", + "7961?d?d?d?d?d?d?d", + "7962?d?d?d?d?d?d?d", + "7963?d?d?d?d?d?d?d", + "7965?d?d?d?d?d?d?d", + "7966?d?d?d?d?d?d?d", + "7981?d?d?d?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mobile_oper_9", + name="MobileOper_9", + description="Перебор мобильных номеров без 7 и знака +.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": f"mask-{index:03d}", + "attack_mode": 3, + "mask": mask, + } + for index, mask in enumerate( + ( + "911?d?d?d?d?d?d?d", + "904?d?d?d?d?d?d?d", + "931?d?d?d?d?d?d?d", + "921?d?d?d?d?d?d?d", + "999?d?d?d?d?d?d?d", + "905?d?d?d?d?d?d?d", + "951?d?d?d?d?d?d?d", + "952?d?d?d?d?d?d?d", + "953?d?d?d?d?d?d?d", + "901?d?d?d?d?d?d?d", + "903?d?d?d?d?d?d?d", + "950?d?d?d?d?d?d?d", + "906?d?d?d?d?d?d?d", + "909?d?d?d?d?d?d?d", + "929?d?d?d?d?d?d?d", + "960?d?d?d?d?d?d?d", + "961?d?d?d?d?d?d?d", + "962?d?d?d?d?d?d?d", + "963?d?d?d?d?d?d?d", + "965?d?d?d?d?d?d?d", + "966?d?d?d?d?d?d?d", + "981?d?d?d?d?d?d?d", + ), + start=1, + ) + ], + }, + ), + StockMethod( + method_id="mask_8_digits", + name="8-digital", + description="Перебор восьмизначных числовых паролей.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": "mask-001", + "attack_mode": 3, + "mask": "?d?d?d?d?d?d?d?d", + }, + ], + }, + ), + StockMethod( + method_id="breachcompilation", + name="BreachCompilation", + description="Перебор по словарю BreachCompilation.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": "dictionary-001", + "attack_mode": 0, + "dictionary": { + "resource": "wordlist:breachcompilation", + }, + }, + ], + }, + ), + StockMethod( + method_id="insidepro_wpa", + name="insidePRO_WPA", + description="Перебор по словарю insidePRO_WPA.", + definition={ + "schema_version": 1, + "hash_mode": 22000, + "steps": [ + { + "step_id": "dictionary-001", + "attack_mode": 0, + "dictionary": { + "resource": "wordlist:insidepro-wpa", + }, + }, + ], + }, + ), +) + + +class StockMethodSeeder: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + self._methods = MethodService(conn) + + def seed(self) -> None: + with self._conn: + for stock_method in STOCK_METHODS: + if stock_method.definition is None: + continue + + existing_method = self._methods.get_method( + stock_method.method_id + ) + + if existing_method is None: + self._methods.create_method( + method_id=stock_method.method_id, + name=stock_method.name, + description=stock_method.description, + ) + else: + if existing_method["name"] != stock_method.name: + raise ValueError( + "Stock method ID is already used with a " + f"different name: {stock_method.method_id}" + ) + + existing_version = self._methods.get_method_version( + stock_method.method_id, + 1, + ) + + if existing_version is None: + self._methods.create_method_version( + method_id=stock_method.method_id, + version=1, + definition=stock_method.definition, + ) + elif existing_version["definition_json"] != ( + self._canonical_json(stock_method.definition) + ): + raise ValueError( + "Stock method version 1 already exists with " + f"different definition: {stock_method.method_id}" + ) + + @staticmethod + def _canonical_json(definition: dict[str, Any]) -> str: + import json + + return json.dumps( + definition, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) diff --git a/cracklab/server/web/__init__.py b/cracklab/server/web/__init__.py new file mode 100644 index 0000000..f525b62 --- /dev/null +++ b/cracklab/server/web/__init__.py @@ -0,0 +1,14 @@ +from flask import Blueprint + + +cracklab_bp = Blueprint( + "cracklab", + __name__, + url_prefix="/cracklab", + template_folder="templates", + static_folder="static", + static_url_path="/static", +) + + +from cracklab.server.web import routes # noqa: E402,F401 diff --git a/cracklab/server/web/routes.py b/cracklab/server/web/routes.py new file mode 100644 index 0000000..d9a5b94 --- /dev/null +++ b/cracklab/server/web/routes.py @@ -0,0 +1,408 @@ +from __future__ import annotations + +import json +from collections import Counter + +from flask import redirect, render_template, request, url_for + +from cracklab.server.db.connection import connect_database +from cracklab.server.repositories.clients import ClientsRepository +from cracklab.server.repositories.jobs import JobsRepository +from cracklab.server.repositories.methods import MethodsRepository +from cracklab.server.repositories.results import ResultsRepository +from cracklab.server.services.methods import MethodService, MethodServiceError + +from cracklab.server.web import cracklab_bp + + +@cracklab_bp.route("/") +def dashboard(): + conn = connect_database() + + try: + methods = MethodsRepository(conn).list_methods() + jobs = JobsRepository(conn).list_jobs() + clients = ClientsRepository(conn).list_clients() + results = ResultsRepository(conn).list_results() + finally: + conn.close() + + job_statuses = Counter( + row["status"] + for row in jobs + ) + + recent_jobs = jobs[:10] + + method_names = { + row["id"]: row["name"] + for row in methods + } + + client_names = { + row["id"]: row["name"] + for row in clients + } + + return render_template( + "dashboard.html", + active_page="dashboard", + methods_count=len(methods), + jobs_count=len(jobs), + clients_count=len(clients), + results_count=len(results), + active_jobs_count=sum( + job_statuses.get(status, 0) + for status in ( + "CREATED", + "QUEUED", + "RUNNING", + "PARTIAL", + ) + ), + job_statuses=job_statuses, + recent_jobs=recent_jobs, + method_names=method_names, + client_names=client_names, + ) + + +@cracklab_bp.route("/jobs/") +def jobs_page(): + return _placeholder( + "Jobs", + "Job management will be implemented here.", + "jobs", + ) + + +@cracklab_bp.route("/methods/") +def methods_page(): + conn = connect_database() + + try: + service = MethodService(conn) + methods = service.list_methods() + + method_rows = [] + + for method in methods: + versions = service.list_method_versions(method["id"]) + + latest = versions[-1] if versions else None + + steps_count = 0 + + if latest is not None: + try: + definition = json.loads( + latest["definition_json"] + ) + steps_count = len( + definition.get("steps", []) + ) + except (TypeError, ValueError): + steps_count = 0 + + method_rows.append( + { + "id": method["id"], + "name": method["name"], + "description": method["description"], + "created_at": method["created_at"], + "version": ( + latest["version"] + if latest is not None + else None + ), + "steps_count": steps_count, + } + ) + + finally: + conn.close() + + return render_template( + "methods.html", + active_page="methods", + methods=method_rows, + ) + + +@cracklab_bp.route("/methods/create/", methods=["GET", "POST"]) +def method_create_page(): + error = None + + if request.method == "POST": + try: + name = request.form.get("name", "").strip() + description = request.form.get( + "description", + "", + ).strip() + + hash_mode_raw = request.form.get( + "hash_mode", + "22000", + ).strip() + + if not name: + raise MethodServiceError( + "Введите название метода." + ) + + if hash_mode_raw != "22000": + raise MethodServiceError( + "Сейчас поддерживается только hash mode 22000." + ) + + hash_mode = 22000 + + steps = _build_steps_from_form() + + definition = { + "schema_version": 1, + "hash_mode": hash_mode, + "steps": steps, + } + + conn = connect_database() + + try: + service = MethodService(conn) + + with conn: + method_id = service.create_method( + name=name, + description=description or None, + ) + + service.create_method_version( + method_id=method_id, + version=1, + definition=definition, + ) + + finally: + conn.close() + + return redirect( + url_for( + "cracklab.methods_page", + ) + ) + + except (MethodServiceError, ValueError) as exc: + error = str(exc) + + return render_template( + "method_create.html", + active_page="methods", + error=error, + ) + + +def _build_steps_from_form() -> list[dict]: + step_count_raw = request.form.get( + "step_count", + "1", + ).strip() + + try: + step_count = int(step_count_raw) + except ValueError as exc: + raise MethodServiceError( + "Некорректное количество шагов." + ) from exc + + if step_count < 1: + raise MethodServiceError( + "Метод должен содержать хотя бы один шаг." + ) + + steps = [] + + for index in range(1, step_count + 1): + prefix = f"step_{index}" + + attack_mode_raw = request.form.get( + f"{prefix}_attack_mode", + "", + ).strip() + + if not attack_mode_raw: + raise MethodServiceError( + f"Для шага {index} не выбран attack mode." + ) + + try: + attack_mode = int(attack_mode_raw) + except ValueError as exc: + raise MethodServiceError( + f"Некорректный attack mode в шаге {index}." + ) from exc + + if attack_mode not in (0, 1, 3, 6, 7): + raise MethodServiceError( + f"Attack mode {attack_mode} " + f"не поддерживается клиентом CrackLab." + ) + + step = { + "step_id": f"step-{index:03d}", + "attack_mode": attack_mode, + } + + workload_raw = request.form.get( + f"{prefix}_workload_profile", + "2", + ).strip() + + if workload_raw: + try: + workload_profile = int(workload_raw) + except ValueError as exc: + raise MethodServiceError( + f"Некорректный workload profile " + f"в шаге {index}." + ) from exc + + if workload_profile not in (1, 2, 3, 4): + raise MethodServiceError( + f"Workload profile в шаге {index} " + "должен быть от 1 до 4." + ) + + step["workload_profile"] = workload_profile + + if attack_mode == 0: + step["dictionary"] = { + "resource": _get_dictionary( + prefix, + "dictionary", + index, + ), + } + + elif attack_mode == 1: + step["dictionaries"] = [ + { + "resource": _get_dictionary( + prefix, + "dictionary_1", + index, + ), + }, + { + "resource": _get_dictionary( + prefix, + "dictionary_2", + index, + ), + }, + ] + + elif attack_mode == 3: + step["mask"] = _get_mask( + prefix, + index, + ) + + elif attack_mode == 6: + step["dictionary"] = { + "resource": _get_dictionary( + prefix, + "dictionary", + index, + ), + } + step["mask"] = _get_mask( + prefix, + index, + ) + + elif attack_mode == 7: + step["mask"] = _get_mask( + prefix, + index, + ) + step["dictionary"] = { + "resource": _get_dictionary( + prefix, + "dictionary", + index, + ), + } + + steps.append(step) + + return steps + + +def _get_dictionary( + prefix: str, + field: str, + index: int, +) -> str: + value = request.form.get( + f"{prefix}_{field}", + "", + ).strip() + + if not value: + raise MethodServiceError( + f"Для шага {index} необходимо указать словарь." + ) + + if not value.startswith("wordlist:"): + value = f"wordlist:{value}" + + return value + + +def _get_mask( + prefix: str, + index: int, +) -> str: + value = request.form.get( + f"{prefix}_mask", + "", + ).strip() + + if not value: + raise MethodServiceError( + f"Для шага {index} необходимо указать маску." + ) + + return value + + +@cracklab_bp.route("/clients/") +def clients_page(): + return _placeholder( + "Clients", + "Client management will be implemented here.", + "clients", + ) + + +@cracklab_bp.route("/results/") +def results_page(): + return _placeholder( + "Results", + "Result history will be implemented here.", + "results", + ) + + +def _placeholder( + title: str, + description: str, + active_page: str, +): + return render_template( + "placeholder.html", + active_page=active_page, + title=title, + description=description, + ) diff --git a/cracklab/server/web/static/cracklab.css b/cracklab/server/web/static/cracklab.css new file mode 100644 index 0000000..1da06d9 --- /dev/null +++ b/cracklab/server/web/static/cracklab.css @@ -0,0 +1,785 @@ +@font-face { + font-family: "Bender"; + + src: + url("fonts/Bender.woff2") format("woff2"), + url("fonts/Bender.woff") format("woff"); + + font-weight: 400; + font-style: normal; +} + + +@font-face { + font-family: "Bender"; + + src: + url("fonts/Bender-Bold.woff2") format("woff2"), + url("fonts/Bender-Bold.woff") format("woff"); + + font-weight: 700; + font-style: normal; +} + + +@font-face { + font-family: "Bender"; + + src: + url("fonts/Bender-Light.woff2") format("woff2"), + url("fonts/Bender-Light.woff") format("woff"); + + font-weight: 300; + font-style: normal; +} + + +:root { + --bg: #0f141a; + --surface: #171e26; + --surface-light: #1c252f; + --border: #2b3743; + + --text: #e6edf3; + --muted: #8b98a6; + + --green: #45d483; + --yellow: #e5c07b; + --red: #ef6262; + --accent: #69a7ff; + + --terminal: #0a0f14; +} + + +* { + box-sizing: border-box; +} + + +html { + min-height: 100%; +} + + +body { + margin: 0; + padding: 0; + + min-height: 100vh; + + font-family: + "Bender", + Arial, + Helvetica, + sans-serif; + + background: var(--bg); + color: var(--text); +} + + +a { + color: var(--accent); + text-decoration: none; +} + + +a:hover { + color: #9bc4ff; +} + + +.cracklab-header { + position: sticky; + top: 0; + + z-index: 1000; + + width: 100%; + + background: rgba(15, 20, 26, 0.96); + + border-bottom: 1px solid var(--border); + + backdrop-filter: blur(12px); +} + + +.cracklab-header-inner { + width: 100%; + + max-width: 1800px; + + margin: 0 auto; + + min-height: 68px; + + display: flex; + + align-items: center; + + gap: 36px; + + padding: 0 30px; +} + + +.cracklab-brand { + flex: 0 0 auto; + + display: flex; + + flex-direction: column; + + justify-content: center; + + color: var(--text); + + text-decoration: none; + + white-space: nowrap; +} + + +.cracklab-brand:hover { + color: var(--text); + + text-decoration: none; +} + + +.cracklab-brand-title { + font-size: 19px; + font-weight: 700; + + letter-spacing: 0.4px; + + line-height: 1.1; +} + + +.cracklab-brand-subtitle { + margin-top: 3px; + + color: var(--muted); + + font-size: 12px; + font-weight: 400; + + letter-spacing: 0.7px; + + line-height: 1.1; +} + + +.cracklab-nav { + display: flex; + + align-items: center; + + gap: 6px; + + min-width: 0; + + overflow-x: auto; + + scrollbar-width: thin; +} + + +.cracklab-nav a { + display: inline-flex; + + align-items: center; + + min-height: 38px; + + padding: 0 14px; + + border-radius: 7px; + + color: var(--muted); + + font-size: 13px; + font-weight: 700; + + letter-spacing: 0.7px; + + white-space: nowrap; + + transition: + color 0.15s ease, + background 0.15s ease; +} + + +.cracklab-nav a:hover { + color: var(--text); + + background: var(--surface-light); + + text-decoration: none; +} + + +.cracklab-nav a.active { + color: var(--text); + + background: var(--surface-light); + + box-shadow: + inset 0 -2px 0 var(--accent); +} + + +.cracklab-content { + width: 100%; + + max-width: 1800px; + + margin: 0 auto; + + padding: 30px; +} + + +.page-title { + margin-top: 0; + margin-bottom: 8px; + + font-size: 34px; + font-weight: 700; + + letter-spacing: 0.2px; +} + + +.page-description { + color: var(--muted); + + margin-bottom: 30px; + + font-size: 15px; +} + +.methods-page { + width: 100%; +} + + +.methods-page-header { + display: flex; + + align-items: flex-start; + justify-content: space-between; + + gap: 24px; + + margin-bottom: 30px; +} + + +.methods-page-header .page-description { + margin-bottom: 0; +} + + +.methods-button, +.methods-button-secondary { + display: inline-flex; + align-items: center; + justify-content: center; + + min-height: 42px; + padding: 10px 18px; + + border: 2px outset ButtonFace; + border-radius: 7px; + + font: inherit; + font-size: 14px; + font-weight: 700; + + cursor: pointer; + text-decoration: none; + + transition: + background 0.15s ease, + color 0.15s ease, + transform 0.15s ease; +} + +.methods-button { + background: var(--accent); + color: #0f141a; +} + +.methods-button:hover { + background: #8abaff; + color: #0f141a; + text-decoration: none; +} + +.methods-button:active { + border-style: inset; + transform: translateY(1px); +} + +.methods-button-secondary { + background: var(--surface-light); + color: var(--text); +} + +.methods-button-secondary:hover { + background: var(--border); + color: var(--text); + text-decoration: none; +} + +.methods-button-secondary:active { + border-style: inset; + transform: translateY(1px); +} + + +.methods-list { + display: grid; + + gap: 14px; +} + + +.method-card { + display: flex; + + align-items: center; + justify-content: space-between; + + gap: 30px; + + padding: 20px 22px; + + background: var(--surface); + + border: 1px solid var(--border); + border-radius: 12px; + + box-shadow: + 0 2px 10px rgba(0, 0, 0, 0.20); +} + + +.method-card-main { + min-width: 0; +} + + +.method-card-title { + margin-bottom: 7px; + + color: var(--text); + + font-size: 20px; + font-weight: 700; +} + + +.method-card-description { + margin-bottom: 9px; + + color: var(--muted); + + font-size: 14px; + line-height: 1.5; +} + + +.method-card-id { + color: var(--muted); + + font-family: monospace; + font-size: 12px; +} + + +.method-card-meta { + display: flex; + + flex-shrink: 0; + + gap: 28px; +} + + +.method-meta-item { + min-width: 80px; +} + + +.method-meta-item span { + display: block; + + margin-bottom: 5px; + + color: var(--muted); + + font-size: 12px; +} + + +.method-meta-item strong { + color: var(--text); + + font-size: 14px; + font-weight: 700; +} + + +.method-empty { + padding: 50px 30px; + + text-align: center; + + background: var(--surface); + + border: 1px dashed var(--border); + border-radius: 12px; +} + + +.method-empty-title { + margin-bottom: 10px; + + color: var(--text); + + font-size: 21px; + font-weight: 700; +} + + +.method-empty-description { + max-width: 520px; + + margin: 0 auto 24px; + + color: var(--muted); + + font-size: 14px; + line-height: 1.6; +} + +.stats-grid { + display: grid; + + grid-template-columns: + repeat( + auto-fit, + minmax(180px, 1fr) + ); + + gap: 18px; + + margin-bottom: 24px; +} + + +.stat-card { + background: var(--surface); + + border: 1px solid var(--border); + + border-radius: 10px; + + padding: 18px; + + text-align: center; +} + + +.stat-value { + margin-bottom: 8px; + + color: var(--accent); + + font-size: 34px; + font-weight: 700; +} + + +.stat-title { + color: var(--muted); + + font-size: 14px; +} + + +.dashboard-grid { + display: grid; + + grid-template-columns: + minmax(260px, 0.35fr) + minmax(500px, 1fr); + + gap: 24px; + + align-items: start; +} + + +.card { + background: var(--surface); + + border: 1px solid var(--border); + + border-radius: 12px; + + padding: 22px; + + margin-bottom: 24px; + + box-shadow: + 0 2px 10px rgba(0, 0, 0, 0.20); +} + + +.card h2 { + margin-top: 0; + margin-bottom: 20px; + + color: var(--text); + + font-size: 21px; +} + + +.table-container { + overflow-x: auto; + overflow-y: auto; + + max-height: 700px; + + border: 1px solid var(--border); + + border-radius: 10px; +} + + +table { + width: 100%; + + border-collapse: collapse; +} + + +th { + background: var(--surface-light); + + color: var(--text); + + font-weight: 700; + + text-align: left; + + padding: 12px; + + border-bottom: 2px solid var(--border); + + position: sticky; + top: 0; + + z-index: 2; +} + + +td { + padding: 10px 12px; + + border-bottom: 1px solid var(--border); + + vertical-align: top; + + color: var(--text); +} + + +tbody tr:hover { + background: rgba(105, 167, 255, 0.05); +} + + +.status-list { + display: flex; + + flex-direction: column; + + gap: 10px; +} + + +.status-row { + display: flex; + + align-items: center; + + justify-content: space-between; + + gap: 12px; + + padding-bottom: 10px; + + border-bottom: 1px solid var(--border); +} + + +.status-row:last-child { + padding-bottom: 0; + + border-bottom: 0; +} + + +.badge { + display: inline-flex; + + align-items: center; + + min-height: 24px; + + padding: 0 9px; + + border-radius: 6px; + + font-size: 11px; + font-weight: 700; + + letter-spacing: 0.5px; + + background: var(--surface-light); + + color: var(--muted); +} + + +.badge-created, +.badge-queued { + color: var(--yellow); +} + + +.badge-running, +.badge-partial { + color: var(--accent); +} + + +.badge-completed { + color: var(--green); +} + + +.badge-failed, +.badge-cancelled { + color: var(--red); +} + + +.muted { + color: var(--muted); +} + + +.empty-state { + padding: 35px 20px; + + color: var(--muted); + + text-align: center; + + border: 1px dashed var(--border); + + border-radius: 8px; +} + + +@media (max-width: 900px) { + + .cracklab-header-inner { + align-items: flex-start; + + flex-direction: column; + + gap: 12px; + + padding-top: 14px; + padding-bottom: 14px; + } + + + .cracklab-nav { + width: 100%; + } + + + .cracklab-content { + padding: 20px; + } + + .methods-page-header { + align-items: stretch; + + flex-direction: column; + + gap: 16px; + } + + + .methods-button { + width: 100%; + } + + + .method-card { + align-items: stretch; + + flex-direction: column; + + gap: 20px; + } + + + .method-card-meta { + width: 100%; + + justify-content: space-between; + } + + .dashboard-grid { + grid-template-columns: 1fr; + } + +} + + +@media (max-width: 600px) { + + .cracklab-content { + padding: 15px; + } + + + .page-title { + font-size: 28px; + } + + + .stat-value { + font-size: 28px; + } + + + .card { + padding: 16px; + } + +} diff --git a/cracklab/server/web/static/fonts/Bender-Bold.woff b/cracklab/server/web/static/fonts/Bender-Bold.woff new file mode 100644 index 0000000..cde28f9 Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender-Bold.woff differ diff --git a/cracklab/server/web/static/fonts/Bender-Bold.woff2 b/cracklab/server/web/static/fonts/Bender-Bold.woff2 new file mode 100644 index 0000000..1caf36c Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender-Bold.woff2 differ diff --git a/cracklab/server/web/static/fonts/Bender-Light.woff b/cracklab/server/web/static/fonts/Bender-Light.woff new file mode 100644 index 0000000..1ed6dd5 Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender-Light.woff differ diff --git a/cracklab/server/web/static/fonts/Bender-Light.woff2 b/cracklab/server/web/static/fonts/Bender-Light.woff2 new file mode 100644 index 0000000..bbae05d Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender-Light.woff2 differ diff --git a/cracklab/server/web/static/fonts/Bender.woff b/cracklab/server/web/static/fonts/Bender.woff new file mode 100644 index 0000000..92f4b54 Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender.woff differ diff --git a/cracklab/server/web/static/fonts/Bender.woff2 b/cracklab/server/web/static/fonts/Bender.woff2 new file mode 100644 index 0000000..39df036 Binary files /dev/null and b/cracklab/server/web/static/fonts/Bender.woff2 differ diff --git a/cracklab/server/web/templates/base.html b/cracklab/server/web/templates/base.html new file mode 100644 index 0000000..44fdf42 --- /dev/null +++ b/cracklab/server/web/templates/base.html @@ -0,0 +1,95 @@ + + + + + + + + + + {% block title %} + CrackLab + {% endblock %} + + + + + + + +
+ + + +
+ +
+ + {% block content %} + {% endblock %} + +
+ + + + diff --git a/cracklab/server/web/templates/dashboard.html b/cracklab/server/web/templates/dashboard.html new file mode 100644 index 0000000..c8f53e6 --- /dev/null +++ b/cracklab/server/web/templates/dashboard.html @@ -0,0 +1,215 @@ +{% extends "base.html" %} + +{% block title %} + CrackLab — Dashboard +{% endblock %} + +{% block content %} + +

+ CrackLab +

+ +
+ Job and cracking coverage management. +
+ + +
+ +
+
+ {{ methods_count }} +
+ +
+ Methods +
+
+ + +
+
+ {{ jobs_count }} +
+ +
+ Jobs +
+
+ + +
+
+ {{ active_jobs_count }} +
+ +
+ Active Jobs +
+
+ + +
+
+ {{ clients_count }} +
+ +
+ Clients +
+
+ + +
+
+ {{ results_count }} +
+ +
+ Results +
+
+ +
+ + +
+ +
+ +

+ Job Status +

+ +
+ + {% for status in ( + "CREATED", + "QUEUED", + "RUNNING", + "PARTIAL", + "COMPLETED", + "FAILED", + "CANCELLED" + ) %} + +
+ + + + {{ status }} + + + + + {{ job_statuses.get(status, 0) }} + + +
+ + {% endfor %} + +
+ +
+ + +
+ +

+ Recent Jobs +

+ + {% if recent_jobs %} + +
+ + + + + + + + + + + + + + + + {% for job in recent_jobs %} + + + + + + + + + + + + + + + + {% endfor %} + + + +
JobMethodStatusHashesClient
+ + {{ job["id"] }} + + + {{ method_names.get( + job["method_id"], + job["method_id"] + ) }} + + v{{ job["method_version"] }} + + + + {{ job["status"] }} + + + {{ job["hash_count"] }} + + {% if job["client_id"] %} + {{ client_names.get( + job["client_id"], + job["client_id"] + ) }} + {% else %} + + — + + {% endif %} +
+ +
+ + {% else %} + +
+ No jobs have been issued yet. +
+ + {% endif %} + +
+ +
+ +{% endblock %} diff --git a/cracklab/server/web/templates/method_create.html b/cracklab/server/web/templates/method_create.html new file mode 100644 index 0000000..eeb7ca1 --- /dev/null +++ b/cracklab/server/web/templates/method_create.html @@ -0,0 +1,1700 @@ +{% extends "base.html" %} + +{% block title %} + CrackLab — Create Method +{% endblock %} + +{% block content %} + + + + +
+ +
+ +
+

+ Создание метода +

+ +
+ Новый рабочий метод будет сохранён в базе данных. +
+
+ +
+ + + {% if error %} + +
+ {{ error }} +
+ + {% endif %} + + +
+ +
+ +

+ Основная информация +

+ +
+ +
+ + + +
+ + +
+ + + + + +
+ Сейчас CrackLab работает с WPA/WPA2 hash mode 22000. + Дополнительные Wi-Fi hash modes можно будет добавить + позже. +
+ +
+ + +
+ + + + + +
+ +
+ +
+ + +
+ +

+ Шаги метода +

+ +
+ +
+ + + + + +
+ + + +
+ +
+
+ Список масок +
+ + + +
+ Только для attack mode 3. + Одна маска на строку. + Пустые строки игнорируются. + Дубликаты удаляются после нормализации. + Минимальная длина кандидата — 8 позиций. +
+ +
+ + +
+
+
+ +
+ + + + + Отмена + + +
+ +
+ +
+ + + + +{% endblock %} diff --git a/cracklab/server/web/templates/methods.html b/cracklab/server/web/templates/methods.html new file mode 100644 index 0000000..c311d5f --- /dev/null +++ b/cracklab/server/web/templates/methods.html @@ -0,0 +1,128 @@ +{% extends "base.html" %} + +{% block title %} + CrackLab — Methods +{% endblock %} + +{% block content %} + +
+ +
+ +
+

+ Methods +

+ +
+ Рабочие методы перебора, сохранённые в базе данных. +
+
+ + {% if methods %} + + + Создать метод + + {% endif %} + +
+ + + {% if methods %} + +
+ + {% for method in methods %} + +
+ +
+ +
+ {{ method.name }} +
+ + {% if method.description %} +
+ {{ method.description }} +
+ {% endif %} + +
+ {{ method.id }} +
+ +
+ + +
+ +
+ Version + + + {% if method.version %} + {{ method.version }} + {% else %} + — + {% endif %} + +
+ + +
+ Steps + + + {{ method.steps_count }} + +
+ + +
+ Created + + + {{ method.created_at }} + +
+ +
+ +
+ + {% endfor %} + +
+ + {% else %} + +
+ +
+ Методов пока нет +
+ +
+ Создайте первый метод, чтобы начать + выдавать задания CrackLab. +
+ + + + Создать метод + + +
+ + {% endif %} + +
+ +{% endblock %} diff --git a/cracklab/server/web/templates/placeholder.html b/cracklab/server/web/templates/placeholder.html new file mode 100644 index 0000000..cb232f8 --- /dev/null +++ b/cracklab/server/web/templates/placeholder.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} + +{% block title %} + CrackLab — {{ title }} +{% endblock %} + +{% block content %} + +

+ {{ title }} +

+ +
+ {{ description }} +
+ +
+ +
+ This section is under development. +
+ +
+ +{% endblock %} diff --git a/gui/__init__.py b/gui/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/gui/app.py b/gui/app.py new file mode 100644 index 0000000..e8b587f --- /dev/null +++ b/gui/app.py @@ -0,0 +1,2611 @@ +import os +import sys +import signal +import subprocess +import threading +import logging +import secrets +import time +import tempfile +from collections import deque +from datetime import datetime, timezone +from pathlib import Path + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +sys.path.insert( + 0, + str(PROJECT_ROOT / "src") +) + +from flask import ( + Flask, + Response, + jsonify, + redirect, + render_template, + request, + send_file, + send_from_directory, + url_for, +) + +from reports.database import close as close_database +from reports.database import connect as connect_database +from reports.dashboard import ( + generate_capture_sessions, + generate_dashboard, +) +from cracklab.server.web import cracklab_bp +from reports.search import ( + build_hash_export, + build_search_data, + normalize_criteria, + render_search_page, +) +from reports.hashcat import ( + build_all_hash_export, + build_export_filename, + import_hashcat_show, +) +from reports.hashcat_page import ( + render_hashcat_page, +) +from reports.trips_page import render_trips_page +from reports.wifitrip import ( + export_wifitrip, + import_wifitrip, + validate_wifitrip, +) +from reports.session_page import render_session_page +from reports.access_points import render_access_points_page +from reports.access_points_page import render_access_point_page +from reports.template import ReportContext +from reports.vendors import render_vendors_page +from vendor_service import VendorService +from sudo import SudoChecker +from config import Config +from gps_test import GPSTestService + +app = Flask( + __name__, + template_folder=str( + PROJECT_ROOT / "gui" / "templates" + ), + static_folder=str( + PROJECT_ROOT / "gui" / "static" + ) +) + +app.register_blueprint( + cracklab_bp +) + +@app.before_request +def scanner_navigation_guard(): + + status = get_scanner_status() + + if not status["running"]: + return None + + if ( + request.endpoint is not None + and request.endpoint.startswith("cracklab.") + ): + return None + + allowed_endpoints = { + "index", + "api_status", + "scanner_stop", + "api_gps_test", + "gps_test_stop", + "static" + } + + if request.endpoint in allowed_endpoints: + return None + + return redirect( + url_for("index") + ) + + +scanner_process = None + +scanner_health = "READY" + +scanner_stopped_at = None + +scanner_output = deque( + maxlen=500 +) + +scanner_lock = threading.Lock() + +vendor_previews = {} + +vendor_preview_lock = threading.Lock() + +vendor_update_job = None + +vendor_update_lock = threading.Lock() + +gps_test_service = None + +gps_test_lock = threading.Lock() + +def check_sudo(): + + try: + + result = subprocess.run( + [ + "sudo", + "-n", + "-v" + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + + except KeyboardInterrupt: + return False + + except Exception: + return False + + return result.returncode == 0 + + +def sudo_keepalive(): + + checker = SudoChecker() + + while True: + + time.sleep(60) + + checker.refresh() + +def gps_test_output(message): + + with scanner_lock: + + scanner_output.append( + message + ) + + +def get_gps_test_status(): + + with gps_test_lock: + + service = gps_test_service + + if service is None: + + return { + "running": False, + "state": "READY", + "nmea_received": False, + "fix_received": False, + "nmea_count": 0, + "fix_count": 0, + "latitude": None, + "longitude": None, + "error": None + } + + return { + "running": service.running, + "state": service.state, + "nmea_received": service.nmea_received, + "fix_received": service.fix_received, + "nmea_count": service.nmea_count, + "fix_count": service.fix_count, + "latitude": service.latitude, + "longitude": service.longitude, + "error": service.error + } + +def get_scanner_status(): + + global scanner_health + global scanner_stopped_at + global scanner_process + + with scanner_lock: + + process = scanner_process + + if ( + scanner_health == "STOPPED" + and + scanner_stopped_at is not None + and + time.time() - scanner_stopped_at >= 5 + ): + + scanner_health = "READY" + + scanner_stopped_at = None + + if process is None: + return { + "running": False, + "pid": None, + "health": scanner_health + } + + return_code = process.poll() + + if return_code is None: + return { + "running": True, + "pid": process.pid, + "health": scanner_health + } + + scanner_process = None + scanner_health = "STOPPED" + scanner_stopped_at = time.time() + + scanner_output.append( + f"[GUI] Scanner process exited with code {return_code}." + ) + + return { + "running": False, + "pid": process.pid, + "health": scanner_health, + "return_code": return_code + } + + +def read_scanner_output(process): + + global scanner_health + + try: + + for line in iter( + process.stdout.readline, + "" + ): + + line = line.rstrip() + + if line.startswith( + "ScannerState:" + ): + + state = line.split( + ":", + 1 + )[1].strip() + + if state in { + "READY", + "ACTIVE", + "WARNING", + "STOPPED" + }: + + if ( + state != "STOPPED" + or + process.poll() is not None + ): + + with scanner_lock: + + scanner_health = state + + continue + + if line: + + with scanner_lock: + + scanner_output.append( + line + ) + + except Exception as error: + + with scanner_lock: + + scanner_output.append( + f"[GUI] Output reader error: {error}" + ) + + finally: + + try: + + process.stdout.close() + + except Exception: + + pass + + +def get_wifi_interfaces(): + + try: + + result = subprocess.run( + [ + "sudo", + "-n", + "iw", + "dev" + ], + + cwd=PROJECT_ROOT, + + capture_output=True, + + text=True, + + timeout=10 + + ) + + except Exception as error: + + return [], str(error) + + + if result.returncode != 0: + + error = ( + result.stderr.strip() + or + f"iw exited with code {result.returncode}" + ) + + return [], error + + + interfaces = [] + + current = None + + for line in result.stdout.splitlines(): + + line = line.strip() + + if line.startswith("Interface"): + + parts = line.split() + + if len(parts) >= 2: + + current = parts[1] + + interfaces.append(current) + + + return interfaces, None + +def get_wifi_channels(interface): + + try: + + result = subprocess.run( + [ + "sudo", + "-n", + str( + PROJECT_ROOT + / "bin" + / "hcxdumptool" + ), + "-I", + interface + ], + + cwd=PROJECT_ROOT, + + capture_output=True, + + text=True, + + timeout=30 + ) + + except Exception as error: + + return { + "2.4": [], + "5": [], + "6": [], + "error": str(error) + } + + + output = ( + result.stdout + + + "\n" + + + result.stderr + ) + + + if result.returncode != 0: + + error = ( + result.stderr.strip() + or + result.stdout.strip() + or + f"hcxdumptool exited with code " + f"{result.returncode}" + ) + + return { + "2.4": [], + "5": [], + "6": [], + "error": error + } + + + import re + + + channels = { + "2.4": [], + "5": [], + "6": [] + } + + + pattern = re.compile( + r"(\d{4,5})\s+" + r"\[\s*(\d+)\s*\]" + r"(?:\s+(disabled))?" + ) + + + seen = { + "2.4": set(), + "5": set(), + "6": set() + } + + + for line in output.splitlines(): + + matches = pattern.findall(line) + + + for frequency, channel, disabled in matches: + + frequency = int(frequency) + channel = int(channel) + + + if 2400 <= frequency < 2500: + + band = "2.4" + suffix = "a" + + elif 5000 <= frequency < 5925: + + band = "5" + suffix = "b" + + elif 5925 <= frequency <= 7125: + + band = "6" + suffix = "c" + + else: + + continue + + + key = ( + channel, + frequency + ) + + + if key in seen[band]: + + continue + + + seen[band].add(key) + + + channels[band].append( + { + "channel": channel, + "frequency": frequency, + "value": f"{channel}{suffix}", + "available": not bool(disabled) + } + ) + + + for band in channels: + + channels[band].sort( + key=lambda item: ( + item["channel"], + item["frequency"] + ) + ) + + + return { + "2.4": channels["2.4"], + "5": channels["5"], + "6": channels["6"], + "error": None + } + +def read_config(): + + import yaml + + config_file = ( + PROJECT_ROOT + / + "config" + / + "config.yaml" + ) + + try: + + with open( + config_file, + "r" + ) as file: + + data = yaml.safe_load(file) + + gps = data["gps"] + + if "source" not in gps: + + data["gps"] = { + "source": "gpsrelay", + "gpsrelay": { + "host": gps["host"], + "port": gps["port"], + }, + "gnss": { + "handler": "direct", + "direct": { + "device": + "/dev/serial/by-id/" + "usb-u-blox_AG_-_www.u-blox.com_" + "u-blox_GNSS_receiver-if00", + }, + "gpsd": {}, + "modem": { + "device": + "/dev/serial/by-id/" + "usb-Quectel_EM160R-GL_718c89b2-if01-port0", + "at_device": + "/dev/serial/by-id/" + "usb-Quectel_EM160R-GL_718c89b2-if03-port0", + }, + }, + } + + elif "gnss" in gps and "direct" not in gps["gnss"]: + + old_gnss = gps["gnss"] + + data["gps"]["gnss"] = { + "handler": old_gnss.get( + "handler", + "direct" + ), + "direct": { + "device": + old_gnss.get( + "device", + "/dev/serial/by-id/" + "usb-u-blox_AG_-_www.u-blox.com_" + "u-blox_GNSS_receiver-if00" + ) + }, + "gpsd": {}, + "modem": { + "device": + "/dev/serial/by-id/" + "usb-Quectel_EM160R-GL_718c89b2-if01-port0", + "at_device": + old_gnss.get( + "at_device", + "/dev/serial/by-id/" + "usb-Quectel_EM160R-GL_718c89b2-if03-port0" + ), + }, + } + + return data + + except Exception as error: + + return { + "_error": str(error) + } + + +def save_config(data): + + import re + import yaml + + config_file = ( + PROJECT_ROOT + / + "config" + / + "config.yaml" + ) + + with open( + config_file, + "r" + ) as file: + + text = file.read() + + def yaml_string(value): + + import json + + return json.dumps( + str(value), + ensure_ascii=False + ) + + from zoneinfo import ZoneInfo + + timezone_name = str( + data["timezone"] + ).strip() + + if not timezone_name: + raise RuntimeError( + "Timezone cannot be empty." + ) + + try: + ZoneInfo(timezone_name) + except Exception as error: + raise RuntimeError( + f"Invalid timezone: {timezone_name}" + ) from error + + values = { + "database": { + "file": yaml_string( + data["database"]["file"] + ), + }, + + "vendor": { + "database": yaml_string( + data["vendor"]["database"] + ), + }, + + "wifi": { + "enable_2_4ghz": ( + "true" + if data["wifi"]["enable_2_4ghz"] + else + "false" + ), + "channels_2_4ghz": yaml_string( + data["wifi"]["channels_2_4ghz"] + ), + "enable_5ghz": ( + "true" + if data["wifi"]["enable_5ghz"] + else + "false" + ), + "channels_5ghz": yaml_string( + data["wifi"]["channels_5ghz"] + ), + "enable_6ghz": ( + "true" + if data["wifi"]["enable_6ghz"] + else + "false" + ), + "channels_6ghz": yaml_string( + data["wifi"]["channels_6ghz"] + ), + "filtermode": str( + data["wifi"]["filtermode"] + ), + "extra_args": yaml_string( + data["wifi"]["extra_args"] + ), + }, + + "captures": { + "directory": yaml_string( + data["captures"]["directory"] + ), + }, + + "reports": { + "recent_sessions_limit": str( + data["reports"]["recent_sessions_limit"] + ), + }, + + "logging": { + "level": yaml_string( + data["logging"]["level"] + ), + }, + + "status": { + "interval": str( + data["status"]["interval"] + ), + }, + } + + timezone_pattern = ( + r"(^timezone:[ \t]*)" + r"([^#\n]*?)" + r"([ \t]*#.*)?$" + ) + + text, count = re.subn( + timezone_pattern, + lambda item: ( + item.group(1) + + + yaml_string( + timezone_name + ) + + + ( + item.group(3) + if item.group(3) + else + "" + ) + ), + text, + count=1, + flags=re.MULTILINE + ) + + if count != 1: + raise RuntimeError( + "Configuration key not found: timezone" + ) + + gps_pattern = ( + r"(^gps:[ \t]*\n)" + r"(.*?)(?=^[A-Za-z_][A-Za-z0-9_]*:[ \t]*$|\Z)" + ) + + gps_match = re.search( + gps_pattern, + text, + flags=re.MULTILINE | re.DOTALL + ) + + if not gps_match: + + raise RuntimeError( + "Configuration section not found: gps" + ) + + gps_text = ( + " source: " + + yaml_string( + data["gps"]["source"] + ) + + "\n" + " gpsrelay:\n" + " host: " + + yaml_string( + data["gps"]["gpsrelay"]["host"] + ) + + "\n" + " port: " + + str( + data["gps"]["gpsrelay"]["port"] + ) + + "\n" + " gnss:\n" + " handler: " + + yaml_string( + data["gps"]["gnss"]["handler"] + ) + + "\n" + " direct:\n" + " device: " + + yaml_string( + data["gps"]["gnss"]["direct"]["device"] + ) + + "\n" + " gpsd: {}\n" + " modem:\n" + " device: " + + yaml_string( + data["gps"]["gnss"]["modem"]["device"] + ) + + "\n" + " at_device: " + + yaml_string( + data["gps"]["gnss"]["modem"]["at_device"] + ) + + "\n" + ) + + text = ( + text[:gps_match.start(2)] + + + gps_text + + + text[gps_match.end(2):] + ) + + for section, section_values in values.items(): + + section_pattern = ( + r"(^" + + re.escape(section) + + r":[ \t]*\n)" + r"(.*?)(?=^[A-Za-z_][A-Za-z0-9_]*:[ \t]*$|\Z)" + ) + + match = re.search( + section_pattern, + text, + flags=re.MULTILINE | re.DOTALL + ) + + if not match: + + raise RuntimeError( + f"Configuration section not found: {section}" + ) + + section_text = match.group(2) + + for key, value in section_values.items(): + + pattern = ( + r"(^[ \t]+" + + re.escape(key) + + r":[ \t]*)" + + r"([^#\n]*?)" + + r"([ \t]*#.*)?$" + ) + + section_text, count = re.subn( + pattern, + lambda item: ( + item.group(1) + + + value + + + ( + item.group(3) + if item.group(3) + else + "" + ) + ), + section_text, + count=1, + flags=re.MULTILINE + ) + + if count != 1: + + raise RuntimeError( + f"Configuration key not found: " + f"{section}.{key}" + ) + + text = ( + text[:match.start(2)] + + + section_text + + + text[match.end(2):] + ) + + with open( + config_file, + "w" + ) as file: + + file.write(text) + +def render_report( + render_function, + *args, + **kwargs +): + + conn = connect_database() + + try: + + context = ReportContext( + mode="server" + ) + + html = render_function( + conn, + *args, + context=context, + **kwargs + ) + + return Response( + html, + mimetype="text/html" + ) + + finally: + close_database(conn) + +@app.route("/reports/vendors/") +def reports_vendors(): + + config = read_config() + + if "_error" in config: + + return jsonify( + { + "error": config["_error"] + } + ), 500 + + vendor_config = config.get( + "vendor", + {} + ) + + database_config = config.get( + "database", + {} + ) + + service = VendorService( + PROJECT_ROOT / vendor_config["database"], + PROJECT_ROOT / database_config["file"], + vendor_config["sources"], + vendor_config.get( + "mirrors", + {} + ) + ) + + job_id = request.args.get( + "job_id" + ) + + job = None + preview = None + token = None + + if job_id: + + with vendor_update_lock: + + if ( + vendor_update_job is not None + and vendor_update_job["id"] == job_id + ): + + job = dict( + vendor_update_job + ) + + service = job["service"] + + if job is not None: + + token = job.get( + "preview_token" + ) + + if token: + + with vendor_preview_lock: + + preview = vendor_previews.get( + token + ) + + return render_report( + render_vendors_page, + service, + preview, + token, + job=job + ) + +def _run_vendor_update( + job_id, + service +): + + global vendor_update_job + + def progress_callback( + stage, + source=None, + message=None + ): + + with vendor_update_lock: + + if ( + vendor_update_job is None + or vendor_update_job["id"] != job_id + ): + return + + vendor_update_job["stage"] = stage + vendor_update_job["source"] = source + vendor_update_job["message"] = message + + try: + + preview = service.prepare_update( + progress_callback=progress_callback + ) + + token = secrets.token_urlsafe( + 32 + ) + + with vendor_preview_lock: + + while len(vendor_previews) >= 5: + + old_token, old_preview = ( + next( + iter( + vendor_previews.items() + ) + ) + ) + + del vendor_previews[ + old_token + ] + + service._cleanup_preview( + old_preview + ) + + vendor_previews[ + token + ] = preview + + with vendor_update_lock: + + if ( + vendor_update_job is not None + and vendor_update_job["id"] == job_id + ): + + vendor_update_job["status"] = "ready" + vendor_update_job["stage"] = "ready" + vendor_update_job["source"] = None + vendor_update_job["message"] = ( + "Обновление готово к применению" + ) + vendor_update_job["preview_token"] = token + vendor_update_job["error"] = None + + except Exception as error: + + with vendor_update_lock: + + if ( + vendor_update_job is not None + and vendor_update_job["id"] == job_id + ): + + vendor_update_job["status"] = "error" + vendor_update_job["stage"] = "error" + vendor_update_job["message"] = None + vendor_update_job["error"] = str( + error + ) + + +@app.route( + "/reports/vendors/update", + methods=["POST"] +) +def reports_vendors_update(): + + global vendor_update_job + + config = read_config() + + if "_error" in config: + + return jsonify( + { + "error": config["_error"] + } + ), 500 + + vendor_config = config.get( + "vendor", + {} + ) + + database_config = config.get( + "database", + {} + ) + + service = VendorService( + PROJECT_ROOT / vendor_config["database"], + PROJECT_ROOT / database_config["file"], + vendor_config["sources"], + vendor_config.get( + "mirrors", + {} + ) + ) + + with vendor_update_lock: + + if ( + vendor_update_job is not None + and vendor_update_job["status"] == "running" + ): + + job = dict( + vendor_update_job + ) + + return render_report( + render_vendors_page, + job["service"], + job=job + ) + + job_id = secrets.token_urlsafe( + 16 + ) + + vendor_update_job = { + "id": job_id, + "status": "running", + "stage": "starting", + "source": None, + "message": "Подготовка обновления", + "error": None, + "preview_token": None, + "service": service + } + + thread = threading.Thread( + target=_run_vendor_update, + args=( + job_id, + service + ), + daemon=True + ) + + thread.start() + + job = dict( + vendor_update_job + ) + + return render_report( + render_vendors_page, + service, + job=job + ) + + +@app.route( + "/reports/vendors/update/status/" +) +def reports_vendors_update_status( + job_id +): + + with vendor_update_lock: + + if ( + vendor_update_job is None + or vendor_update_job["id"] != job_id + ): + + return jsonify( + { + "status": "missing", + "error": + "Vendor update job is missing." + } + ), 404 + + job = dict( + vendor_update_job + ) + + return jsonify( + { + "status": job["status"], + "stage": job["stage"], + "source": job["source"], + "message": job["message"], + "error": job["error"], + "preview_ready": + job["preview_token"] is not None + } + ) + +@app.route( + "/reports/vendors/apply", + methods=["POST"] +) +def reports_vendors_apply(): + + token = request.form.get( + "token", + "" + ) + + with vendor_preview_lock: + + preview = vendor_previews.pop( + token, + None + ) + + if preview is None: + + return jsonify( + { + "error": + "Vendor preview is missing or expired." + } + ), 400 + + config = read_config() + + if "_error" in config: + + return jsonify( + { + "error": config["_error"] + } + ), 500 + + vendor_config = config.get( + "vendor", + {} + ) + + database_config = config.get( + "database", + {} + ) + + service = VendorService( + PROJECT_ROOT / vendor_config["database"], + PROJECT_ROOT / database_config["file"], + vendor_config["sources"], + vendor_config.get( + "mirrors", + {} + ) + ) + + selected = { + "unknown_to_vendor": + request.form.get( + "unknown_to_vendor" + ) == "1", + "vendor_to_vendor": + request.form.get( + "vendor_to_vendor" + ) == "1", + "vendor_to_unknown": + request.form.get( + "vendor_to_unknown" + ) == "1" + } + + try: + + result = service.apply( + preview, + **selected + ) + + except Exception as error: + + return render_report( + render_vendors_page, + service, + message={ + "type": "error", + "text": str(error) + } + ) + + return render_report( + render_vendors_page, + service, + message={ + "type": "success", + "text": ( + "Update completed. " + f"OUI updated: " + f"{'yes' if result['oui_updated'] else 'no'}. " + f"WiFi AP records updated: " + f"{result['wifi_updated']}." + ) + } + ) + +@app.route("/reports/") +def reports_dashboard(): + + return render_report( + generate_dashboard + ) + + +@app.route("/reports/sessions/") +def reports_capture_sessions(): + + return render_report( + generate_capture_sessions + ) + +@app.route("/reports/trips/") +def reports_trips(): + + return render_report( + render_trips_page + ) + + +@app.route("/reports/trips/export") +def reports_trips_export(): + + filename = ( + "wifi-gps-mapper-" + f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip" + ) + + temp_file = tempfile.NamedTemporaryFile( + prefix="wifitrip-", + suffix=".tmp", + delete=False, + ) + + temp_path = Path( + temp_file.name + ) + + temp_file.close() + + output_path = ( + temp_path.with_name( + filename + ) + ) + + temp_path.unlink( + missing_ok=True + ) + + conn = connect_database() + + try: + + result = export_wifitrip( + conn, + output_path=output_path, + ) + + except Exception: + + output_path.unlink( + missing_ok=True + ) + + raise + + finally: + close_database(conn) + + response = send_file( + output_path, + as_attachment=True, + download_name=output_path.name, + mimetype="application/zip", + ) + + response.headers[ + "X-Wifitrip-Sessions" + ] = str(result["sessions"]) + + response.headers[ + "X-Wifitrip-Size" + ] = str(result["size"]) + + response.headers[ + "X-Wifitrip-Duration" + ] = str(result["duration"]) + + response.call_on_close( + lambda: output_path.unlink( + missing_ok=True + ) + ) + + return response + + +@app.route( + "/reports/trips/preflight", + methods=["POST"] +) +def reports_trips_preflight(): + + uploaded_file = request.files.get( + "wifitrip_file" + ) + + if uploaded_file is None: + return jsonify( + { + "valid": False, + "error": + "Wifitrip package is required." + } + ), 400 + + temp_file = tempfile.NamedTemporaryFile( + suffix=".wifitrip", + delete=False, + ) + + package_path = Path( + temp_file.name + ) + + try: + + uploaded_file.save( + temp_file + ) + + temp_file.close() + + result = validate_wifitrip( + package_path + ) + + return jsonify( + result + ) + + except Exception as error: + + return jsonify( + { + "valid": False, + "error": str(error), + } + ), 400 + + finally: + + if not temp_file.closed: + temp_file.close() + + package_path.unlink( + missing_ok=True + ) + + +@app.route( + "/reports/trips/import", + methods=["POST"] +) +def reports_trips_import(): + + uploaded_file = request.files.get( + "wifitrip_file" + ) + + if uploaded_file is None: + return render_report( + render_trips_page, + message={ + "type": "error", + "text": + "Wifitrip package is required.", + } + ), 400 + + temp_file = tempfile.NamedTemporaryFile( + suffix=".wifitrip", + delete=False, + ) + + package_path = Path( + temp_file.name + ) + + try: + + uploaded_file.save( + temp_file + ) + + temp_file.close() + + validation = validate_wifitrip( + package_path + ) + + if not validation.get("valid"): + + return render_report( + render_trips_page, + validation=validation, + message={ + "type": "error", + "text": ( + "Import was rejected. " + "The package is invalid and " + "no sessions were imported." + ), + } + ), 400 + + conn = connect_database() + + try: + + result = import_wifitrip( + conn, + package_path, + ) + + finally: + close_database(conn) + + if result["failed"]: + + return render_report( + render_trips_page, + import_result=result, + validation=validation, + message={ + "type": "error", + "text": ( + "Import completed with " + "failed sessions." + ), + } + ), 400 + + return render_report( + render_trips_page, + import_result=result, + validation=validation, + message={ + "type": "success", + "text": ( + "Import completed successfully." + ), + } + ) + + except Exception as error: + + return render_report( + render_trips_page, + message={ + "type": "error", + "text": ( + "Import failed: " + f"{error}" + ), + } + ), 500 + + finally: + + if not temp_file.closed: + temp_file.close() + + package_path.unlink( + missing_ok=True + ) + + +@app.route("/reports/session/") +def reports_session(session_id): + + return render_report( + render_session_page, + session_id + ) + + +@app.route("/reports/access-points/") +def reports_access_points(): + + return render_report( + render_access_points_page + ) + +@app.route("/reports/access-points/") +def reports_access_point(bssid): + + return render_report( + render_access_point_page, + bssid + ) + +@app.route("/reports/hashcat/") +def reports_hashcat(): + + return render_report( + render_hashcat_page + ) + + +@app.route("/reports/hashcat/export") +def reports_hashcat_export(): + + vendor = request.args.get( + "vendor", + "" + ).strip() + + conn = connect_database() + + try: + + if vendor: + + criteria = normalize_criteria( + vendor=vendor + ) + + if not criteria: + + return jsonify( + { + "error": + "At least one search criterion " + "is required." + } + ), 400 + + content = build_hash_export( + conn, + criteria + ) + + filename = build_export_filename( + "search", + vendor + ) + + else: + + content = build_all_hash_export( + conn + ) + + filename = build_export_filename( + "all" + ) + + return Response( + content, + mimetype="text/plain", + headers={ + "Content-Disposition": + f'attachment; filename="{filename}"' + } + ) + + except Exception as error: + + return jsonify( + { + "error": str(error) + } + ), 500 + + finally: + + close_database(conn) + +@app.route( + "/reports/hashcat/preflight", + methods=["POST"] +) +def reports_hashcat_preflight(): + + uploaded_file = request.files.get( + "hashcat_file" + ) + + if uploaded_file is None: + return jsonify( + { + "valid": False, + "error": + "Hashcat result file is required." + } + ), 400 + + try: + content = uploaded_file.read().decode( + "utf-8" + ) + except UnicodeDecodeError: + return jsonify( + { + "valid": False, + "error": + "Hashcat result file must be " + "valid UTF-8 text." + } + ), 400 + + from reports.hashcat import ( + validate_hashcat_show_file, + ) + + conn = connect_database() + + try: + + result = validate_hashcat_show_file( + conn, + content.splitlines( + keepends=True + ) + ) + + result["valid"] = ( + result["total_lines"] > 0 + and result["matched_handshakes"] > 0 + and result["invalid_lines"] == 0 + ) + + return jsonify( + result + ) + + except Exception as error: + + return jsonify( + { + "valid": False, + "error": str(error) + } + ), 500 + + finally: + + close_database(conn) + +@app.route( + "/reports/hashcat/import", + methods=["POST"] +) +def reports_hashcat_import(): + + uploaded_file = request.files.get( + "hashcat_file" + ) + + if uploaded_file is None: + return jsonify( + { + "error": + "Hashcat result file is required." + } + ), 400 + + try: + content = uploaded_file.read().decode( + "utf-8" + ) + except UnicodeDecodeError: + return jsonify( + { + "error": + "Hashcat result file must be " + "valid UTF-8 text." + } + ), 400 + + conn = connect_database() + + try: + + result = import_hashcat_show( + conn, + content.splitlines( + keepends=True + ) + ) + + if result["errors"]: + + html = render_hashcat_page( + conn, + context=ReportContext( + mode="server" + ), + import_result=result, + message={ + "type": "error", + "text": ( + "Import was rejected. " + "No credentials were committed." + ), + } + ) + + return Response( + html, + mimetype="text/html", + status=400 + ) + + html = render_hashcat_page( + conn, + context=ReportContext( + mode="server" + ), + import_result=result, + message={ + "type": "success", + "text": ( + "Import completed successfully." + ), + } + ) + + return Response( + html, + mimetype="text/html" + ) + + except Exception as error: + + return jsonify( + { + "error": str(error) + } + ), 500 + + finally: + + close_database(conn) + +@app.route("/reports/search/") +def reports_search(): + + return render_report( + render_search_page + ) + + +@app.route("/reports/search/data") +def reports_search_data(): + + criteria = normalize_criteria( + vendor=request.args.get( + "vendor", + "" + ) + ) + + if not criteria: + + return jsonify( + { + "error": + "At least one search criterion is required." + } + ), 400 + + conn = connect_database() + + try: + + data = build_search_data( + conn, + criteria + ) + + return jsonify( + data + ) + + except Exception as error: + + return jsonify( + { + "error": str(error) + } + ), 500 + + finally: + + close_database(conn) + + +@app.route("/reports/search/export") +def reports_search_export(): + + criteria = normalize_criteria( + vendor=request.args.get( + "vendor", + "" + ) + ) + + if not criteria: + + return jsonify( + { + "error": + "At least one search criterion is required." + } + ), 400 + + conn = connect_database() + + try: + + content = build_hash_export( + conn, + criteria + ) + + filename = build_export_filename( + "search", + request.args.get( + "vendor", + "" + ) + ) + + return Response( + content, + mimetype="text/plain", + headers={ + "Content-Disposition": + f'attachment; filename="{filename}"' + } + ) + + except Exception as error: + + return jsonify( + { + "error": str(error) + } + ), 500 + + finally: + + close_database(conn) + + +@app.route("/reports/static/") +def reports_static(filename): + + return send_from_directory( + PROJECT_ROOT / "reports" / "static", + filename + ) + +@app.route("/") +def index(): + + config = read_config() + + interfaces, interface_error = ( + get_wifi_interfaces() + ) + + status = get_scanner_status() + gps_test = get_gps_test_status() + + with scanner_lock: + + output = list( + scanner_output + ) + + return render_template( + "index.html", + config=config, + interfaces=interfaces, + interface_error=interface_error, + status=status, + gps_test=gps_test, + output=output + ) + + +@app.route( + "/api/status" +) +def api_status(): + + status = get_scanner_status() + gps_test = get_gps_test_status() + + with scanner_lock: + + output = list( + scanner_output + ) + + return jsonify( + { + "status": status, + "gps_test": gps_test, + "output": output + } + ) + +@app.route( + "/gps-test/start", + methods=["POST"] +) +def gps_test_start(): + + global gps_test_service + + if get_scanner_status()["running"]: + + with scanner_lock: + + scanner_output.append( + "[GUI] GPS test cannot start " + "while scanner is running." + ) + + return jsonify( + { + "ok": False, + "error": + "GPS test cannot start " + "while scanner is running." + } + ), 409 + + with gps_test_lock: + + if ( + gps_test_service is not None + and + gps_test_service.running + ): + + return jsonify( + { + "ok": False, + "error": + "GPS test is already running." + } + ), 409 + + try: + + cfg = Config() + + gps_test_service = GPSTestService( + cfg, + callback=gps_test_output + ) + + if not gps_test_service.start(): + + gps_test_service = None + + return jsonify( + { + "ok": False, + "error": + "Failed to start GPS test." + } + ), 500 + + except Exception as error: + + gps_test_service = None + + with scanner_lock: + + scanner_output.append( + f"[GUI] Failed to start GPS test: " + f"{error}" + ) + + return jsonify( + { + "ok": False, + "error": str(error) + } + ), 500 + + return jsonify( + { + "ok": True + } + ) + + +@app.route( + "/gps-test/stop", + methods=["POST"] +) +def gps_test_stop(): + + with gps_test_lock: + + service = gps_test_service + + if ( + service is None + or + not service.running + ): + + return jsonify( + { + "ok": False, + "error": + "GPS test is not running." + } + ), 409 + + service.stop() + + if ( + service.thread is not None + and + service.thread is not threading.current_thread() + ): + + service.thread.join( + timeout=2 + ) + + with scanner_lock: + + scanner_output.append( + "[GUI] GPS test stop requested." + ) + + return jsonify( + { + "ok": True + } + ) + + +@app.route( + "/api/gps-test" +) +def api_gps_test(): + + return jsonify( + get_gps_test_status() + ) + +@app.route( + "/api/wifi/channels" +) +def api_wifi_channels(): + + interface = request.args.get( + "interface", + "" + ).strip() + + + if not interface: + + return jsonify( + { + "2.4": [], + "5": [], + "6": [], + "error": "WiFi interface was not selected." + } + ), 400 + + + interfaces, interface_error = ( + get_wifi_interfaces() + ) + + + if interface_error: + + return jsonify( + { + "2.4": [], + "5": [], + "6": [], + "error": interface_error + } + ), 500 + + + if interface not in interfaces: + + return jsonify( + { + "2.4": [], + "5": [], + "6": [], + "error": "Invalid WiFi interface." + } + ), 400 + + + return jsonify( + get_wifi_channels(interface) + ) + +@app.route( + "/config/save", + methods=["POST"] +) +def config_save(): + + if get_scanner_status()["running"]: + + with scanner_lock: + + scanner_output.append( + "[GUI] Configuration cannot be " + "saved while scanner is running." + ) + + return jsonify( + { + "ok": False, + "error": + "Configuration cannot be saved " + "while scanner is running." + } + ), 409 + + if get_gps_test_status()["running"]: + + with scanner_lock: + scanner_output.append( + "[GUI] Configuration cannot be " + "saved while GPS test is running." + ) + + return jsonify( + { + "ok": False, + "error": + "Configuration cannot be saved " + "while GPS test is running." + } + ), 409 + + + try: + + data = request.get_json( + silent=True + ) + + if not data: + + raise RuntimeError( + "No configuration data received." + ) + + save_config(data) + + with scanner_lock: + + scanner_output.append( + "[GUI] Configuration saved." + ) + + return jsonify( + { + "ok": True, + "message": + "Configuration saved successfully." + } + ) + + + except Exception as error: + + with scanner_lock: + + scanner_output.append( + f"[GUI] Failed to save configuration: " + f"{error}" + ) + + return jsonify( + { + "ok": False, + "error": str(error) + } + ), 500 + + +@app.route( + "/scanner/start", + methods=["POST"] +) +def scanner_start(): + + global scanner_process + global scanner_health + global scanner_stopped_at + + with scanner_lock: + + if ( + scanner_process is not None + and + scanner_process.poll() is None + ): + + return redirect( + url_for("index") + ) + + if get_gps_test_status()["running"]: + + with scanner_lock: + + scanner_output.append( + "[GUI] Scanner cannot start " + "while GPS test is running." + ) + + return redirect( + url_for("index") + ) + + interface = request.form.get( + "interface", + "" + ).strip() + + + if not interface: + + with scanner_lock: + + scanner_output.append( + "[GUI] WiFi interface was not selected." + ) + + return redirect( + url_for("index") + ) + + + environment = os.environ.copy() + + environment[ + "WIFI_INTERFACE" + ] = interface + + + command = [ + sys.executable, + "src/main.py" + ] + + + try: + + process = subprocess.Popen( + + command, + + cwd=PROJECT_ROOT, + + env=environment, + + stdin=subprocess.DEVNULL, + + stdout=subprocess.PIPE, + + stderr=subprocess.STDOUT, + + text=True, + + bufsize=1, + + process_group=0 + + ) + + except Exception as error: + + with scanner_lock: + + scanner_output.append( + f"[GUI] Failed to start scanner: {error}" + ) + + return redirect( + url_for("index") + ) + + + with scanner_lock: + + scanner_process = process + + scanner_health = "ACTIVE" + + scanner_stopped_at = None + + scanner_output.clear() + + scanner_output.append( + "[GUI] Scanner started." + ) + + scanner_output.append( + f"[GUI] PID: {process.pid}" + ) + + scanner_output.append( + f"[GUI] Interface: {interface}" + ) + + + thread = threading.Thread( + target=read_scanner_output, + args=(process,), + daemon=True + ) + + thread.start() + + + return redirect( + url_for("index") + ) + + +@app.route( + "/scanner/stop", + methods=["POST"] +) +def scanner_stop(): + + global scanner_health + + with scanner_lock: + + process = scanner_process + + if ( + process is None + or + process.poll() is not None + ): + return redirect( + url_for("index") + ) + + scanner_health = "STOPPING" + + scanner_output.append( + "[GUI] SIGINT sent to scanner." + ) + + try: + + os.killpg( + process.pid, + signal.SIGINT + ) + + except Exception as error: + + with scanner_lock: + + scanner_health = "ACTIVE" + + scanner_output.append( + f"[GUI] Failed to stop scanner: {error}" + ) + + return redirect( + url_for("index") + ) + + +if __name__ == "__main__": + + print( + "Checking sudo privileges..." + ) + + if not check_sudo(): + + print( + "sudo authentication failed." + ) + + raise SystemExit(1) + + + print( + "sudo: OK" + ) + + + thread = threading.Thread( + target=sudo_keepalive, + daemon=True + ) + + thread.start() + + + logging.getLogger("werkzeug").disabled = True + + app.run( + host="127.0.0.1", + port=5000, + debug=False + ) \ No newline at end of file diff --git a/gui/static/fonts/Bender-Bold.woff2 b/gui/static/fonts/Bender-Bold.woff2 new file mode 100644 index 0000000..1caf36c Binary files /dev/null and b/gui/static/fonts/Bender-Bold.woff2 differ diff --git a/gui/static/fonts/Bender.woff2 b/gui/static/fonts/Bender.woff2 new file mode 100644 index 0000000..39df036 Binary files /dev/null and b/gui/static/fonts/Bender.woff2 differ diff --git a/gui/static/style.css b/gui/static/style.css new file mode 100644 index 0000000..f21a746 --- /dev/null +++ b/gui/static/style.css @@ -0,0 +1,1349 @@ +@font-face { + + font-family: "Bender"; + + src: + url("/static/fonts/Bender.woff2") + format("woff2"); + + font-weight: 400; + + font-style: normal; +} + + +@font-face { + + font-family: "Bender"; + + src: + url("/static/fonts/Bender-Bold.woff2") + format("woff2"); + + font-weight: 700; + + font-style: normal; +} + + +* { + + box-sizing: border-box; +} + + +:root { + + --bg: #0f141a; + + --surface: #171e26; + + --surface-light: #1c252f; + + --border: #2b3743; + + --text: #e6edf3; + + --muted: #8b98a6; + + --green: #45d483; + + --yellow: #e5c07b; + + --red: #ef6262; + + --accent: #69a7ff; + + --terminal: #0a0f14; +} + + +body { + + margin: 0; + + background: + var(--bg); + + color: + var(--text); + + font-family: + "Bender", + sans-serif; + + font-size: 15px; + + line-height: 1.5; +} + + +button, +select { + + font-family: + inherit; +} + + +.app-header { + + position: sticky; + + top: 0; + + z-index: 1000; + + width: 100%; + + background: + rgba(15, 20, 26, 0.96); + + border-bottom: + 1px solid var(--border); + + backdrop-filter: + blur(12px); +} + + +.header-inner { + + max-width: 1400px; + + margin: 0 auto; + + min-height: 68px; + + display: flex; + + align-items: center; + + justify-content: space-between; + + gap: 36px; + + padding: + 0 30px; +} + +.header-actions { + + display: flex; + + align-items: center; + + gap: 24px; +} + +/* ============================================================ + SCANNER HEADER CONTROLS + Компактные START / STOP в sticky-шапке. + ============================================================ */ + + +.header-scanner-controls { + + display: flex; + + align-items: center; + + gap: 7px; +} + + +.header-scanner-controls form { + + margin: 0; +} + + +.header-button { + + height: 30px; + + padding: + 0 11px; + + border: 0; + + border-radius: 5px; + + cursor: pointer; + + font-family: + inherit; + + font-size: 11px; + + font-weight: 700; + + letter-spacing: 0.5px; + + transition: + opacity 0.15s ease, + transform 0.05s ease; +} + + +.header-button:active:not(:disabled) { + + transform: + translateY(1px); +} + + +.header-button:disabled { + + opacity: 0.25; + + cursor: not-allowed; +} + + +/* Цвет кнопки START */ + +.header-button.start { + + background: + var(--green); + + color: + #08110c; +} + + +/* Цвет кнопки STOP */ + +.header-button.stop { + + background: + var(--red); + + color: + #180909; +} + +.header-link { + + color: + var(--muted); + + text-decoration: none; + + font-size: 13px; + + font-weight: 700; + + letter-spacing: 0.8px; + + transition: + color 0.15s ease; +} + + +.header-link:hover { + + color: + var(--accent); +} + +h1, +h2 { + + margin: 0; + + font-weight: 700; +} + + +h1 { + + font-size: 19px; + + letter-spacing: 0.4px; + + line-height: 1.1; +} + + +.subtitle { + + margin-top: 3px; + + color: + var(--muted); + + font-size: 12px; + + font-weight: 400; + + letter-spacing: 0.7px; + + line-height: 1.1; +} + + +/* ============================================================ + SCANNER STATUS IN HEADER + Здесь настраивается внешний вид индикатора сканера. + ============================================================ */ + + +.header-status { + + display: flex; + + align-items: center; + + gap: 9px; + + font-size: 13px; + + font-weight: 700; + + letter-spacing: 0.8px; + + transition: + color 0.2s ease; +} + + +/* ------------------------------------------------------------ + Размер и форма индикатора + Меняй width / height, если нужен другой размер. + Для READY / ACTIVE / WARNING используется круг. + ------------------------------------------------------------ */ + +.status-indicator { + + width: 9px; + + height: 9px; + + display: inline-block; + + flex-shrink: 0; + + border-radius: 50%; +} + + +/* ------------------------------------------------------------ + READY + Жёлтый кружок и жёлтая надпись. + Здесь можно самостоятельно менять цвет READY. + ------------------------------------------------------------ */ + +.header-status.ready { + + color: + var(--yellow); +} + + +.status-indicator.ready { + + background: + var(--yellow); + + box-shadow: + 0 0 9px rgba(229, 192, 123, 0.45); +} + + +/* ------------------------------------------------------------ + ACTIVE + КРАСНЫЙ кружок + ЗЕЛЁНАЯ надпись. + Кружок и надпись плавно мигают вместе. + ------------------------------------------------------------ */ + +.header-status.active { + + color: + var(--green); + + animation: + scanner-active-pulse 1.8s ease-in-out infinite; +} + + +.status-indicator.active { + + background: + var(--red); + + box-shadow: + 0 0 9px rgba(255, 70, 70, 0.65); +} + + +/* ------------------------------------------------------------ + WARNING + Всё красное. + Состояние светится, но НЕ мигает. + ------------------------------------------------------------ */ + +.header-status.warning { + + color: + var(--red); + + text-shadow: + 0 0 8px rgba(255, 70, 70, 0.55); +} + + +.status-indicator.warning { + + background: + var(--red); + + box-shadow: + 0 0 11px rgba(255, 70, 70, 0.8); +} + + +/* ------------------------------------------------------------ + STOPPED + Вместо кружка используется статичный CSS-квадрат. + ------------------------------------------------------------ */ + +.header-status.stopped { + + color: + var(--red); + + opacity: 0.8; +} + + +.status-indicator.stopped { + + width: 9px; + + height: 9px; + + border-radius: 1px; + + background: + var(--red); +} + + +/* ------------------------------------------------------------ + ACTIVE animation + Здесь меняется скорость мигания ACTIVE. + Например: + 1s = быстрее + 2s = медленнее + 3s = ещё медленнее + ------------------------------------------------------------ */ + +@keyframes scanner-active-pulse { + + 0%, + 100% { + + opacity: 1; + } + + 50% { + + opacity: 0.45; + } +} + + +main { + + max-width: 1400px; + + margin: 0 auto; + + padding: + 28px; +} + + +.panel { + + margin-bottom: 22px; + + padding: 24px; + + background: + var(--surface); + + border: + 1px solid var(--border); + + border-radius: 10px; +} + + +.panel-heading { + + display: flex; + + align-items: center; + + justify-content: space-between; + + gap: 20px; + + margin-bottom: 22px; +} + + +.panel-kicker { + + margin-bottom: 3px; + + color: + var(--muted); + + font-size: 11px; + + font-weight: 700; + + letter-spacing: 1.5px; +} + + +.panel h2 { + + font-size: 20px; +} + + +.panel-hint { + + color: + var(--muted); + + font-size: 13px; +} + + +.scanner-panel { + + border-color: + #354556; +} + + +.scanner-state { + + display: flex; + + align-items: center; + + gap: 12px; + + color: + var(--muted); + + font-size: 13px; +} + +.gps-diagnostics { + display: flex; + + flex-direction: column; + + gap: 20px; +} + + +.gps-diagnostics-state { + display: flex; + + align-items: center; + + gap: 16px; + + min-height: 82px; + + padding: + 18px 20px; + + background: + var(--terminal); + + border: + 1px solid #202a34; + + border-radius: 8px; +} + + +.gps-state-indicator { + font-size: 42px; + + line-height: 1; +} + + +.gps-diagnostics-state strong { + display: block; + + font-size: 22px; + + line-height: 1.25; +} + + +.gps-diagnostics-state span:last-child { + display: block; + + margin-top: 5px; + + color: + var(--muted); + + font-size: 13px; +} + + +.gps-state-indicator.ready { + color: + #aeb8c2; +} + + +.gps-state-indicator.connecting { + color: + #6fa8ff; +} + + +.gps-state-indicator.nmea { + color: + #e6c65c; +} + + +.gps-state-indicator.fix { + color: + var(--green); +} + + +.gps-state-indicator.error { + color: + var(--red); +} + + +.gps-state-indicator.stopped { + color: + var(--muted); +} + + +.gps-diagnostics-grid { + display: grid; + + grid-template-columns: + repeat(3, minmax(0, 1fr)); + + gap: 12px; +} + + +.gps-diagnostic { + display: flex; + + flex-direction: column; + + gap: 5px; + + padding: + 12px 14px; + + background: + var(--terminal); + + border: + 1px solid #202a34; + + border-radius: 7px; +} + + +.gps-diagnostic span { + color: + var(--muted); + + font-size: 12px; +} + + +.gps-diagnostic strong { + font-size: 14px; +} + + +.gps-diagnostics-actions { + display: flex; + + justify-content: flex-start; +} + +.running { + + color: + var(--green); +} + + +.stopped { + + color: + var(--red); +} + + +.scanner-controls { + + display: flex; + + align-items: end; + + gap: 14px; +} + + +.interface-form { + + flex: 1; + + display: flex; + + align-items: end; + + gap: 14px; +} + + +.field { + + flex: 1; + + max-width: 430px; +} + + +.config-help { + + margin-top: 7px; + + color: + var(--muted); + + font-size: 12px; + + line-height: 1.5; +} + + +label { + + display: block; + + margin-bottom: 7px; + + color: + var(--muted); + + font-size: 13px; + + font-weight: 700; +} + + +select { + + width: 100%; + + height: 43px; + + padding: + 0 13px; + + background: + var(--bg); + + color: + var(--text); + + border: + 1px solid var(--border); + + border-radius: 6px; + + outline: none; +} + + +select:focus { + + border-color: + var(--accent); + + box-shadow: + 0 0 0 2px rgba(105, 167, 255, 0.12); +} + + +.button { + + height: 43px; + + padding: + 0 20px; + + border: 0; + + border-radius: 6px; + + cursor: pointer; + + font-family: + inherit; + + font-size: 13px; + + font-weight: 700; + + letter-spacing: 0.5px; + + transition: + opacity 0.15s ease, + transform 0.05s ease; +} + + +.button:active:not(:disabled) { + + transform: + translateY(1px); +} + + +.button:disabled { + + opacity: 0.35; + + cursor: not-allowed; +} + + +.start { + + background: + var(--green); + + color: + #08110c; +} + + +.stop { + + background: + var(--red); + + color: + #180909; +} + + +.error { + + margin-top: 10px; + + padding: 10px 12px; + + background: + rgba(239, 98, 98, 0.08); + + color: + #ff9b9b; + + border: + 1px solid rgba(239, 98, 98, 0.25); + + border-radius: 6px; + + font-size: 13px; +} + + +pre { + + margin: 0; + + padding: 16px; + + background: + var(--terminal); + + border: + 1px solid #202a34; + + border-radius: 7px; + + overflow: auto; + + white-space: pre-wrap; + + word-break: break-word; + + font-family: + "Bender", + monospace; + + font-size: 13px; + + line-height: 1.5; +} + + +#scanner-output { + + height: 430px; + + overflow-y: auto; + + white-space: pre; + + word-break: normal; + + color: + #b8c5d1; +} + + +.configuration-panel pre { + max-height: 500px; +} + + +.config-grid { + display: grid; + + grid-template-columns: + minmax(0, 1.35fr) + minmax(0, 1fr) + minmax(0, 1fr); + + gap: 28px; + + align-items: start; +} + + +.config-column { + min-width: 0; +} + + +.config-column .field { + width: 100%; + + max-width: none; + + margin-bottom: 18px; +} + + +.config-column .field:last-child { + margin-bottom: 0; +} + + +.config-column-wifi { + min-width: 0; +} + + +.config-column-wifi .wifi-configuration { + width: 100%; + + max-width: none; +} + + +.config-info { + opacity: 0.45; +} + + +.config-info-value { + min-height: 43px; + + display: flex; + + align-items: center; + + padding: + 0 13px; + + background: + var(--bg); + + color: + var(--text); + + border: + 1px solid var(--border); + + border-radius: 6px; + + font-size: 13px; + + word-break: break-word; +} + + +.wifi-channels { + margin-top: 18px; +} + + +.wifi-band { + display: grid; + + grid-template-columns: + 150px + minmax(0, 1fr); + + align-items: start; + + gap: 12px; + + padding: 12px 0; + + border-top: + 1px solid var(--border); +} + + +.wifi-band:first-child { + border-top: 0; +} + + +.wifi-band-header { + display: flex; + + align-items: center; + + gap: 9px; + + min-height: 32px; +} + + +.wifi-band-header label { + margin: 0; + + color: var(--text); + + font-size: 13px; + + font-weight: 700; +} + + +.wifi-band-header input[type="checkbox"] { + width: 16px; + + height: 16px; + + margin: 0; + + accent-color: var(--accent); +} + + +.wifi-band-header .band-hint { + color: var(--muted); + + font-size: 11px; + + font-weight: 400; +} + + +.wifi-band-controls { + min-width: 0; +} + + +.wifi-channel-actions { + display: flex; + + align-items: center; + + gap: 7px; + + margin-bottom: 7px; +} + + +.channel-action { + height: 30px; + + padding: + 0 10px; + + background: + var(--surface-light); + + color: + var(--text); + + border: + 1px solid var(--border); + + border-radius: 5px; + + cursor: pointer; + + font-family: + inherit; + + font-size: 11px; + + font-weight: 700; +} + + +.channel-action:disabled { + opacity: 0.35; + + cursor: not-allowed; +} + + +.wifi-channel-list { + display: flex; + + flex-wrap: wrap; + + align-items: center; + + gap: 6px; +} + + +.wifi-channel { + display: inline-flex; + + align-items: center; + + gap: 5px; + + margin: 0; + + padding: + 4px 7px; + + background: + var(--bg); + + color: + var(--text); + + border: + 1px solid var(--border); + + border-radius: 4px; + + font-size: 12px; + + font-weight: 400; + + line-height: 1.2; +} + + +.wifi-channel input[type="checkbox"] { + width: 14px; + + height: 14px; + + margin: 0; + + accent-color: var(--accent); +} + + +.wifi-channel.unavailable { + opacity: 0.35; +} + + +.wifi-channel.unavailable input[type="checkbox"] { + cursor: not-allowed; +} + + +.wifi-channel-container { + min-height: 30px; +} + + +.wifi-channel-container.band-unavailable { + opacity: 0.45; +} + + +.wifi-channel-container.band-disabled { + opacity: 0.35; + + pointer-events: none; +} + + +.wifi-diagnostics { + margin-top: 12px; + + color: var(--muted); + + font-size: 12px; +} + + +.wifi-diagnostics-interface { + color: var(--text); + + font-weight: 700; +} + + +#wifi-channel-error { + margin-top: 7px; + + color: #ff9b9b; + + font-size: 12px; +} + + +@media (max-width: 760px) { + .wifi-band { + grid-template-columns: 1fr; + + gap: 8px; + } + + .wifi-band-header { + min-height: auto; + } + + .wifi-channel-actions { + flex-wrap: wrap; + } +} + +@media (max-width: 760px) { + + .header-inner { + + align-items: flex-start; + + flex-direction: column; + } + + + main { + + padding: 16px; + } + + + .panel { + + padding: 18px; + } + + + .scanner-controls { + + align-items: stretch; + + flex-direction: column; + } + + + .interface-form { + + align-items: stretch; + + flex-direction: column; + } + + + .field { + + max-width: none; + } + + + .button { + + width: 100%; + } + + + .scanner-state { + + align-items: flex-end; + + flex-direction: column; + + gap: 2px; + } +} + + + +@media (max-width: 760px) { + + .config-grid { + grid-template-columns: 1fr; + + gap: 0; + } + + + .config-column { + margin-bottom: 24px; + } + + + .config-column:last-child { + margin-bottom: 0; + } +} + +.configuration-actions { + + display: flex; + + align-items: center; + + width: 100%; +} + + +#configuration-save-status { + + margin-left: auto; + + text-align: right; +} \ No newline at end of file diff --git a/gui/templates/index.html b/gui/templates/index.html new file mode 100644 index 0000000..34c0185 --- /dev/null +++ b/gui/templates/index.html @@ -0,0 +1,2888 @@ + + + + + + + + + + WiFi GPS Mapper + + + + + + + +
+ +
+ +
+ +

+ WiFi GPS Mapper +

+ +
+ Wireless network scanner +
+ +
+ +
+ + + REPORTS + + + +
+ + + + +
+ + + +
+ +
+ + +
+ + + + {% if status.health == "ACTIVE" %} + SCANNER ACTIVE + {% elif status.health == "WARNING" %} + WARNING + {% elif status.health == "STOPPED" %} + SCANNER STOPPED + {% else %} + SCANNER READY + {% endif %} + +
+ +
+ +
+ + +
+ + +
+ +
+ +
+ +
+ CONTROL +
+ +

+ Scanner +

+ +
+ +
+ + {% if status.running %} + + + RUNNING + + + + PID {{ status.pid }} + + + {% else %} + + + STOPPED + + + {% endif %} + +
+ +
+ + +
+ +
+ +
+ + + + + +
+ + + {% if interface_error %} + +
+ {{ interface_error }} +
+ + {% endif %} + + + + +
+ + +
+ + + +
+ +
+ +
+ + +
+ +
+ +
+ +
+ SYSTEM +
+ +

+ Configuration +

+ +
+ + + config.yaml + + +
+ + + {% if config._error %} + +
+ {{ config._error }} +
+ + {% else %} + +
+ +
+ +
+ +
+ +
+ WiFi +
+ + +
+ + + Interface: + + + + not selected + + + + Select interface to detect channels + + +
+ + +
+ +
+ + + + +
+ + + + + +
+ +
+ + +
+ +
+ + +
+ +
+ + + + +
+ + + + + +
+ +
+ + +
+ +
+ + +
+ +
+ + + + +
+ + + + + +
+ +
+ + +
+ +
+ + + + + + + +
+ +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + + +
+ {{ config.database.file }} +
+ +
+ + +
+ + + +
+ {{ config.vendor.database }} +
+ +
+ + +
+ + + +
+ {{ config.captures.directory }} +
+ +
+ +
+ + +
+ +
+ + + + + +
+ Дополнительные параметры запуска hcxdumptool. + Если параметры не нужны, оставьте поле пустым. + Полную справку по параметрам используемой версии смотрите командой: + ./bin/hcxdumptool --help +
+ +
+ +
+ + + + + +
+ IANA часовой пояс для отображения времени в UI и отчетах. + В базе данных и обменных файлах время всегда хранится в UTC. +
+ +
+ +
+ + + + + +
+ + +
+ + + + + +
+ Интервал вывода контрольной информации о работе программы, секунд. + Каждые N секунд отображаются длительность текущей сессии, + количество полученных GPS сообщений, последние координаты + и текущая статистика захвата. + Сохранение GPS-потока в gps_track.nmea от этого параметра не зависит. +
+ +
+ +
+ +
+ + +
+ + + + + +
+ +
+ + {% endif %} + +
+ + +
+ +
+ +
+ +
+ GPS +
+ +

+ GPS Diagnostics +

+ +
+ + + GPS READY + + +
+ + +
+ +
+ + + ● + + +
+ + + Готов к тесту + + + + GPS test is ready. + + +
+ +
+ + +
+ +
+ + + Source + + + + {{ config.gps.source|upper }} + + +
+ + +
+ + + Handler + + + + {% if config.gps.source == "gnss" %} + {{ config.gps.gnss.handler }} + {% else %} + GPSRelay + {% endif %} + + +
+ + +
+ + + NMEA + + + + {{ gps_test.nmea_count }} + + +
+ + +
+ + + FIX + + + + {{ gps_test.fix_count }} + + +
+ + +
+ + + Latitude + + + + {% if gps_test.latitude is not none %} + {{ "%.6f"|format(gps_test.latitude) }} + {% else %} + — + {% endif %} + + +
+ + +
+ + + Longitude + + + + {% if gps_test.longitude is not none %} + {{ "%.6f"|format(gps_test.longitude) }} + {% else %} + — + {% endif %} + + +
+ +
+ + +
+ + + +
+ +
+ +
+ + +
+ +
+ +
+ +
+ RUNTIME +
+ +

+ Scanner Output +

+ +
+ + + Live output + + +
+ + +
{% for line in output %}{{ line }}
+{% endfor %}
+ +
+ + +
+ + + + + + + diff --git a/reports/__init__.py b/reports/__init__.py new file mode 100644 index 0000000..7c68785 --- /dev/null +++ b/reports/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- \ No newline at end of file diff --git a/reports/access_points.py b/reports/access_points.py new file mode 100644 index 0000000..21164eb --- /dev/null +++ b/reports/access_points.py @@ -0,0 +1,1116 @@ +import html +import json + +from reports.database import query_all, query_one +from reports.template import ( + ReportContext, + card, + page_begin, + page_end, + page_header, +) +from reports.utils import ( + format_datetime as format_report_datetime, +) + + +def esc(value): + + if value is None: + return "—" + + return html.escape( + str(value), + quote=True, + ) + + +def format_datetime(value): + return format_report_datetime( + value, + "%d.%m.%y-%H.%M.%S" + ) + + +def format_popup_datetime(value): + return format_report_datetime( + value, + "%d-%m-%Y-%H-%M-%S" + ) + + +def load_report_interval(conn): + + row = query_one( + conn, + """ + SELECT + MIN(start_time) AS first_time, + MAX( + COALESCE( + end_time, + start_time + ) + ) AS last_time + FROM capture_sessions + """, + ) + + if not row: + return ( + None, + None, + ) + + return ( + row["first_time"], + row["last_time"], + ) + + +def load_access_points(conn): + + rows = query_all( + conn, + """ + WITH ranked_observations AS ( + SELECT + obs.access_point_id, + obs.latitude, + obs.longitude, + obs.observed_at, + obs.rssi, + obs.channel, + ROW_NUMBER() OVER ( + PARTITION BY obs.access_point_id + ORDER BY + obs.observed_at DESC, + obs.id DESC + ) AS rn + FROM access_point_observations AS obs + WHERE + obs.latitude IS NOT NULL + AND obs.longitude IS NOT NULL + AND obs.latitude != 0 + AND obs.longitude != 0 + ) + SELECT + ap.id, + ap.bssid, + ap.essid, + ap.vendor, + ap.has_handshake, + ap.has_pmkid, + ap.is_cracked, + obs.latitude, + obs.longitude, + obs.observed_at, + obs.rssi, + obs.channel, + ( + SELECT c.password + FROM credentials AS c + WHERE c.access_point_id = ap.id + ORDER BY + c.created_at DESC, + c.id DESC + LIMIT 1 + ) AS password + FROM access_points AS ap + JOIN ranked_observations AS obs + ON obs.access_point_id = ap.id + AND obs.rn = 1 + ORDER BY + obs.observed_at DESC, + ap.bssid + """, + ) + + return rows + + +def build_marker_js(observations): + + ap_features = [] + handshake_features = [] + pmkid_features = [] + password_features = [] + + for row in observations: + + latitude = row["latitude"] + longitude = row["longitude"] + + if ( + latitude is None + or longitude is None + ): + continue + + ssid = ( + row["essid"] + if row["essid"] is not None + and str(row["essid"]) != "" + else "—" + ) + + vendor = ( + row["vendor"] + if row["vendor"] is not None + and str(row["vendor"]) != "" + else "—" + ) + + channel = ( + row["channel"] + if row["channel"] is not None + else "—" + ) + + rssi = ( + f"{row['rssi']} dBm" + if row["rssi"] is not None + else "—" + ) + + password = ( + row["password"] + if row["password"] is not None + and str(row["password"]) != "" + else "—" + ) + + popup = ( + f"{esc(ssid)}" + f"
MAC: {esc(row['bssid'])}" + f"
Vendor: {esc(vendor)}" + f"
Channel: {esc(channel)}" + f"
RSSI: {esc(rssi)}" + f"
Password: {esc(password)}" + f"
Date: " + f"{esc(format_popup_datetime(row['observed_at']))}" + f'
' + f"Подробнее" + ) + + feature = { + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [ + float(longitude), + float(latitude), + ], + }, + "properties": { + "popup": popup, + }, + } + + ap_features.append(feature) + + if row["has_handshake"]: + handshake_features.append( + feature + ) + + if row["has_pmkid"]: + pmkid_features.append( + feature + ) + + if row["is_cracked"] or row["password"]: + password_features.append( + feature + ) + + return ( + "const apFeatures = " + + json.dumps( + ap_features, + ensure_ascii=False, + ) + + ";\n" + "const handshakeFeatures = " + + json.dumps( + handshake_features, + ensure_ascii=False, + ) + + ";\n" + "const pmkidFeatures = " + + json.dumps( + pmkid_features, + ensure_ascii=False, + ) + + ";\n" + "const passwordFeatures = " + + json.dumps( + password_features, + ensure_ascii=False, + ) + + ";\n" + ) + + +def render_access_points_map( + observations, + context, +): + + marker_js = build_marker_js( + observations + ) + + maplibre_css_url = context.asset_url( + "maplibre/maplibre-gl.css" + ) + + maplibre_js_url = context.asset_url( + "maplibre/maplibre-gl.js" + ) + + map_html = """ +
+ + + + + + +""" + + map_html = map_html.replace( + "__MAPLIBRE_CSS_URL__", + esc(maplibre_css_url), + ) + + map_html = map_html.replace( + "__MAPLIBRE_JS_URL__", + esc(maplibre_js_url), + ) + + map_html = map_html.replace( + "__MARKER_JS__", + marker_js, + ) + + return map_html + + +def render_access_points_page( + conn, + context=None, +): + + if context is None: + context = ReportContext( + mode="server" + ) + + first_time, last_time = ( + load_report_interval(conn) + ) + + observations = load_access_points( + conn + ) + + html = page_begin( + "📡 Access Points", + active="access_points", + context=context, + ) + + html += f""" +
+ +Time interval: + +{esc(format_datetime(first_time))} +— +{esc(format_datetime(last_time))} + +
+""" + + html += card( + """ + + + 🗺 Capture Map + + + + + + + + + + + + + """, + render_access_points_map( + observations, + context, + ), + ) + + html += page_end() + + return html \ No newline at end of file diff --git a/reports/access_points_page.py b/reports/access_points_page.py new file mode 100644 index 0000000..63538d7 --- /dev/null +++ b/reports/access_points_page.py @@ -0,0 +1,1536 @@ +import html +import json +import math +from collections import defaultdict + +from reports.database import query_all, query_one +from reports.utils import ( + format_datetime as format_report_datetime, +) + +from reports.template import ( + ReportContext, + card, + page_begin, + page_end, + page_header, +) + + +def esc(value): + return html.escape("" if value is None else str(value), quote=True) + + +def format_datetime(value): + return format_report_datetime( + value, + "%d.%m.%y-%H.%M.%S" + ) + + +def format_number(value, digits=1): + if value is None: + return "—" + + try: + return f"{float(value):.{digits}f}" + except (TypeError, ValueError): + return str(value) + + +def format_speed(value): + if value is None: + return "—" + + try: + speed = float(value) + except (TypeError, ValueError): + return str(value) + + if abs(speed) < 0.05: + return "0" + + return f"{speed:.1f}" + + +def haversine_m(lat1, lon1, lat2, lon2): + radius = 6371000.0 + + phi1 = math.radians(lat1) + phi2 = math.radians(lat2) + dphi = math.radians(lat2 - lat1) + dlambda = math.radians(lon2 - lon1) + + a = ( + math.sin(dphi / 2.0) ** 2 + + math.cos(phi1) + * math.cos(phi2) + * math.sin(dlambda / 2.0) ** 2 + ) + + return 2.0 * radius * math.asin(min(1.0, math.sqrt(a))) + + +def weighted_mean(values): + if not values: + return None + + total_weight = sum(weight for _, weight in values) + + if total_weight <= 0: + return sum(value for value, _ in values) / len(values) + + return sum(value * weight for value, weight in values) / total_weight + + +def percentile(values, fraction): + if not values: + return None + + ordered = sorted(values) + + if len(ordered) == 1: + return ordered[0] + + position = (len(ordered) - 1) * fraction + lower = int(math.floor(position)) + upper = int(math.ceil(position)) + + if lower == upper: + return ordered[lower] + + ratio = position - lower + return ordered[lower] + (ordered[upper] - ordered[lower]) * ratio + + +def observation_weight(rssi): + """ + RSSI is used only as a relative confidence weight. + + We deliberately do not convert RSSI to a physical distance because + environmental attenuation, antenna characteristics, reflections and + transmitter power make such a conversion unreliable for this task. + """ + if rssi is None: + return 1.0 + + try: + value = float(rssi) + except (TypeError, ValueError): + return 1.0 + + # Keep the influence deliberately moderate. + # + # - -90 dBm -> 1 + # - -70 dBm -> 2 + # - -50 dBm -> 4 + # + # This makes stronger observations useful without allowing a handful + # of unusually strong readings to dominate the whole history. + normalized = max(0.0, min(40.0, value + 90.0)) + return 1.0 + normalized / 10.0 + + +def valid_observations(rows): + result = [] + + for row in rows: + try: + latitude = float(row["latitude"]) + longitude = float(row["longitude"]) + except (TypeError, ValueError): + continue + + if not (-90.0 <= latitude <= 90.0): + continue + + if not (-180.0 <= longitude <= 180.0): + continue + + if abs(latitude) < 1e-12 and abs(longitude) < 1e-12: + continue + + result.append( + { + "id": row["id"], + "session_id": row["session_id"], + "observed_at": row["observed_at"], + "latitude": latitude, + "longitude": longitude, + "speed": row["speed"], + "rssi": row["rssi"], + "channel": row["channel"], + "frequency": row["frequency"], + "essid": row["essid"], + "encryption": row["encryption"], + "cipher": row["cipher"], + "akm": row["akm"], + "country": row["country"], + } + ) + + return result + +def normalize_bursts(observations): + """ + Treat repeated observations at the same time and position as one + independent spatial observation. + + RSSI values inside a burst are averaged so that short-lived RSSI + fluctuations do not give duplicate rows additional influence. + """ + if not observations: + return observations + + groups = {} + + for item in observations: + key = ( + item["session_id"], + item["observed_at"], + item["latitude"], + item["longitude"], + ) + + group = groups.setdefault( + key, + { + "item": item, + "rssi_values": [], + }, + ) + + if item["rssi"] is not None: + try: + group["rssi_values"].append(float(item["rssi"])) + except (TypeError, ValueError): + pass + + result = [] + + for group in groups.values(): + item = dict(group["item"]) + rssi_values = group["rssi_values"] + + if rssi_values: + item["rssi"] = sum(rssi_values) / len(rssi_values) + + result.append(item) + + return result + +def local_projection(observations): + """ + Convert geographic coordinates to a local metre-based coordinate system. + + x = east/west + y = north/south + """ + if not observations: + return None, [] + + center_lat = sum(item["latitude"] for item in observations) / len(observations) + center_lon = sum(item["longitude"] for item in observations) / len(observations) + + cos_lat = math.cos(math.radians(center_lat)) + + if abs(cos_lat) < 1e-8: + cos_lat = 1e-8 + + projected = [] + + meters_per_degree = 111320.0 + + for item in observations: + x = ( + (item["longitude"] - center_lon) + * meters_per_degree + * cos_lat + ) + y = (item["latitude"] - center_lat) * meters_per_degree + + projected.append((item, x, y)) + + return (center_lat, center_lon), projected + + +def weighted_center(observations): + if not observations: + return None + + center, projected = local_projection(observations) + + weighted_x = [] + weighted_y = [] + + for item, x, y in projected: + weight = observation_weight(item["rssi"]) + weighted_x.append((x, weight)) + weighted_y.append((y, weight)) + + x = weighted_mean(weighted_x) + y = weighted_mean(weighted_y) + + center_lat, center_lon = center + meters_per_degree = 111320.0 + cos_lat = math.cos(math.radians(center_lat)) + + if abs(cos_lat) < 1e-8: + cos_lat = 1e-8 + + latitude = center_lat + y / meters_per_degree + longitude = center_lon + x / (meters_per_degree * cos_lat) + + return { + "latitude": latitude, + "longitude": longitude, + "x": x, + "y": y, + } + + +def robust_observations(observations): + """ + Remove only strong spatial outliers. + + The method intentionally has a conservative threshold. We do not want + to destroy normal driving tracks merely because the AP was observed + from several nearby positions. + """ + if len(observations) < 8: + return observations + + center = weighted_center(observations) + + if not center: + return observations + + distances = [] + + for item in observations: + distance = haversine_m( + center["latitude"], + center["longitude"], + item["latitude"], + item["longitude"], + ) + distances.append((item, distance)) + + numeric_distances = [distance for _, distance in distances] + + median = percentile(numeric_distances, 0.50) + p90 = percentile(numeric_distances, 0.90) + + if median is None or p90 is None: + return observations + + # Robust scale estimate. + deviations = [abs(distance - median) for distance in numeric_distances] + mad = percentile(deviations, 0.50) or 0.0 + + robust_limit = median + max(3.0 * mad, 0.0) + + # Never trim inside the central 90% envelope. + limit = max(robust_limit, p90) + + # Avoid creating an artificially tiny area. + minimum_limit = max(75.0, median * 1.5) + limit = max(limit, minimum_limit) + + filtered = [ + item + for item, distance in distances + if distance <= limit + ] + + # If the filter became too aggressive, retain the original data. + if len(filtered) < max(5, int(len(observations) * 0.60)): + return observations + + return filtered + + +def covariance_ellipse(observations): + """ + Calculate an oriented uncertainty ellipse in metres. + + The ellipse describes the spatial dispersion of the useful observations, + not a guaranteed physical reception radius of the AP. + """ + if len(observations) < 2: + return None + + center, projected = local_projection(observations) + + weights = [ + observation_weight(item["rssi"]) + for item, _, _ in projected + ] + + total_weight = sum(weights) + + if total_weight <= 0: + return None + + mean_x = sum(x * weight for (_, x, _), weight in zip(projected, weights)) + mean_y = sum(y * weight for (_, _, y), weight in zip(projected, weights)) + + mean_x /= total_weight + mean_y /= total_weight + + covariance_xx = 0.0 + covariance_xy = 0.0 + covariance_yy = 0.0 + + for (_, x, y), weight in zip(projected, weights): + dx = x - mean_x + dy = y - mean_y + + covariance_xx += weight * dx * dx + covariance_xy += weight * dx * dy + covariance_yy += weight * dy * dy + + covariance_xx /= total_weight + covariance_xy /= total_weight + covariance_yy /= total_weight + + trace = covariance_xx + covariance_yy + determinant = ( + covariance_xx * covariance_yy + - covariance_xy * covariance_xy + ) + + determinant = max(0.0, determinant) + + discriminant = max( + 0.0, + trace * trace - 4.0 * determinant, + ) + + lambda1 = max( + 0.0, + (trace + math.sqrt(discriminant)) / 2.0, + ) + + lambda2 = max( + 0.0, + (trace - math.sqrt(discriminant)) / 2.0, + ) + + if lambda1 <= 0.0: + return None + + if abs(covariance_xy) > 1e-9: + axis_x = lambda1 - covariance_yy + axis_y = covariance_xy + elif covariance_xx >= covariance_yy: + axis_x = 1.0 + axis_y = 0.0 + else: + axis_x = 0.0 + axis_y = 1.0 + + axis_length = math.hypot(axis_x, axis_y) + + if axis_length <= 1e-9: + return None + + axis_x /= axis_length + axis_y /= axis_length + + angle = math.degrees(math.atan2(axis_x, axis_y)) + + # Approximately 90% confidence ellipse for a 2D Gaussian. + scale = math.sqrt(4.605170186) + + semi_major = math.sqrt(lambda1) * scale + semi_minor = math.sqrt(lambda2) * scale + + # A tiny covariance can occur when the same point was observed many + # times. Keep the visualization visible but do not claim centimetre + # accuracy. + semi_major = max(25.0, semi_major) + semi_minor = max(20.0, semi_minor) + + # Prevent visually misleading enormous ellipses. + semi_major = min(5000.0, semi_major) + semi_minor = min(5000.0, semi_minor) + + center_lat, center_lon = center + meters_per_degree = 111320.0 + cos_lat = math.cos(math.radians(center_lat)) + + if abs(cos_lat) < 1e-8: + cos_lat = 1e-8 + + latitude = center_lat + mean_y / meters_per_degree + longitude = center_lon + mean_x / (meters_per_degree * cos_lat) + + return { + "latitude": latitude, + "longitude": longitude, + "semi_major": semi_major, + "semi_minor": semi_minor, + "angle": angle, + } + + +def ellipse_polygon(ellipse, points=64): + if not ellipse: + return [] + + lat0 = ellipse["latitude"] + lon0 = ellipse["longitude"] + + angle = math.radians(ellipse["angle"]) + cos_lat = math.cos(math.radians(lat0)) + + if abs(cos_lat) < 1e-8: + cos_lat = 1e-8 + + result = [] + + for index in range(points + 1): + theta = 2.0 * math.pi * index / points + + local_x = ellipse["semi_major"] * math.cos(theta) + local_y = ellipse["semi_minor"] * math.sin(theta) + + x = ( + local_x * math.cos(angle) + + local_y * math.sin(angle) + ) + y = ( + -local_x * math.sin(angle) + + local_y * math.cos(angle) + ) + + latitude = lat0 + y / 111320.0 + longitude = lon0 + x / (111320.0 * cos_lat) + + result.append([longitude, latitude]) + + return result + + +def spatial_zones(observations): + """ + Find clearly separated observation groups. + + This is intentionally conservative. A zone is reported only when there + are at least three observations in a group and the groups are separated + by roughly 600 metres. + """ + if len(observations) < 6: + return [] + + remaining = list(observations) + groups = [] + + while remaining: + seed = remaining.pop(0) + group = [seed] + changed = True + + while changed: + changed = False + keep = [] + + for item in remaining: + close = False + + for member in group: + if ( + haversine_m( + item["latitude"], + item["longitude"], + member["latitude"], + member["longitude"], + ) + <= 300.0 + ): + close = True + break + + if close: + group.append(item) + changed = True + else: + keep.append(item) + + remaining = keep + + groups.append(group) + + significant = [ + group + for group in groups + if len(group) >= 3 + ] + + if len(significant) <= 1: + return [] + + centers = [] + + for group in significant: + center = weighted_center(group) + + if center: + centers.append((group, center)) + + separated = False + + for index, (_, center_a) in enumerate(centers): + for _, center_b in centers[index + 1:]: + if ( + haversine_m( + center_a["latitude"], + center_a["longitude"], + center_b["latitude"], + center_b["longitude"], + ) + > 600.0 + ): + separated = True + break + + if separated: + break + + if not separated: + return [] + + return [ + { + "observations": group, + "center": center, + } + for group, center in centers + ] + + +def load_access_point(conn, bssid): + return query_one( + conn, + """ + SELECT + id, + bssid, + essid, + encryption, + cipher, + akm, + country, + channel, + frequency, + vendor, + first_seen, + last_seen, + times_seen, + last_rssi, + last_latitude, + last_longitude, + last_speed, + has_handshake, + has_pmkid, + is_cracked + FROM access_points + WHERE lower(bssid) = lower(?) + LIMIT 1 + """, + (bssid,), + ) + + +def load_observations(conn, access_point_id): + return query_all( + conn, + """ + SELECT + id, + session_id, + observed_at, + latitude, + longitude, + speed, + rssi, + channel, + frequency, + essid, + encryption, + cipher, + akm, + country + FROM access_point_observations + WHERE access_point_id = ? + ORDER BY observed_at, id + """, + (access_point_id,), + ) + + +def load_credentials(conn, access_point_id): + return query_all( + conn, + """ + SELECT + c.password, + c.source, + c.created_at, + c.verified, + c.handshake_id + FROM credentials AS c + WHERE c.access_point_id = ? + ORDER BY c.created_at DESC, c.id DESC + """, + (access_point_id,), + ) + + +def security_text(ap): + values = [] + + for key in ("encryption", "cipher", "akm"): + value = ap[key] + + if value and value not in values: + values.append(str(value)) + + return " / ".join(values) if values else "—" + + +def calculate_statistics(observations): + rssis = [] + + speeds = [] + + for item in observations: + if item["rssi"] is not None: + try: + rssis.append(float(item["rssi"])) + except (TypeError, ValueError): + pass + + if item["speed"] is not None: + try: + speeds.append(float(item["speed"])) + except (TypeError, ValueError): + pass + + sessions = { + item["session_id"] + for item in observations + if item["session_id"] is not None + } + + return { + "observations": len(observations), + "sessions": len(sessions), + "coordinates": len(valid_observations(observations)), + "rssi_min": min(rssis) if rssis else None, + "rssi_avg": sum(rssis) / len(rssis) if rssis else None, + "rssi_max": max(rssis) if rssis else None, + "speed_avg": sum(speeds) / len(speeds) if speeds else None, + "speed_max": max(speeds) if speeds else None, + } + + +def build_geojson(observations, ellipse=None, zones=None): + features = [] + + for item in observations: + try: + latitude = float(item["latitude"]) + longitude = float(item["longitude"]) + except (TypeError, ValueError): + continue + + properties = { + "type": "observation", + "id": item["id"], + "session_id": item["session_id"], + "observed_at": format_datetime(item["observed_at"]), + "rssi": item["rssi"], + "speed": item["speed"], + "map_status": item.get("map_status", "normal"), + } + + features.append( + { + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [longitude, latitude], + }, + "properties": properties, + } + ) + + if ellipse: + polygon = ellipse_polygon(ellipse) + + if polygon: + features.append( + { + "type": "Feature", + "geometry": { + "type": "Polygon", + "coordinates": [polygon], + }, + "properties": { + "type": "uncertainty", + }, + } + ) + + if zones: + for index, zone in enumerate(zones, start=1): + center = zone["center"] + + features.append( + { + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [ + center["longitude"], + center["latitude"], + ], + }, + "properties": { + "type": "zone", + "zone": index, + "observations": len(zone["observations"]), + }, + } + ) + + return { + "type": "FeatureCollection", + "features": features, + } + + +def render_map(geojson, context, title): + maplibre_css = context.asset_url("maplibre/maplibre-gl.css") + maplibre_js = context.asset_url("maplibre/maplibre-gl.js") + + geojson_json = json.dumps( + geojson, + ensure_ascii=False, + separators=(",", ":"), + ) + + return f""" + + + + +
+ +
+
+ + Обычное наблюдение — координата, записанная во время сканирования. +
+
+ + Handshake — для этого AP в базе есть перехваченный handshake. +
+
+ + Пароль найден — для этого AP в базе есть credential. +
+
+ + Расчётная область — статистическая оценка положения AP по истории наблюдений. Это не гарантированная зона покрытия и не точная координата устройства. +
+
+ + + +""" + + +def render_observation_table(observations): + rows = [] + + for item in reversed(observations): + coordinates = "—" + + if ( + item["latitude"] is not None + and item["longitude"] is not None + ): + coordinates = ( + f"{float(item['latitude']):.6f}, " + f"{float(item['longitude']):.6f}" + ) + + rows.append( + f""" + + {esc(format_datetime(item["observed_at"]))} + + + {esc(item["session_id"])} + + + {esc(coordinates)} + {esc(item["rssi"] if item["rssi"] is not None else "—")} + {esc(format_speed(item["speed"]))} + {esc(item["channel"] if item["channel"] is not None else "—")} + {esc(item["frequency"] if item["frequency"] is not None else "—")} + +""" + ) + + return f""" +
+ + + + + + + + + + + + + +{''.join(rows)} + +
ДатаСессияКоординатыRSSIСкоростьКаналЧастота
+
+""" + + +def render_access_point_page( + conn, + bssid, + context=None, +): + if context is None: + context = ReportContext(mode="server") + + ap = load_access_point(conn, bssid) + + if not ap: + page = page_begin( + "Access Point", + active="access_points", + context=context, + ) + + page += page_header( + "Точка доступа не найдена", + "BSSID: " + esc(bssid), + ) + + page += card( + """ +
+ Запрошенная точка доступа отсутствует в базе данных. +
+""" + ) + + page += page_end() + return page + + observations_raw = load_observations(conn, ap["id"]) + observations = valid_observations(observations_raw) + credentials = load_credentials(conn, ap["id"]) + + if ap["is_cracked"]: + map_status = "cracked" + elif ap["has_handshake"]: + map_status = "handshake" + else: + map_status = "normal" + + map_observations = [] + + for item in observations: + map_item = dict(item) + map_item["map_status"] = map_status + map_observations.append(map_item) + + statistics = calculate_statistics(observations_raw) + + burst_observations = normalize_bursts(observations) + useful_observations = robust_observations(burst_observations) + + estimated_center = weighted_center(burst_observations) + ellipse = covariance_ellipse(burst_observations) + zones = spatial_zones(observations) + + geojson = build_geojson( + map_observations, + ellipse=ellipse, + zones=zones, + ) + + page = page_begin( + f"AP {ap['bssid']}", + active="access_points", + context=context, + ) + + page += page_header( + f"📡 {esc(ap['essid'] or 'Access Point')}", + f"BSSID: {esc(ap['bssid'])}", + ) + + page += f""" + +""" + + page += card( + "Основная информация", + f""" +
+
+ BSSID
+ {esc(ap["bssid"])} +
+ +
+ ESSID
+ {esc(ap["essid"] or "—")} +
+ +
+ Vendor
+ {esc(ap["vendor"] or "—")} +
+ +
+ Security
+ {esc(security_text(ap))} +
+ +
+ Channel
+ {esc(ap["channel"] if ap["channel"] is not None else "—")} +
+ +
+ Frequency
+ {esc(ap["frequency"] if ap["frequency"] is not None else "—")} +
+ +
+ First seen
+ {esc(format_datetime(ap["first_seen"]))} +
+ +
+ Last seen
+ {esc(format_datetime(ap["last_seen"]))} +
+
+""" + ) + + page += card( + "История наблюдений", + f""" +
+
+ Наблюдений
+ {statistics["observations"]} +
+ +
+ Сессий
+ {statistics["sessions"]} +
+ +
+ С координатами
+ {statistics["coordinates"]} +
+ +
+ RSSI min
+ {format_number(statistics["rssi_min"])} +
+ +
+ RSSI avg
+ {format_number(statistics["rssi_avg"])} +
+ +
+ RSSI max
+ {format_number(statistics["rssi_max"])} +
+ +
+ Средняя скорость
+ {format_speed(statistics["speed_avg"])} +
+ +
+ Максимальная скорость
+ {format_speed(statistics["speed_max"])} +
+
+""" + ) + + status_parts = [] + + if ap["has_handshake"]: + status_parts.append("Handshake") + + if ap["has_pmkid"]: + status_parts.append("PMKID") + + if ap["is_cracked"]: + status_parts.append("Cracked") + + if status_parts: + status_text = ", ".join(status_parts) + else: + status_text = "Нет связанных данных" + + credential_rows = [] + + for credential in credentials: + verified = "Да" if credential["verified"] else "Нет" + + credential_rows.append( + f""" + + {esc(credential["password"])} + {esc(credential["source"] or "—")} + {esc(verified)} + {esc(format_datetime(credential["created_at"]))} + #{esc(credential["handshake_id"])} + +""" + ) + + credentials_html = "" + + if credential_rows: + credentials_html = f""" +
+ + + + + + + + + + + +{''.join(credential_rows)} + +
PasswordSourceVerifiedCreatedHandshake
+
+""" + else: + credentials_html = """ +
+ Связанных credentials нет. +
+""" + + page += card( + "Связанные данные", + f""" +
+ Статус: {esc(status_text)} +
+ +{credentials_html} +""" + ) + + if estimated_center: + estimated_coordinates = ( + f"{estimated_center['latitude']:.6f}, " + f"{estimated_center['longitude']:.6f}" + ) + else: + estimated_coordinates = "Недостаточно координат" + + if ellipse: + ellipse_size = ( + f"{ellipse['semi_major']:.0f} × " + f"{ellipse['semi_minor']:.0f} м" + ) + + ellipse_direction = f"{ellipse['angle']:.0f}°" + else: + ellipse_size = "Недостаточно данных" + ellipse_direction = "—" + + if zones: + zone_message = ( + f"История содержит {len(zones)} пространственно " + f"разделённых зоны наблюдений. Поэтому одна общая " + f"область неопределённости может быть misleading." + ) + else: + zone_message = ( + "Наблюдения не показывают достаточно выраженного " + "разделения на несколько независимых пространственных зон." + ) + + + page += card( + "Расчёт положения", + f""" +
+
+ Оценочный центр
+ {esc(estimated_coordinates)} +
+ +
+ Размер эллипса
+ {esc(ellipse_size)} +
+ +
+ Ориентация
+ {esc(ellipse_direction)} +
+ +
+ Использовано координат
+ {len(useful_observations)} +
+
+ +
+ Важно: + расчётная точка является статистической оценкой по истории + наблюдений. Она не означает, что AP физически находится + непосредственно в этой координате. + RSSI используется только как дополнительный относительный вес. + Расчётная область показывает неопределённость оценки, а не + гарантированную дальность действия Wi-Fi. +
+ +
+ {esc(zone_message)} +
+""" + ) + + password_text = "" + + if credentials: + password = credentials[0]["password"] + + if password: + password_text = ( + f" · Password: {esc(password)}" + ) + + page += card( + "Карта истории", + f""" +
+ 📡 {esc(ap["essid"] or "Access Point")} + · AP {esc(ap["bssid"])} + {password_text} +
+ + {render_map( + geojson, + context, + ap["bssid"], + )} + """ + ) + + page += card( + "Полная история наблюдений", + f""" +
+ Здесь отображаются все записи из + access_point_observations. + Записи без координат сохраняются в истории, но не участвуют + в пространственном расчёте. +
+ +{render_observation_table(observations_raw)} +""" + ) + + page += page_end() + + return page diff --git a/reports/config.py b/reports/config.py new file mode 100644 index 0000000..79cabf9 --- /dev/null +++ b/reports/config.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Конфигурация HTML Report. + +Все пути генератора отчётов находятся здесь. + +Это позволяет не использовать "магические" строки +по всему проекту. +""" + +from pathlib import Path + +import yaml + + +# ============================================================ +# Пути проекта +# ============================================================ + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +DATABASE_FILE = PROJECT_ROOT / "database" / "wifi.sqlite3" + +CAPTURES_DIR = PROJECT_ROOT / "captures" + +CONFIG_FILE = PROJECT_ROOT / "config" / "config.yaml" + + +# ============================================================ +# Загрузка конфигурации +# ============================================================ + +if CONFIG_FILE.exists(): + + with CONFIG_FILE.open( + "r", + encoding="utf-8" + ) as fp: + + CONFIG = yaml.safe_load(fp) or {} + +else: + + CONFIG = {} + +REPORTS_CONFIG = CONFIG.get( + "reports", + {} +) + +RECENT_SESSIONS_LIMIT = REPORTS_CONFIG.get( + "recent_sessions_limit", + 10 +) + +TIMEZONE = CONFIG.get( + "timezone", + "Europe/Moscow" +) + +# ============================================================ +# Каталог отчёта +# ============================================================ + +OUTPUT_DIR = PROJECT_ROOT / "reports" / "output" + +SESSIONS_DIR = OUTPUT_DIR / "sessions" + +INDEX_FILE = OUTPUT_DIR / "index.html" + +ACCESS_POINTS_FILE = OUTPUT_DIR / "access_points.html" + + +# Страница всех поездок + +CAPTURE_SESSIONS_FILE = OUTPUT_DIR / "capture_sessions.html" + + +# ============================================================ +# Создание каталогов +# ============================================================ + +OUTPUT_DIR.mkdir( + parents=True, + exist_ok=True +) + +SESSIONS_DIR.mkdir( + parents=True, + exist_ok=True +) \ No newline at end of file diff --git a/reports/dashboard.py b/reports/dashboard.py new file mode 100644 index 0000000..59bd79d --- /dev/null +++ b/reports/dashboard.py @@ -0,0 +1,856 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Dashboard HTML report. + +Главная страница отчета. + +Содержит только обзорную информацию. + +Без карты. + +Без полного списка точек доступа. + +Вся детальная информация находится +на страницах отдельных поездок. +""" + +from pathlib import Path + +from .config import ( + RECENT_SESSIONS_LIMIT, +) + +from .utils import ( + format_datetime, +) + +from .template import ( + + page_begin, + + page_end, + + page_header, + + card, + + stat, + + stats_grid, + +) + +from .statistics import ( + + database_statistics, + + top_vendors, + + top_essid, + + channel_statistics, + + encryption_statistics, + +) + +from .sessions import ( + + recent_sessions, + + all_sessions, + +) + +# ============================================================ +# Helpers +# ============================================================ + +def format_session_folder(capture_file): + if not capture_file: + return "-" + + folder = Path(capture_file).parent.name + + try: + from datetime import datetime, timezone + + dt = datetime.strptime( + folder, + "%Y%m%d_%H%M%S" + ).replace( + tzinfo=timezone.utc + ) + + return format_datetime( + dt.isoformat() + ) + + except ValueError: + return folder + + +# ============================================================ +# Database statistics +# ============================================================ + +def statistics_block(conn): + + data = database_statistics(conn) + + items = [ + + stat( + data["access_points"], + "Access Points" + ), + + stat( + data["access_points_without_coordinates"], + "AP without Coordinates" + ), + + stat( + data["sessions"], + "Capture Sessions" + ), + + stat( + data["vendors"], + "Vendors" + ), + + stat( + data["handshakes"], + "Handshakes" + ), + + stat( + data["credentials"], + "Handshake Cracked" + ), + + stat( + data["pmkid"], + "PMKID" + ), + + stat( + data["cracked"], + "Cracked AP" + ), + + stat( + data["database_size"], + "Database" + ), + + ] + + return card( + + "📊 Database Overview", + + stats_grid(items) + + ) + + +# ============================================================ +# Information +# ============================================================ + +def information_block(conn): + + data = database_statistics(conn) + + html = f""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Database size{data["database_size"]}
Captures size{data["captures_size"]}
Capture files{data["capture_files"]}
First access point{format_datetime(data["first_seen"])}
Last access point{format_datetime(data["last_seen"])}
+ +""" + + return card( + + "ℹ️ Database Information", + + html, + + ) +# ============================================================ +# Top Vendors +# ============================================================ + +def vendors_block(conn): + + rows = top_vendors( + conn, + limit=15 + ) + + html = """ + + + + + + + + + + + +""" + + for vendor, total in rows: + + if not vendor: + + vendor = "-" + + html += f""" + + + + + + + + + +""" + + html += """ + +
VendorDevices
{vendor}{total}
+ +""" + + return card( + + "🏭 Top Vendors", + + html, + + ) + + +# ============================================================ +# Top ESSID +# ============================================================ + +def essid_block(conn): + + rows = top_essid( + conn, + limit=20 + ) + + html = """ + + + + + + + + + + + +""" + + for essid, total in rows: + + if not essid: + + essid = "<hidden>" + + html += f""" + + + + + + + + + +""" + + html += """ + +
ESSIDCount
{essid}{total}
+ +""" + + return card( + + "📶 Most Common ESSID", + + html, + + ) + + +# ============================================================ +# Channels +# ============================================================ + +def channels_block(conn): + + rows = channel_statistics( + conn + ) + + html = """ + + + + + + + + + + + +""" + + for channel, total in rows: + + html += f""" + + + + + + + + + +""" + + html += """ + +
ChannelAccess Points
{channel}{total}
+ +""" + + return card( + + "📡 Channel Statistics", + + html, + + ) + + +# ============================================================ +# Encryption +# ============================================================ + +def encryption_block(conn): + + rows = encryption_statistics( + conn + ) + + html = """ + + + + + + + + + + + +""" + + for encryption, total in rows: + + if not encryption: + + encryption = "-" + + html += f""" + + + + + + + + + +""" + + html += """ + +
EncryptionNetworks
{encryption}{total}
+ +""" + + return card( + + "🔐 Encryption", + + html, + + ) +# ============================================================ +# Session Card +# ============================================================ + +def session_card( + session, + context=None, +): + + session_url = context.session_url( + session["id"] + ) + + return f""" + +
+ +

+ +🚗 Session {format_datetime(session.get("trip_start"))} + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Trip start{format_datetime(session.get("trip_start"))}
Trip end{format_datetime(session.get("trip_end"))}
Duration{session.get("duration","-")}
Imported{format_datetime(session.get("start_time"))}
Session folder{format_session_folder(session.get("capture_file"))}
Access Points{session.get("access_points","-")}
Coordinates Restored{session.get("coordinates_restored","-")}
AP without Coordinates{session.get("ap_without_coordinates","-")}
Handshake AP{session.get("handshakes","-")}
Handshake Records{session.get("handshake_records","-")}
PMKID AP{session.get("pmkid","-")}
Cracked AP{session.get("cracked","-")}
Directory size{session.get("directory_size","-")}
+ +

+ + + +📄 Open Session Report + + + +

+ +
+ +""" + + +# ============================================================ +# Recent Sessions +# ============================================================ + +def sessions_block( + conn, + context=None, +): + + sessions = recent_sessions( + + conn, + + limit=RECENT_SESSIONS_LIMIT, + + ) + + if not sessions: + + return card( + + "🚗 Recent Capture Sessions", + + """ + +

+ +Capture sessions not found. + +

+ +""" + + ) + + cards = [] + + for session in sessions: + + cards.append( + + session_card( + + session, + context, + + ) + + ) + + capture_sessions_url = ( + context.capture_sessions_url() + ) + + html = """ + +
+ +""" + + html += "\n".join(cards) + + html += f""" + +
+ +

+ + + +Show all sessions + + + +

+ +""" + + return card( + + "🚗 Recent Capture Sessions", + + html, + + ) +# ============================================================ +# Dashboard +# ============================================================ + +def generate_dashboard( + conn, + context=None, +): + + html = page_begin( + + title="WiFi GPS Mapper", + + description=( + "Database overview" + ), + + active="dashboard", + + context=context, + + ) + + # -------------------------------------------------------- + # Database statistics + # -------------------------------------------------------- + + html += statistics_block( + conn + ) + + # -------------------------------------------------------- + # Information + # -------------------------------------------------------- + + html += information_block( + conn + ) + + # -------------------------------------------------------- + # Vendors / ESSID + # -------------------------------------------------------- + + html += """ + +
+ +""" + + html += vendors_block( + conn + ) + + html += essid_block( + conn + ) + + html += """ + +
+ +""" + + # -------------------------------------------------------- + # Channels / Encryption + # -------------------------------------------------------- + + html += """ + +
+ +""" + + html += channels_block( + conn + ) + + html += encryption_block( + conn + ) + + html += """ + +
+ +""" + + # -------------------------------------------------------- + # Sessions + # -------------------------------------------------------- + + html += sessions_block( + conn, + context, + ) + + # -------------------------------------------------------- + # Footer + # -------------------------------------------------------- + + html += page_end() + + return html + +# ============================================================ +# All Capture Sessions +# ============================================================ + +def generate_capture_sessions( + conn, + context=None, +): + + sessions = all_sessions( + conn + ) + + html = page_begin( + + title="Capture Sessions", + + description="All capture sessions", + + active="capture_sessions", + + context=context, + + ) + + html += page_header( + + "🚗 Capture Sessions", + + f""" + +Total sessions: + +{len(sessions)} + +""" + ) + + cards = [] + + for session in sessions: + + cards.append( + session_card( + session, + context, + ) + ) + + html += """ + +
+ +""" + + html += "\n".join(cards) + + html += """ + +
+ +""" + + html += page_end() + + return html \ No newline at end of file diff --git a/reports/database.py b/reports/database.py new file mode 100644 index 0000000..412054f --- /dev/null +++ b/reports/database.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Работа с базой данных SQLite. + +Данный модуль является единственной точкой доступа +к базе данных для HTML Report. + +Никакие другие модули не должны напрямую вызывать +sqlite3.connect(). +""" + +import sqlite3 + +from pathlib import Path + +from .config import DATABASE_FILE + + +# ============================================================ +# Подключение +# ============================================================ + + +def connect(database_file=None): + """ + Открыть соединение с SQLite. + """ + + if database_file is None: + database_file = DATABASE_FILE + + database_file = Path(database_file) + + if not database_file.exists(): + raise FileNotFoundError( + f"Database not found:\n{database_file}" + ) + + conn = sqlite3.connect(database_file) + + conn.row_factory = sqlite3.Row + + return conn + + +# ============================================================ +# Выполнение SQL +# ============================================================ + + +def execute(conn, sql, parameters=None): + """ + Выполнить SQL запрос. + """ + + if parameters is None: + parameters = () + + cursor = conn.cursor() + + cursor.execute( + sql, + parameters + ) + + return cursor + + +# ============================================================ +# Один объект +# ============================================================ + + +def query_one(conn, sql, parameters=None): + """ + Вернуть одну запись. + """ + + cursor = execute( + conn, + sql, + parameters + ) + + return cursor.fetchone() + + +# ============================================================ +# Все записи +# ============================================================ + + +def query_all(conn, sql, parameters=None): + """ + Вернуть список записей. + """ + + cursor = execute( + conn, + sql, + parameters + ) + + return cursor.fetchall() + + +# ============================================================ +# Одно значение +# ============================================================ + + +def query_value(conn, sql, parameters=None, default=None): + """ + Вернуть первое поле первой записи. + """ + + row = query_one( + conn, + sql, + parameters + ) + + if row is None: + return default + + if len(row) == 0: + return default + + return row[0] + + +# ============================================================ +# Проверка существования таблицы +# ============================================================ + + +def table_exists(conn, table_name): + """ + Проверить существование таблицы. + """ + + row = query_one( + conn, + """ + SELECT + name + FROM sqlite_master + WHERE type='table' + AND name=? + """, + ( + table_name, + ) + ) + + return row is not None + + +# ============================================================ +# Количество строк +# ============================================================ + + +def count_rows(conn, table_name): + """ + Вернуть количество строк таблицы. + """ + + if not table_exists( + conn, + table_name + ): + return 0 + + cursor = execute( + conn, + f""" + SELECT COUNT(*) + FROM {table_name} + """ + ) + + return cursor.fetchone()[0] + + +# ============================================================ +# Список таблиц +# ============================================================ + + +def list_tables(conn): + """ + Вернуть список таблиц базы. + """ + + rows = query_all( + conn, + """ + SELECT + name + FROM sqlite_master + WHERE type='table' + ORDER BY name + """ + ) + + return [ + row["name"] + for row in rows + ] + + +# ============================================================ +# Структура таблицы +# ============================================================ + + +def table_info(conn, table_name): + """ + Вернуть описание таблицы. + """ + + cursor = execute( + conn, + f"PRAGMA table_info({table_name})" + ) + + return cursor.fetchall() + + +# ============================================================ +# Закрытие соединения +# ============================================================ + + +def close(conn): + """ + Закрыть соединение. + """ + + if conn is not None: + conn.close() \ No newline at end of file diff --git a/reports/hashcat.py b/reports/hashcat.py new file mode 100644 index 0000000..870df8d --- /dev/null +++ b/reports/hashcat.py @@ -0,0 +1,834 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Общая бизнес-логика Hashcat. + +Этот модуль используется одновременно: + • серверным Reports; + • CLI tools/hashcat.py. + +Модуль не открывает соединение с SQLite самостоятельно. + +Соединение передаётся вызывающим кодом и обслуживается +существующим reports.database. +""" + +from datetime import datetime, timezone +from pathlib import Path +import re + + +# ============================================================ +# Constants +# ============================================================ + +MAC_PATTERN = re.compile( + r"^[0-9a-fA-F]{12}$" +) + +SUPPORTED_HANDSHAKE_TYPES = { + "WPA*01", + "WPA*02", +} + + +# ============================================================ +# Export filename +# ============================================================ + +def sanitize_export_query( + query, +): + value = str( + query or "" + ).strip().lower() + + value = re.sub( + r"[^a-z0-9]+", + "-", + value + ) + + value = value.strip( + "-" + ) + + if not value: + value = "all" + + return value[ + :80 + ] + + +def build_export_filename( + export_type, + query="", +): + timestamp = datetime.now( + timezone.utc + ).strftime( + "%Y%m%d-%H%M%S" + ) + + if export_type == "all": + + return ( + "wifi-gps-mapper-all-" + f"{timestamp}.hc22000" + ) + + if export_type == "search": + + safe_query = sanitize_export_query( + query + ) + + return ( + "wifi-gps-mapper-search-" + f"{safe_query}-" + f"{timestamp}.hc22000" + ) + + raise ValueError( + f"Unknown export type: {export_type}" + ) + + +# ============================================================ +# Hash export +# ============================================================ + +def _build_hash_export_from_rows( + rows, +): + hashes = [ + str( + row["hash22000"] + ) + for row in rows + if row["hash22000"] is not None + and str( + row["hash22000"] + ).strip() + ] + + if not hashes: + return "" + + return ( + "\n".join( + hashes + ) + + + "\n" + ) + + +def get_all_hashes( + conn, +): + cursor = conn.execute( + """ + SELECT DISTINCT + h.hash22000 + FROM handshakes AS h + WHERE + h.hash22000 IS NOT NULL + AND TRIM(h.hash22000) != '' + AND NOT EXISTS ( + SELECT 1 + FROM credentials AS c + WHERE c.handshake_id = h.id + ) + ORDER BY + h.hash22000 + """ + ) + + return cursor.fetchall() + + +def build_all_hash_export( + conn, +): + rows = get_all_hashes( + conn + ) + + return _build_hash_export_from_rows( + rows + ) + + +# ============================================================ +# Database statistics +# ============================================================ + +def get_export_statistics( + conn, +): + rows = get_all_hashes( + conn + ) + + statistics = { + "exported_hashes": len(rows), + "wpa01": 0, + "wpa02": 0, + } + + for row in rows: + + hash_value = str( + row["hash22000"] + ) + + if hash_value.startswith( + "WPA*01*" + ): + statistics["wpa01"] += 1 + + elif hash_value.startswith( + "WPA*02*" + ): + statistics["wpa02"] += 1 + + return statistics + +def get_database_statistics( + conn, +): + statistics = {} + + cursor = conn.execute( + """ + SELECT COUNT(*) + FROM access_points + """ + ) + + statistics["access_points"] = cursor.fetchone()[0] + + cursor = conn.execute( + """ + SELECT COUNT(*) + FROM handshakes + """ + ) + + statistics["handshakes"] = cursor.fetchone()[0] + + cursor = conn.execute( + """ + SELECT COUNT(*) + FROM handshakes + WHERE + hash22000 IS NOT NULL + AND TRIM(hash22000) != '' + """ + ) + + statistics["hashes"] = cursor.fetchone()[0] + + cursor = conn.execute( + """ + SELECT COUNT(DISTINCT hash22000) + FROM handshakes + WHERE + hash22000 IS NOT NULL + AND TRIM(hash22000) != '' + """ + ) + + statistics["unique_hashes"] = cursor.fetchone()[0] + + cursor = conn.execute( + """ + SELECT COUNT(*) + FROM credentials + """ + ) + + statistics["credentials"] = cursor.fetchone()[0] + + cursor = conn.execute( + """ + SELECT COUNT(DISTINCT c.access_point_id) + FROM credentials AS c + JOIN handshakes AS h + ON h.id = c.handshake_id + """ + ) + + statistics["cracked_access_points"] = cursor.fetchone()[0] + + return statistics + +# ============================================================ +# Hashcat --show parser +# ============================================================ + +def _normalize_mac( + value, +): + value = str( + value or "" + ).strip().lower() + + value = value.replace( + ":", + "" + ) + + value = value.replace( + "-", + "" + ) + + return value + +def _normalize_hashcat_essid( + value, +): + value = str( + value or "" + ).strip() + + if ( + value.startswith("$HEX[") + and value.endswith("]") + ): + encoded = value[5:-1] + + if not encoded: + return "" + + if ( + len(encoded) % 2 != 0 + or re.fullmatch( + r"[0-9a-fA-F]+", + encoded + ) is None + ): + raise ValueError( + "ESSID $HEX value must be hexadecimal." + ) + + return bytes.fromhex( + encoded + ).hex() + + return value.encode( + "utf-8" + ).hex() + +def _parse_handshake_hash( + value, +): + value = str( + value or "" + ).strip() + + if not value: + raise ValueError( + "HASH is empty." + ) + + parts = value.split( + "*" + ) + + if len(parts) < 6: + raise ValueError( + "HASH is not a valid WPA hash." + ) + + handshake_type = ( + f"{parts[0]}*{parts[1]}" + ) + + if handshake_type not in SUPPORTED_HANDSHAKE_TYPES: + raise ValueError( + "Unsupported handshake type: " + f"{handshake_type}." + ) + + hash_value = parts[2].strip().lower() + ap_bssid = _normalize_mac( + parts[3] + ) + client_mac = _normalize_mac( + parts[4] + ) + essid = parts[5].strip().lower() + + if not hash_value: + raise ValueError( + "HASH value is empty." + ) + + if ( + len(hash_value) != 32 + or re.fullmatch( + r"[0-9a-f]{32}", + hash_value + ) is None + ): + raise ValueError( + "HASH value must be 32 hexadecimal characters." + ) + + if not MAC_PATTERN.fullmatch( + ap_bssid + ): + raise ValueError( + "AP_BSSID is not a valid MAC address." + ) + + if not MAC_PATTERN.fullmatch( + client_mac + ): + raise ValueError( + "CLIENT_MAC is not a valid MAC address." + ) + + if essid and ( + len(essid) % 2 != 0 + or re.fullmatch( + r"[0-9a-fA-F]+", + essid + ) is None + ): + raise ValueError( + "ESSID must be hexadecimal." + ) + + return { + "handshake_type": handshake_type, + "hash": hash_value.lower(), + "ap_bssid": ap_bssid, + "client_mac": client_mac, + "essid": essid, + } + + +def parse_hashcat_show_line( + line, + line_number, +): + raw = str( + line + ).rstrip( + "\r\n" + ) + + if not raw.strip(): + raise ValueError( + "Empty line." + ) + + parts = raw.split( + ":", + 4 + ) + + if len(parts) != 5: + raise ValueError( + "Expected format: " + "HASH:AP_BSSID:CLIENT_MAC:ESSID:PASSWORD." + ) + + hash_value = parts[0].strip().lower() + ap_bssid = _normalize_mac( + parts[1] + ) + client_mac = _normalize_mac( + parts[2] + ) + essid = parts[3].strip() + password = parts[4] + + if not hash_value: + raise ValueError( + "HASH is empty." + ) + + if ( + len(hash_value) != 32 + or re.fullmatch( + r"[0-9a-f]{32}", + hash_value + ) is None + ): + raise ValueError( + "HASH value must be 32 hexadecimal characters." + ) + + if not MAC_PATTERN.fullmatch( + ap_bssid + ): + raise ValueError( + "AP_BSSID is not a valid MAC address." + ) + + if not MAC_PATTERN.fullmatch( + client_mac + ): + raise ValueError( + "CLIENT_MAC is not a valid MAC address." + ) + + essid_hex = _normalize_hashcat_essid( + essid + ) + + return { + "line_number": line_number, + "hash22000": hash_value, + "hash": hash_value, + "ap_bssid": ap_bssid, + "client_mac": client_mac, + "essid": essid_hex, + "password": password, + } + + +# ============================================================ +# Handshake matching +# ============================================================ + +def find_matching_handshake( + conn, + parsed, +): + from reports.database import query_all + + rows = query_all( + conn, + """ + SELECT + h.id, + h.access_point_id, + h.hash22000 + FROM handshakes AS h + WHERE + h.hash22000 IS NOT NULL + AND TRIM(h.hash22000) != '' + ORDER BY + h.id + """ + ) + + for row in rows: + + try: + handshake = _parse_handshake_hash( + row["hash22000"] + ) + except ValueError: + continue + + if ( + handshake["hash"] + == parsed["hash"] + and handshake["ap_bssid"] + == parsed["ap_bssid"] + and handshake["client_mac"] + == parsed["client_mac"] + ): + return row + + return None + + +# ============================================================ +# Credential operations +# ============================================================ + +def credential_exists( + conn, + access_point_id, + handshake_id, + password, +): + from reports.database import query_one + + row = query_one( + conn, + """ + SELECT id + FROM credentials + WHERE + access_point_id = ? + AND handshake_id = ? + AND password = ? + LIMIT 1 + """, + ( + access_point_id, + handshake_id, + password, + ) + ) + + return row is not None + + +def add_credential( + conn, + access_point_id, + handshake_id, + password, +): + from reports.database import execute + + now = datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ) + + cursor = execute( + conn, + """ + INSERT INTO credentials + ( + access_point_id, + handshake_id, + password, + source, + created_at + ) + VALUES + ( + ?, + ?, + ?, + ?, + ? + ) + """, + ( + access_point_id, + handshake_id, + password, + "hashcat", + now, + ) + ) + + execute( + conn, + """ + UPDATE access_points + SET + is_cracked = 1 + WHERE + id = ? + """, + ( + access_point_id, + ) + ) + + return cursor.lastrowid + +# ============================================================ +# Import validation +# ============================================================ + +def validate_hashcat_show_file( + conn, + lines, +): + statistics = { + "total_lines": 0, + "valid_lines": 0, + "invalid_lines": 0, + "matched_handshakes": 0, + "missing_handshakes": 0, + "new_credentials": 0, + "duplicate_credentials": 0, + "already_existing": 0, + "errors": [], + "missing": [], + "items": [], + } + + seen = set() + seen_credentials = set() + + for line_number, line in enumerate( + lines, + start=1 + ): + statistics["total_lines"] += 1 + + try: + parsed = parse_hashcat_show_line( + line, + line_number + ) + + key = ( + parsed["hash"], + parsed["ap_bssid"], + parsed["client_mac"], + parsed["essid"], + parsed["password"], + ) + + if key in seen: + raise ValueError( + "Duplicate line in input file." + ) + + seen.add( + key + ) + + handshake = find_matching_handshake( + conn, + parsed + ) + + if handshake is None: + statistics["missing_handshakes"] += 1 + + statistics["missing"].append( + { + "line": line_number, + "hash": + parsed["hash"], + "ap_bssid": + parsed["ap_bssid"], + "client_mac": + parsed["client_mac"], + "essid": + parsed["essid"], + "password": + parsed["password"], + } + ) + + continue + + statistics["matched_handshakes"] += 1 + + credential_key = ( + handshake["access_point_id"], + handshake["id"], + parsed["password"], + ) + + if credential_key in seen_credentials: + + statistics["duplicate_credentials"] += 1 + status = "Duplicate credential" + + else: + + seen_credentials.add( + credential_key + ) + + exists = credential_exists( + conn, + handshake["access_point_id"], + handshake["id"], + parsed["password"] + ) + + if exists: + statistics["already_existing"] += 1 + status = "Already exists" + + else: + statistics["new_credentials"] += 1 + status = "New credential" + + statistics["valid_lines"] += 1 + + statistics["items"].append( + { + "line": line_number, + "access_point_id": + handshake["access_point_id"], + "handshake_id": + handshake["id"], + "password": + parsed["password"], + "status": status, + } + ) + + except ValueError as error: + + statistics["invalid_lines"] += 1 + + statistics["errors"].append( + { + "line": line_number, + "reason": str( + error + ), + } + ) + + return statistics + +# ============================================================ +# Atomic import +# ============================================================ + +def import_hashcat_show( + conn, + lines, +): + lines = list( + lines + ) + + validation = validate_hashcat_show_file( + conn, + lines + ) + + if validation["errors"]: + + return { + **validation, + "committed": False, + "result": "Rejected", + } + + try: + + for item in validation["items"]: + + if item["status"] != "New credential": + continue + + add_credential( + conn, + item["access_point_id"], + item["handshake_id"], + item["password"] + ) + + conn.commit() + + return { + **validation, + "committed": True, + "result": "Imported", + } + + except Exception: + + conn.rollback() + + raise \ No newline at end of file diff --git a/reports/hashcat_page.py b/reports/hashcat_page.py new file mode 100644 index 0000000..dca233c --- /dev/null +++ b/reports/hashcat_page.py @@ -0,0 +1,903 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Server-side Hashcat report page. +""" + +from html import escape + +from reports.hashcat import ( + get_database_statistics, + get_export_statistics, +) + + +# ============================================================ +# Hashcat page +# ============================================================ + +def render_hashcat_page( + conn, + context=None, + message=None, + import_result=None, +): + from reports.template import ( + page_begin, + page_end, + ) + + if context is None: + from reports.template import ( + ReportContext, + ) + + context = ReportContext( + mode="server" + ) + + export_statistics = get_export_statistics( + conn + ) + + database_statistics = get_database_statistics( + conn + ) + + html = page_begin( + "Hashcat", + ( + "Export WPA handshakes for Hashcat " + "and import passwords returned by " + "hashcat --show." + ), + "hashcat", + context + ) + + if message: + + message_type = escape( + str( + message.get( + "type", + "info" + ) + ) + ) + + message_text = escape( + str( + message.get( + "text", + "" + ) + ) + ) + + html += f""" +
+ +
+ +{message_text} + +
+ +
+""" + + # ======================================================== + # Export + # ======================================================== + + html += """ +
+ +

+ Export +

+ +

+ Export WPA handshake hashes from the database + for Hashcat. +

+ +
+ +
+
+ {exported_hashes} +
+
+ Hashes to export +
+
+ +
+
+ {wpa01} +
+
+ WPA*01 +
+
+ +
+
+ {wpa02} +
+
+ WPA*02 +
+
+ +
+ +

+ The generated file contains the original WPA*01 + and WPA*02 handshake lines stored in the database. +

+ + + Export all hashes + + +
+ """.format( + exported_hashes=export_statistics[ + "exported_hashes" + ], + wpa01=export_statistics[ + "wpa01" + ], + wpa02=export_statistics[ + "wpa02" + ], + ) + + # ======================================================== + # Import + # ======================================================== + + html += """ +
+ +

+ Import Hashcat results +

+ +
+ +Требуемый файл: + +текстовый результат команды +hashcat --show. + +Не загружайте напрямую файл Hashcat +.potfile. + +
+ +

+ Как создать файл для импорта +

+ +

+ После завершения подбора паролей Hashcat + выполните hashcat --show с теми же + параметрами Hashcat и сохраните текстовый + результат в файл. +

+ +
hashcat -m 22000 --show --potfile-path "ПУТЬ_К_ВАШЕМУ_wifi-gps-mapper.potfile" "ПУТЬ_К_ФАЙЛУ_wifi-gps-mapper-all-20260915-002541.hc22000" > wifi-gps-mapper-result.txt
+ +

+ Имя и расширение файла не имеют значения. + Проверяется только его содержимое. +

+ +

+ Ожидаемый формат +

+ +
HASH:AP_BSSID:CLIENT_MAC:ESSID:PASSWORD
+ +

+ Каждая строка проверяется по историческим + данным рукопожатий: HASH, BSSID точки доступа, + MAC-адрес клиента и ESSID. +

+ +

+ Если хотя бы одна строка имеет неверный формат, + весь импорт отклоняется. Если для результата + не найдено соответствующее рукопожатие, такая + строка будет пропущена, а остальные результаты + могут быть импортированы. +

+ +

+ Уже существующие credentials и повторяющиеся + результаты не создают новых записей. Они будут + показаны отдельно в статистике импорта. +

+ +
+ +
+ + + + + + + Файл не выбран + + + + +
+ + + +
+ +
+""" + + html += """ + +""" + + # ======================================================== + # Import statistics + # ======================================================== + + if import_result is not None: + + html += """ +
+ +

+ Import statistics +

+ +
+ +
+
+ {total_lines} +
+
+ Total lines +
+
+ +
+
+ {valid_lines} +
+
+ Valid lines +
+
+ +
+
+ {invalid_lines} +
+
+ Invalid lines +
+
+ +
+
+ {matched_handshakes} +
+
+ Matched handshakes +
+
+ +
+
+ {missing_handshakes} +
+
+ Missing handshakes +
+
+ +
+
+ {new_credentials} +
+
+ New credentials +
+
+ +
+
+ {duplicate_credentials} +
+
+ Duplicate credentials +
+
+ +
+
+ {already_existing} +
+
+ Already exists +
+
+ +
+ +

+ Result +

+ +

+ + {result} + +

+""".format( + total_lines=import_result[ + "total_lines" + ], + valid_lines=import_result[ + "valid_lines" + ], + invalid_lines=import_result[ + "invalid_lines" + ], + matched_handshakes=import_result[ + "matched_handshakes" + ], + missing_handshakes=import_result[ + "missing_handshakes" + ], + new_credentials=import_result[ + "new_credentials" + ], + duplicate_credentials=import_result[ + "duplicate_credentials" + ], + already_existing=import_result[ + "already_existing" + ], + result=escape( + str( + import_result[ + "result" + ] + ) + ), + ) + + errors = import_result[ + "errors" + ] + + if errors: + + html += """ +

+ Errors +

+ +
+ + + + + + + + + + + +""" + + for error in errors: + + html += """ + + + + +""".format( + line=error[ + "line" + ], + reason=escape( + str( + error[ + "reason" + ] + ) + ), + ) + + html += """ + + +
LineReason
+ {line} + + {reason} +
+ +
+""" + + html += """ +
+""" + + # ======================================================== + # Database state + # ======================================================== + + html += """ +
+ +

+ Database +

+ +
+ +
+
+ {access_points} +
+
+ Access points +
+
+ +
+
+ {handshakes} +
+
+ Handshakes +
+
+ +
+
+ {unique_hashes} +
+
+ Unique hashes +
+
+ +
+
+ {credentials} +
+
+ Handshake Cracked +
+
+ +
+
+ {cracked_access_points} +
+
+ Cracked access points +
+
+ +
+ +
+""".format( + access_points=database_statistics[ + "access_points" + ], + handshakes=database_statistics[ + "handshakes" + ], + unique_hashes=database_statistics[ + "unique_hashes" + ], + credentials=database_statistics[ + "credentials" + ], + cracked_access_points=database_statistics[ + "cracked_access_points" + ], + ) + + html += page_end() + + return html \ No newline at end of file diff --git a/reports/main.py b/reports/main.py new file mode 100644 index 0000000..46c1664 --- /dev/null +++ b/reports/main.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +WiFi GPS Mapper + +HTML Report Generator + +Запуск: + + python reports/main.py +""" + +from pathlib import Path + +import shutil + +from reports.database import connect + +from reports.config import DATABASE_FILE + +from reports.template import ( + ReportContext, +) + +from reports.dashboard import ( + generate_dashboard, + generate_capture_sessions, +) + +from reports.session_page import ( + build_all_session_pages, +) + + +# ============================================================ +# Output directory +# ============================================================ + +OUTPUT_DIR = ( + Path(__file__).parent + / "output" +) + +OUTPUT_DIR.mkdir( + parents=True, + exist_ok=True, +) + + +# ============================================================ +# Helpers +# ============================================================ + +def save_text( + + filename: Path, + + text: str, + +): + + filename.parent.mkdir( + parents=True, + exist_ok=True, + ) + + filename.write_text( + + text, + + encoding="utf-8", + + ) + +# ============================================================ +# Copy static resources +# ============================================================ + +def copy_static(): + + source = ( + Path(__file__).parent + / "static" + ) + + destination = ( + OUTPUT_DIR + / "static" + ) + + if destination.exists(): + + shutil.rmtree( + destination + ) + + if source.exists(): + + shutil.copytree( + source, + destination + ) + +# ============================================================ +# Build report +# ============================================================ + +def build_report(): + + print() + + print("=" * 60) + + print(" WiFi GPS Mapper") + + print(" HTML Report Generator") + + print("=" * 60) + + print() + + if not DATABASE_FILE.exists(): + + raise FileNotFoundError( + + f"Database not found:\n{DATABASE_FILE}" + + ) + + print("Opening database...") + + conn = connect(DATABASE_FILE) + + context = ReportContext( + "static" + ) + + print("Copying static resources...") + + copy_static() + + try: + + # + # Dashboard + # + + print("Generating dashboard...") + + dashboard = generate_dashboard( + conn, + context, + ) + + save_text( + + OUTPUT_DIR / "index.html", + + dashboard, + + ) + + # + # Capture Sessions + # + + print("Generating capture sessions page...") + + capture_sessions = generate_capture_sessions( + conn, + context, + ) + + save_text( + + OUTPUT_DIR / "capture_sessions.html", + + capture_sessions, + + ) + + # + # Sessions + # + + print("Generating session pages...") + + generated = build_all_session_pages( + conn, + context, + ) + + print() + + print( + + f"Generated {len(generated)} session pages." + +) + + finally: + + conn.close() + + print() + + print("Done.") + + print() + + print( + + "Dashboard:" + + ) + + print( + + OUTPUT_DIR / "index.html" + + ) + + print() + + print( + + "Output directory:" + + ) + + print( + + OUTPUT_DIR.resolve() + + ) + + print() + + print("=" * 60) + + print() + +# ============================================================ +# MAIN +# ============================================================ + +def main(): + + build_report() + + +if __name__ == "__main__": + + main() + diff --git a/reports/search.py b/reports/search.py new file mode 100644 index 0000000..5cbe955 --- /dev/null +++ b/reports/search.py @@ -0,0 +1,2044 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Server-side search for WiFi GPS Mapper reports. + +Search criteria are intentionally represented as a dictionary so that +new search blocks can be added without redesigning the search layer. +""" + +import json +from html import escape + +from reports.utils import ( + format_datetime as format_report_datetime, +) + + +MAP_STYLE_URL = ( + "http://127.0.0.1:8080/styles/server-map/style.json" +) + + +# ============================================================ +# Search criteria +# ============================================================ + +def normalize_criteria( + vendor=None, +): + criteria = {} + + if vendor is not None: + vendor = str(vendor).strip() + + if vendor: + criteria["vendor"] = vendor + + return criteria + + +def build_where_clause(criteria): + conditions = [] + parameters = [] + + vendor = criteria.get("vendor") + + if vendor: + conditions.append( + """ + LOWER( + REPLACE( + REPLACE( + REPLACE( + REPLACE( + REPLACE( + COALESCE(ap.vendor, ''), + '-', + '' + ), + ' ', + '' + ), + '_', + '' + ), + '.', + '' + ), + '/', + '' + ) + ) LIKE + '%' || + LOWER( + REPLACE( + REPLACE( + REPLACE( + REPLACE( + REPLACE( + ?, + '-', + '' + ), + ' ', + '' + ), + '_', + '' + ), + '.', + '' + ), + '/', + '' + ) + ) || + '%' + """ + ) + + parameters.append( + vendor + ) + + if not conditions: + raise ValueError( + "At least one search criterion is required." + ) + + return ( + " AND ".join(conditions), + parameters + ) + +# ============================================================ +# Popular vendors +# ============================================================ + +def get_popular_vendors( + conn, + limit=20, +): + rows = conn.execute( + """ + SELECT + vendor, + COUNT(*) AS count + FROM access_points + WHERE + vendor IS NOT NULL + AND TRIM(vendor) != '' + GROUP BY vendor + ORDER BY + count DESC, + vendor COLLATE NOCASE ASC + LIMIT ? + """, + ( + limit, + ) + ).fetchall() + + return [ + { + "vendor": row["vendor"], + "count": row["count"], + } + for row in rows + ] + +def get_matching_vendors( + conn, + criteria, + limit=20, +): + where_clause, parameters = ( + build_where_clause(criteria) + ) + + rows = conn.execute( + f""" + SELECT + ap.vendor, + COUNT(*) AS count + FROM access_points AS ap + WHERE + {where_clause} + AND ap.vendor IS NOT NULL + AND TRIM(ap.vendor) != '' + GROUP BY + ap.vendor + ORDER BY + count DESC, + ap.vendor COLLATE NOCASE ASC + LIMIT ? + """, + parameters + [limit] + ).fetchall() + + return [ + { + "vendor": row["vendor"], + "count": row["count"], + } + for row in rows + ] + +# ============================================================ +# Access point search +# ============================================================ + +def search_access_points( + conn, + criteria, +): + where_clause, parameters = ( + build_where_clause(criteria) + ) + + return conn.execute( + f""" + SELECT + ap.id, + ap.bssid, + ap.essid, + ap.encryption, + ap.cipher, + ap.akm, + ap.country, + ap.channel, + ap.frequency, + ap.vendor, + ap.first_seen, + ap.last_seen, + ap.times_seen, + ap.last_rssi, + ap.last_latitude, + ap.last_longitude, + ap.last_speed, + ap.has_handshake, + ap.has_pmkid, + ap.is_cracked + FROM access_points AS ap + WHERE + {where_clause} + ORDER BY + ap.vendor COLLATE NOCASE, + ap.essid COLLATE NOCASE, + ap.bssid + """, + parameters + ).fetchall() + + +# ============================================================ +# Credentials +# ============================================================ + +def load_credentials( + conn, + criteria, +): + where_clause, parameters = ( + build_where_clause(criteria) + ) + + rows = conn.execute( + f""" + SELECT + c.access_point_id, + c.password, + c.source, + c.created_at, + c.verified + FROM credentials AS c + INNER JOIN access_points AS ap + ON ap.id = c.access_point_id + WHERE + {where_clause} + ORDER BY + c.access_point_id, + c.password + """, + parameters + ).fetchall() + + result = {} + + for row in rows: + + access_point_id = row["access_point_id"] + + result.setdefault( + access_point_id, + [] + ).append( + { + "password": row["password"], + "source": row["source"], + "created_at": row["created_at"], + "verified": bool( + row["verified"] + ), + } + ) + + return result + + +# ============================================================ +# Handshakes / PMKIDs +# ============================================================ + +def load_handshakes( + conn, + criteria, +): + where_clause, parameters = ( + build_where_clause(criteria) + ) + + rows = conn.execute( + f""" + SELECT + h.id, + h.access_point_id, + h.type, + h.hash22000, + h.message_pair, + h.captured_at + FROM handshakes AS h + INNER JOIN access_points AS ap + ON ap.id = h.access_point_id + WHERE + {where_clause} + ORDER BY + h.access_point_id, + h.captured_at + """, + parameters + ).fetchall() + + result = {} + + for row in rows: + + access_point_id = row["access_point_id"] + + result.setdefault( + access_point_id, + [] + ).append( + { + "id": row["id"], + "type": row["type"], + "hash22000": row["hash22000"], + "message_pair": row["message_pair"], + "captured_at": row["captured_at"], + } + ) + + return result + + +# ============================================================ +# Category +# ============================================================ + +def get_category( + access_point, +): + if access_point["is_cracked"]: + return "password" + + if ( + access_point["has_handshake"] + or + access_point["has_pmkid"] + ): + return "handshake" + + return "other" + + +# ============================================================ +# Popup helpers +# ============================================================ + +def safe(value): + if value is None: + return "—" + + text = str(value) + + if not text: + return "—" + + return escape( + text, + quote=True + ) + + +def format_security( + access_point, +): + parts = [] + + if access_point["encryption"]: + parts.append( + access_point["encryption"] + ) + + if access_point["cipher"]: + parts.append( + access_point["cipher"] + ) + + if access_point["akm"]: + parts.append( + access_point["akm"] + ) + + if not parts: + return "—" + + return escape( + " / ".join( + str(item) + for item in parts + ), + quote=True + ) + + +def popup_password( + access_point, + credentials, +): + password_items = [] + + for credential in credentials: + + verified = ( + "Yes" + if credential["verified"] + else + "No" + ) + + password_items.append( + """ +
+
+ {password} +
+ +
+ Verified: {verified} +  ·  + Source: {source} +
+
+ """.format( + password=safe( + credential["password"] + ), + verified=verified, + source=safe( + credential["source"] + ) + ) + ) + + if not password_items: + password_items.append( + """ +
+ No password details available. +
+ """ + ) + + return """ +
+
+ {essid} +
+ +
+ BSSID: + {bssid} +
+ +
+ Vendor: + {vendor} +
+ +
+ PASSWORD +
+ +
+ {passwords} +
+ +
+ Security: + {security} +
+ +
+ Channel: + {channel} +  ·  + Frequency: + {frequency} +
+ +
+ RSSI: + {rssi} +
+ +
+ First seen: + {first_seen} +
+ +
+ Last seen: + {last_seen} +
+ +
+ Times seen: + {times_seen} +
+
+ """.format( + essid=safe( + access_point["essid"] + ), + bssid=safe( + access_point["bssid"] + ), + vendor=safe( + access_point["vendor"] + ), + passwords="".join( + password_items + ), + security=format_security( + access_point + ), + channel=safe( + access_point["channel"] + ), + frequency=safe( + access_point["frequency"] + ), + rssi=safe( + access_point["last_rssi"] + ), + first_seen=format_report_datetime( + access_point["first_seen"] + ), + last_seen=format_report_datetime( + access_point["last_seen"] + ), + times_seen=safe( + access_point["times_seen"] + ) + ) + + +def popup_handshake( + access_point, + handshakes, +): + eapol_count = 0 + pmkid_count = 0 + capture_times = [] + + for handshake in handshakes: + + handshake_type = ( + str( + handshake["type"] + or "" + ).upper() + ) + + if "PMKID" in handshake_type: + pmkid_count += 1 + else: + eapol_count += 1 + + if handshake["captured_at"]: + capture_times.append( + format_report_datetime( + handshake["captured_at"] + ) + ) + + summary = [] + + if eapol_count: + summary.append( + f"EAPOL × {eapol_count}" + ) + + if pmkid_count: + summary.append( + f"PMKID × {pmkid_count}" + ) + + if not summary: + summary.append( + "Handshake / PMKID" + ) + + capture_html = "" + + if capture_times: + + capture_html = """ +
+ Capture time: +
+ {times} +
+
+ """.format( + times="".join( + "
{}
".format( + safe(timestamp) + ) + for timestamp in capture_times + ) + ) + + return """ +
+
+ {essid} +
+ +
+ BSSID: + {bssid} +
+ +
+ Vendor: + {vendor} +
+ +
+ HANDSHAKE / PMKID +
+ +
+ Material: + {summary} +
+ + {capture_html} + +
+ Security: + {security} +
+ +
+ Channel: + {channel} +  ·  + Frequency: + {frequency} +
+ +
+ RSSI: + {rssi} +
+ +
+ First seen: + {first_seen} +
+ +
+ Last seen: + {last_seen} +
+ +
+ Times seen: + {times_seen} +
+
+ """.format( + essid=safe( + access_point["essid"] + ), + bssid=safe( + access_point["bssid"] + ), + vendor=safe( + access_point["vendor"] + ), + summary=escape( + " · ".join(summary) + ), + capture_html=capture_html, + security=format_security( + access_point + ), + channel=safe( + access_point["channel"] + ), + frequency=safe( + access_point["frequency"] + ), + rssi=safe( + access_point["last_rssi"] + ), + first_seen=format_report_datetime( + access_point["first_seen"] + ), + last_seen=format_report_datetime( + access_point["last_seen"] + ), + times_seen=safe( + access_point["times_seen"] + ) + ) + + +def popup_other( + access_point, +): + return """ +
+
+ {essid} +
+ +
+ BSSID: + {bssid} +
+ +
+ Vendor: + {vendor} +
+ +
+ OTHER AP +
+ +
+ Security: + {security} +
+ +
+ Channel: + {channel} +  ·  + Frequency: + {frequency} +
+ +
+ RSSI: + {rssi} +
+ +
+ First seen: + {first_seen} +
+ +
+ Last seen: + {last_seen} +
+ +
+ Times seen: + {times_seen} +
+
+ """.format( + essid=safe( + access_point["essid"] + ), + bssid=safe( + access_point["bssid"] + ), + vendor=safe( + access_point["vendor"] + ), + security=format_security( + access_point + ), + channel=safe( + access_point["channel"] + ), + frequency=safe( + access_point["frequency"] + ), + rssi=safe( + access_point["last_rssi"] + ), + first_seen=format_report_datetime( + access_point["first_seen"] + ), + last_seen=format_report_datetime( + access_point["last_seen"] + ), + times_seen=safe( + access_point["times_seen"] + ) + ) + + +# ============================================================ +# GeoJSON +# ============================================================ + +def build_geojson( + access_points, + credentials, + handshakes, +): + features = [] + + for access_point in access_points: + + latitude = access_point[ + "last_latitude" + ] + + longitude = access_point[ + "last_longitude" + ] + + if latitude is None or longitude is None: + continue + + if ( + latitude == 0 + and + longitude == 0 + ): + continue + + access_point_id = ( + access_point["id"] + ) + + category = get_category( + access_point + ) + + if category == "password": + + popup = popup_password( + access_point, + credentials.get( + access_point_id, + [] + ) + ) + + elif category == "handshake": + + popup = popup_handshake( + access_point, + handshakes.get( + access_point_id, + [] + ) + ) + + else: + + popup = popup_other( + access_point + ) + + features.append( + { + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [ + float(longitude), + float(latitude) + ] + }, + "properties": { + "id": access_point_id, + "category": category, + "popup": popup, + } + } + ) + + return { + "type": "FeatureCollection", + "features": features + } + + +# ============================================================ +# Hash export +# ============================================================ + +def get_hashes( + conn, + criteria, +): + where_clause, parameters = ( + build_where_clause(criteria) + ) + + rows = conn.execute( + f""" + SELECT DISTINCT + h.hash22000 + FROM handshakes AS h + INNER JOIN access_points AS ap + ON ap.id = h.access_point_id + WHERE + {where_clause} + AND h.hash22000 IS NOT NULL + AND TRIM(h.hash22000) != '' + ORDER BY + h.hash22000 + """, + parameters + ).fetchall() + + return [ + row["hash22000"] + for row in rows + ] + + +def build_hash_export( + conn, + criteria, +): + hashes = get_hashes( + conn, + criteria + ) + + if not hashes: + return "" + + return ( + "\n".join( + str(item) + for item in hashes + ) + + + "\n" + ) + + +# ============================================================ +# Search data +# ============================================================ + +def build_search_data( + conn, + criteria, +): + access_points = ( + search_access_points( + conn, + criteria + ) + ) + + credentials = ( + load_credentials( + conn, + criteria + ) + ) + + handshakes = ( + load_handshakes( + conn, + criteria + ) + ) + + geojson = build_geojson( + access_points, + credentials, + handshakes + ) + + hashes = get_hashes( + conn, + criteria + ) + + password_access_points = sum( + 1 + for access_point in access_points + if access_point["is_cracked"] + ) + + handshake_access_points = sum( + 1 + for access_point in access_points + if ( + access_point["has_handshake"] + or + access_point["has_pmkid"] + ) + ) + + matching_vendors = ( + get_matching_vendors( + conn, + criteria + ) + ) + + return { + "criteria": criteria, + "matched_access_points": len( + access_points + ), + "mapped_access_points": len( + geojson["features"] + ), + "password_access_points": + password_access_points, + "handshake_access_points": + handshake_access_points, + "hash_count": len(hashes), + "matching_vendors": + matching_vendors, + "geojson": geojson, + } + + +# ============================================================ +# Search page +# ============================================================ + +def render_search_page( + conn, + context=None, +): + from reports.template import ( + page_begin, + page_end, + ) + + if context is None: + from reports.template import ( + ReportContext, + ) + + context = ReportContext( + mode="server" + ) + + maplibre_css_url = context.asset_url( + "maplibre/maplibre-gl.css" + ) + + popular_vendors = ( + get_popular_vendors(conn) + ) + + vendor_items = [] + + for item in popular_vendors: + + vendor = escape( + str( + item["vendor"] + ), + quote=True + ) + + count = int( + item["count"] + ) + + vendor_items.append( + """ +
+ + {vendor} + + + + {count} + +
+ """.format( + vendor=vendor, + count=count + ) + ) + + if vendor_items: + + suggestions_html = "".join( + vendor_items + ) + + else: + + suggestions_html = """ + + No vendors available. + + """ + + html = page_begin( + "Search", + "Search access points in the WiFi GPS Mapper database.", + "search", + context + ) + + html += """ +
+ +

+ Search by Vendor +

+ +
+ + + +
+ + + + + +
+ +
+ +
+ +
+ Popular vendors +
+ +
+ {suggestions} +
+ +
+ +
+ +
+ +

+ Search by Access Point +

+ +
+ Reserved for future search criteria: + ESSID, BSSID and other access point attributes. +
+ +
+ + + + + + + + + """.replace( + "{suggestions}", + suggestions_html + ).replace( + "{maplibre_css}", + maplibre_css_url + ).replace( + "{maplibre_js}", + context.asset_url( + "maplibre/maplibre-gl.js" + ) + ).replace( + "{map_style}", + MAP_STYLE_URL + ) + + html += page_end() + + return html \ No newline at end of file diff --git a/reports/session_page.py b/reports/session_page.py new file mode 100644 index 0000000..003d797 --- /dev/null +++ b/reports/session_page.py @@ -0,0 +1,2711 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +HTML report for one capture session. + +Creates: + +reports/sessions/.html +""" + +from __future__ import annotations + +import html +import json +from pathlib import Path + +import pynmea2 + +from reports.database import query_all, query_one +from reports.sessions import ( + session_statistics, + trip_time, + session_directory_size, + coordinates_restored_count, + ap_without_coordinates_count, +) +from reports.utils import ( + format_datetime as format_report_datetime, + format_duration, + format_size, +) + +from reports.template import ( + page_begin, + page_end, + page_header, + card, + ReportContext, +) + + +# ============================================================ +# Helpers +# ============================================================ + + +def esc(value) -> str: + + if value is None: + return "" + + return html.escape(str(value)) + + +def format_datetime(value): + return format_report_datetime( + value + ) + + +def format_session_folder(name): + try: + from datetime import datetime, timezone + + dt = datetime.strptime( + name, + "%Y%m%d_%H%M%S" + ).replace( + tzinfo=timezone.utc + ) + + return format_report_datetime( + dt.isoformat() + ) + + except Exception: + return name + +# ============================================================ +# Session information +# ============================================================ + + +def load_session( + conn, + session_id: int, +): + + session = session_statistics( + conn, + session_id + ) + + if session is None: + + raise RuntimeError( + f"Session {session_id} not found." + ) + + trip_start, trip_end = trip_time( + conn, + session_id + ) + + if trip_start: + session["trip_start"] = trip_start + + if trip_end: + session["trip_end"] = trip_end + + if trip_start and trip_end: + session["duration"] = format_duration( + trip_start, + trip_end + ) + + session["directory_size"] = format_size( + session_directory_size( + conn, + session_id + ) + ) + + return session + +def load_trip_information( + conn, + session_id, +): + row = query_one( + conn, + """ + SELECT + MIN(timestamp), + MAX(timestamp), + COUNT(*) + FROM gps_track + WHERE session_id=? + """, + ( + session_id, + ), + ) + + if ( + row is None + or + row[0] is None + ): + return { + "trip_start": None, + "trip_end": None, + "trip_points": 0, + } + + return { + "trip_start": row[0], + "trip_end": row[1], + "trip_points": row[2], + } + + +# ============================================================ +# GPS track +# ============================================================ + + +def load_gps_track( + conn, + session_id, +): + rows = query_all( + conn, + """ + SELECT + latitude, + longitude + FROM gps_track + WHERE + session_id=? + ORDER BY + timestamp + """, + ( + session_id, + ), + ) + + track = [] + + for row in rows: + + latitude = row[0] + longitude = row[1] + + if ( + latitude is None + or longitude is None + ): + continue + + if ( + latitude == 0 + or longitude == 0 + ): + continue + + track.append( + { + "lat": latitude, + "lon": longitude, + } + ) + + return track + + +# ============================================================ +# Session observations +# ============================================================ + +def load_session_observations( + + conn, + session_id, + +): + + rows = query_all( + + conn, + + """ + + SELECT + + latitude, + longitude, + rssi, + observed_at, + + id, + bssid, + essid, + vendor, + + encryption, + channel, + frequency, + + has_handshake, + has_pmkid, + is_cracked + + FROM + + ( + + SELECT + + obs.latitude, + obs.longitude, + obs.rssi, + obs.observed_at, + + ap.id, + ap.bssid, + ap.essid, + ap.vendor, + + ap.encryption, + ap.channel, + ap.frequency, + + CASE + WHEN hs.id IS NULL THEN 0 + ELSE 1 + END AS has_handshake, + + ap.has_pmkid, + + CASE + WHEN EXISTS + ( + SELECT 1 + FROM credentials AS c + JOIN handshakes AS ch + ON ch.id = c.handshake_id + WHERE + c.access_point_id = ap.id + AND ch.session_id = obs.session_id + ) + THEN 1 + ELSE 0 + END AS is_cracked, + + ROW_NUMBER() OVER + ( + PARTITION BY obs.access_point_id + ORDER BY + obs.rssi DESC, + obs.observed_at DESC + ) AS rn + + FROM access_point_observations AS obs + + JOIN access_points AS ap + ON ap.id = obs.access_point_id + + LEFT JOIN handshakes AS hs + ON hs.access_point_id = ap.id + AND hs.session_id = obs.session_id + + WHERE obs.session_id = ? + + ) + + WHERE rn = 1 + + ORDER BY + + has_handshake DESC, + + is_cracked DESC, + + rssi DESC + + """, + + ( + + session_id, + + ), + + ) + + observations = [] + + for row in rows: + + observations.append( + + { + + "latitude": row[0], + + "longitude": row[1], + + "rssi": row[2], + + "observed_at": row[3], + + "id": row[4], + + "bssid": row[5], + + "essid": row[6], + + "vendor": row[7], + + "encryption": row[8], + + "channel": row[9], + + "frequency": row[10], + + "handshake": bool(row[11]), + + "pmkid": bool(row[12]), + + "cracked": bool(row[13]), + + } + + ) + + return observations + +# ============================================================ +# Summary +# ============================================================ + + +def summary_block( + + conn, + + session, + + observations, + +): + + access_points = len(observations) + + handshake_ap = sum( + 1 + for ap in observations + if ap["handshake"] + ) + + handshake_records = session.get( + "handshake_records", + handshake_ap + ) + + pmkid_ap = sum( + 1 + for ap in observations + if ap["pmkid"] + ) + + cracked_ap = sum( + 1 + for ap in observations + if ap["cracked"] + ) + + coordinates_restored = session.get( + "coordinates_restored", + coordinates_restored_count( + conn, + session["id"] + ) + ) + + ap_without_coordinates = session.get( + "ap_without_coordinates", + ap_without_coordinates_count( + conn, + session["id"] + ) + ) + + html = f""" + +
+ +
+ +
+ +{access_points} + +
+ +
+ +Access Points + +
+ +
+ +
+ +
+ + {coordinates_restored} + +
+ +
+ + Coordinates Restored + +
+ +
+ +
+ +
+ + {ap_without_coordinates} + +
+ +
+ + AP without Coordinates + +
+ +
+ +
+ +
+ + {handshake_ap} + +
+ +
+ + Handshake AP + +
+ +
+ +
+ +
+ + {handshake_records} + +
+ +
+ + Handshake Records + +
+ +
+ +
+ +
+ + {pmkid_ap} + +
+ +
+ + PMKID AP + +
+ +
+ +
+ +
+ + {cracked_ap} + +
+ +
+ + Cracked AP + +
+ +
+ +
+ +
+ + {session.get("directory_size","-")} + +
+ +
+ + Directory size + +
+ +
+ +
+ +""" + + return card( + + "📊 Session Summary", + + html, + + ) + + +# ============================================================ +# Files +# ============================================================ + + +def files_block( + + session, + +): + + capture = Path( + session["capture_file"] + ) + + directory = capture.parent + + if not directory.exists(): + + html = """ +

📁 Каталог файлов этой поездки отсутствует.

+ +

+ Возможно, он был удалён пользователем вручную. + WiFi GPS Mapper не удаляет каталоги поездок автоматически. + Все данные сохранены в базе данных +

+""" + + else: + + html = """ + + + + + + + + + + + +""" + + files = [ + + "capture.pcapng", + + "gps_track.nmea", + + "access_points.csv", + + "handshakes.22000", + + "essid.txt", + + "parser.log", + + ] + + for name in files: + + filename = directory / name + + html += f""" + + + + + + + + + +""" + + html += """ + +
FileExists
{name}{"✅" if filename.exists() else "—"}
+ +""" + + return card( + + "📂 Session Files", + + html, + + ) + +# ============================================================ +# JavaScript +# ============================================================ + + +def build_track_js( + + track, + +): + + if not track: + + return "const track = [];" + + return ( + + "const track = " + + + json.dumps(track) + + + ";" + + ) + + +def build_marker_js( + + observations, + +): + + markers = [] + + for ap in observations: + + if ( + ap["latitude"] is None + or + ap["longitude"] is None + ): + continue + + popup = f""" + + + +{esc(ap["essid"])} + + + +
+ +{esc(ap["bssid"])} + +
+ +Vendor: +{esc(ap["vendor"])} + +
+ +Encryption: +{esc(ap["encryption"])} + +
+ +Channel: +{esc(ap["channel"])} + +   + +Frequency: +{esc(ap["frequency"])} + +
+ +RSSI: +{esc(ap["rssi"])} dBm + +
+ +Handshake: +{"✅" if ap["handshake"] else "—"} + +   + +PMKID: +{"✅" if ap["pmkid"] else "—"} + +   + +Password: +{"✅" if ap["cracked"] else "—"} + +""" + + markers.append( + + { + + "lat": ap["latitude"], + + "lon": ap["longitude"], + + "popup": popup, + + "handshake": ap["handshake"], + + "pmkid": ap["pmkid"], + + "cracked": ap["cracked"], + + } + + ) + + return ( + + "const markers = " + + + json.dumps( + markers, + ensure_ascii=False, + ) + + + ";" + + ) + +# ============================================================ +# Map +# ============================================================ + + +def map_block( + + track, + + observations, + + context=None, + +): + + track_data = [ + + [ + float(p["lat"]), + float(p["lon"]) + ] + + for p in track + + if ( + p.get("lat") is not None + and + p.get("lon") is not None + and + p.get("lat") != 0 + and + p.get("lon") != 0 + ) + ] + + marker_js = build_marker_js( + observations + ) + + maplibre_css_url = context.asset_url( + "maplibre/maplibre-gl.css" + ) + + maplibre_js_url = context.asset_url( + "maplibre/maplibre-gl.js" + ) + + html = f""" + +
+ + + + + + + +""" + + title = """ + + + 🗺 Capture Map + + + + + + + + + + + + + + + """ + + + return card( + + title, + + html, + + ) + +# ============================================================ +# Access Points +# ============================================================ + +def access_points_block( + + observations, + +): + + html = """ + + + + + + + + + + + + + + + + + + + + + + + + + +""" + + handshake_points = [ + ap + for ap in observations + if ap["handshake"] + ] + + for ap in handshake_points: + + html += f""" + + + + + + + + + + + + + + + + + + + + + + + +""" + + html += """ + +
BSSIDESSIDVendorEncryptionChannelRSSIHSPMKIDPASS
+ +{esc(ap["bssid"])} + + + +{esc(ap["essid"])} + + + +{esc(ap["vendor"])} + + + +{esc(ap["encryption"])} + + + +{esc(ap["channel"])} + + + +{esc(ap["rssi"])} + + + +🤝 + + + +{"🟠" if ap["pmkid"] else ""} + + + +{"🔑" if ap["cracked"] else ""} + +
+ +""" + + return card( + + f"📡 Access Points Handshake ({len(handshake_points)})", + + html, + + ) + +# ============================================================ +# Credentials +# ============================================================ + +def credentials_block( + + conn, + + session_id, + +): + + rows = query_all( + + conn, + + """ + SELECT + + ap.bssid, + ap.essid, + + c.password, + c.source, + + c.created_at, + c.verified + + FROM credentials c + + JOIN access_points ap + + ON ap.id=c.access_point_id + + JOIN handshakes hs + + ON hs.id=c.handshake_id + + WHERE + + hs.session_id=? + + GROUP BY + + c.id + + ORDER BY + + c.created_at DESC + + """, + + ( + + session_id, + + ), + + ) + + if not rows: + + return "" + + html = """ + + + + + + + + + + + + + + + + + +""" + + for row in rows: + + ( + + bssid, + + essid, + + password, + + source, + + created, + + verified, + + ) = row + + html += f""" + + + + + + + + + + + + + + + +""" + + html += """ + +
BSSIDESSIDPasswordSourceVerified
{esc(bssid)}{esc(essid)} + + + +{esc(password)} + + + + + +{esc(source)} + + + +{"✅" if verified else ""} + +
+ +""" + + return card( + + f"🔑 Credentials ({len(rows)})", + + html, + + ) + +# ============================================================ +# Handshakes +# ============================================================ + +def handshakes_block( + + conn, + + session_id, + +): + + rows = query_all( + + conn, + + """ + SELECT + + ap.bssid, + ap.essid, + + h.type, + h.message_pair, + + h.captured_at + + FROM handshakes h + + JOIN access_points ap + + ON ap.id=h.access_point_id + + JOIN access_point_observations obs + + ON obs.access_point_id=ap.id + + WHERE + + obs.session_id=? + + GROUP BY + + h.id + + ORDER BY + + h.captured_at DESC + + """, + + ( + + session_id, + + ), + + ) + + if not rows: + + return "" + + html = """ + + + + + + + + + + + + + + + + + +""" + + for row in rows: + + ( + + bssid, + + essid, + + hs_type, + + pair, + + captured, + + ) = row + + html += f""" + + + + + + + + + + + + + + + +""" + + html += """ + +
BSSIDESSIDTypeMessage PairCaptured
+ +{esc(bssid)} + + + +{esc(essid)} + + + +{esc(hs_type)} + + + +{esc(pair)} + + + +{esc(format_datetime(captured))} + +
+ +""" + + return card( + + f"🤝 Handshakes ({len(rows)})", + + html, + + ) + +# ============================================================ +# Session page +# ============================================================ + +def render_session_page( + + conn, + + session_id, + + context=None, + +): + + if context is None: + context = ReportContext() + + context = context.session_page() + + session = load_session( + + conn, + + session_id, + + ) + + trip = load_trip_information( + conn, + session_id, + ) + + session.update( + trip + ) + + track = load_gps_track( + conn, + session_id, + ) + + observations = load_session_observations( + + conn, + + session_id, + + ) + + html = page_begin( + + f"Session {format_session_folder(Path(session['capture_file']).parent.name)}", + + active="capture_sessions", + + context=context, + + ) + + html += page_header( + + f"🚗 Session {format_datetime(session.get('trip_start'))}", + + f""" + +Trip start: + +{esc(format_datetime(session.get("trip_start")))} + +
+ +Trip end: + +{esc(format_datetime(session.get("trip_end")))} + +
+ +Duration: + +{esc(session.get("duration", "-"))} + +
+ +Database imported: + +{esc(format_datetime(session["start_time"]))} + +
+ +Session folder: + +{esc(Path(session["capture_file"]).parent.name)} + +""" + + ) + + html += summary_block( + + conn, + + session, + + observations, + + ) + + html += files_block( + + session, + + ) + + html += map_block( + + track, + + observations, + + context, + + ) + + html += access_points_block( + + observations, + + ) + + + # Handshakes block removed + + + html += credentials_block( + + conn, + + session_id, + + ) + + html += page_end() + + return html + + +def save_session_page( + conn, + session_id, + context=None, +): + html = render_session_page( + conn, + session_id, + context, + ) + + output_dir = ( + Path(__file__).parent + / "output" + / "sessions" + ) + + output_dir.mkdir( + parents=True, + exist_ok=True, + ) + + filename = ( + output_dir + / f"{session_id}.html" + ) + + filename.write_text( + html, + encoding="utf-8", + ) + + return filename + +# ============================================================ +# Build all pages +# ============================================================ + +def build_all_session_pages( + conn, + context=None, +): + rows = query_all( + conn, + """ + SELECT id + FROM capture_sessions + ORDER BY start_time + """, + ) + generated = [] + for ( + session_id, + ) in rows: + generated.append( + save_session_page( + conn, + session_id, + context, + ) + ) + return generated diff --git a/reports/sessions.py b/reports/sessions.py new file mode 100644 index 0000000..29e55ba --- /dev/null +++ b/reports/sessions.py @@ -0,0 +1,1019 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Работа с capture_sessions. + +Модуль предоставляет функции для получения +информации о поездках (захватах). + +Используется: + + dashboard.py + + session_page.py + + generator.py +""" + +from pathlib import Path + +from .config import ( + CAPTURES_DIR, +) + +from .database import ( + query_all, + query_one, + query_value, +) + +from datetime import datetime + +from .utils import ( + format_duration, + format_size, +) + + +# ============================================================ +# Список всех поездок +# ============================================================ + +def get_sessions(conn): + + sql = """ + + SELECT + + id, + + start_time, + + end_time, + + capture_file + + FROM capture_sessions + + ORDER BY + + start_time DESC + + """ + + return query_all( + conn, + sql + ) + + +# ============================================================ +# Получить одну поездку +# ============================================================ + +def get_session( + conn, + session_id +): + + sql = """ + + SELECT + + id, + + start_time, + + end_time, + + capture_file + + FROM capture_sessions + + WHERE id=? + + """ + + return query_one( + conn, + sql, + ( + session_id, + ) + ) + + +# ============================================================ +# Продолжительность +# ============================================================ + +def session_duration( + conn, + session_id +): + + row = query_one( + conn, + """ + + SELECT + + start_time, + + end_time + + FROM capture_sessions + + WHERE id=? + + """, + ( + session_id, + ) + ) + + if row is None: + + return None + + start = row[0] + + end = row[1] + + return format_duration( + start, + end + ) + +# ============================================================ +# Реальное время поездки (GPS) +# ============================================================ + +def trip_time( + conn, + session_id, +): + + row = query_one( + conn, + """ + SELECT + + MIN(timestamp), + MAX(timestamp) + + FROM gps_track + + WHERE session_id=? + + """, + ( + session_id, + ) + ) + + if row is None: + + return ( + None, + None, + ) + + return ( + row[0], + row[1], + ) + +# ============================================================ +# Количество точек доступа в поездке +# ============================================================ + +def access_points_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(DISTINCT access_point_id) + + FROM access_point_observations + + WHERE session_id=? + """, + ( + session_id, + ), + default=0 + ) + + +# ============================================================ +# Handshake AP (уникальные точки) +# ============================================================ + +def handshakes_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(DISTINCT access_point_id) + + FROM handshakes + + WHERE session_id=? + """, + ( + session_id, + ), + default=0 + ) + + +# ============================================================ +# Handshake Records (все записи) +# ============================================================ + +def handshake_records_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(*) + + FROM handshakes + + WHERE session_id=? + """, + ( + session_id, + ), + default=0 + ) + +# ============================================================ +# Найденные пароли +# ============================================================ + +def credentials_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(DISTINCT c.id) + + FROM credentials c + + JOIN access_points ap + ON ap.id = c.access_point_id + + JOIN access_point_observations obs + ON obs.access_point_id = ap.id + + WHERE obs.session_id = ? + """, + ( + session_id, + ), + default=0 + ) + + +# ============================================================ +# PMKID +# ============================================================ + +def pmkid_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(DISTINCT ap.id) + + FROM access_points ap + + JOIN access_point_observations obs + ON obs.access_point_id = ap.id + + WHERE + obs.session_id = ? + AND ap.has_pmkid = 1 + """, + ( + session_id, + ), + default=0 + ) + + +# ============================================================ +# Взломанные сети +# ============================================================ + +def cracked_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(DISTINCT ap.id) + + FROM access_points ap + + JOIN access_point_observations obs + ON obs.access_point_id = ap.id + + WHERE + obs.session_id = ? + AND ap.is_cracked = 1 + """, + ( + session_id, + ), + default=0 + ) + + +def coordinates_restored_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(*) + FROM + ( + SELECT + current_obs.access_point_id + FROM access_point_observations AS current_obs + WHERE + current_obs.session_id = ? + AND current_obs.latitude IS NOT NULL + AND current_obs.longitude IS NOT NULL + AND current_obs.latitude != 0 + AND current_obs.longitude != 0 + AND EXISTS + ( + SELECT 1 + FROM access_point_observations AS previous_obs + WHERE + previous_obs.access_point_id = + current_obs.access_point_id + AND previous_obs.observed_at < + ( + SELECT start_time + FROM capture_sessions + WHERE id=? + ) + ) + AND NOT EXISTS + ( + SELECT 1 + FROM access_point_observations AS previous_coords + WHERE + previous_coords.access_point_id = + current_obs.access_point_id + AND previous_coords.observed_at < + ( + SELECT start_time + FROM capture_sessions + WHERE id=? + ) + AND previous_coords.latitude IS NOT NULL + AND previous_coords.longitude IS NOT NULL + AND previous_coords.latitude != 0 + AND previous_coords.longitude != 0 + ) + GROUP BY current_obs.access_point_id + ) + """, + ( + session_id, + session_id, + session_id + ), + default=0 + ) + + +def ap_without_coordinates_count( + conn, + session_id +): + + return query_value( + conn, + """ + SELECT COUNT(*) + FROM + ( + SELECT + obs.access_point_id + FROM access_point_observations AS obs + WHERE + obs.session_id = ? + GROUP BY obs.access_point_id + HAVING + SUM( + CASE + WHEN obs.latitude IS NOT NULL + AND obs.longitude IS NOT NULL + AND obs.latitude != 0 + AND obs.longitude != 0 + THEN 1 + ELSE 0 + END + ) = 0 + ) + """, + ( + session_id, + ), + default=0 + ) + +# ============================================================ +# Полная статистика поездки +# ============================================================ + +def session_statistics( + conn, + session_id +): + + row = get_session( + conn, + session_id + ) + + if row is None: + + return None + + ( + ident, + start_time, + end_time, + capture_file, + ) = row + + return { + + "id": ident, + + "start_time": start_time, + + "end_time": end_time, + + "duration": session_duration( + conn, + session_id + ), + + "access_points": access_points_count( + conn, + session_id + ), + + "coordinates_restored": coordinates_restored_count( + conn, + session_id + ), + + "ap_without_coordinates": ap_without_coordinates_count( + conn, + session_id + ), + + "handshakes": handshakes_count( + conn, + session_id + ), + + "handshake_records": handshake_records_count( + conn, + session_id + ), + + "credentials": credentials_count( + conn, + session_id + ), + + "pmkid": pmkid_count( + conn, + session_id + ), + + "cracked": cracked_count( + conn, + session_id + ), + + "capture_file": capture_file, + + } + +# ============================================================ +# Каталог поездки +# ============================================================ + +def session_directory(capture_file): + + if capture_file is None: + + return None + + capture_path = Path(capture_file) + + if capture_path.parent.exists(): + + return capture_path.parent + + return CAPTURES_DIR / capture_path.parent.name + + +# ============================================================ +# Проверка существования файла +# ============================================================ + +def file_exists(path): + + if path is None: + + return False + + return Path(path).exists() + + +# ============================================================ +# Получить все файлы поездки +# ============================================================ + +def session_files( + conn, + session_id +): + + row = get_session( + conn, + session_id + ) + + if row is None: + + return None + + directory = session_directory( + row[3] + ) + + files = { + + "directory": directory, + + "capture": directory / "capture.pcapng", + + "gps_track": directory / "gps_track.nmea", + + "parser_log": directory / "parser.log", + + "access_points": directory / "access_points.csv", + + "handshakes": directory / "handshakes.22000", + + "essid": directory / "essid.txt", + + } + + return files + + +# ============================================================ +# Файлы, реально существующие на диске +# ============================================================ + +def existing_files( + conn, + session_id +): + + files = session_files( + conn, + session_id + ) + + if files is None: + + return {} + + result = {} + + for name, path in files.items(): + + if name == "directory": + + result[name] = path + + continue + + result[name] = { + + "path": path, + + "exists": file_exists(path), + + "size": path.stat().st_size if file_exists(path) else 0, + + } + + return result + + +# ============================================================ +# Размер каталога поездки +# ============================================================ + +def session_directory_size( + conn, + session_id +): + + files = session_files( + conn, + session_id + ) + + if files is None: + return 0 + + directory = files["directory"] + + if not directory.exists(): + return 0 + + total = 0 + + for file in directory.iterdir(): + + if file.is_file(): + total += file.stat().st_size + + return total + + +# ============================================================ +# Последние поездки +# ============================================================ + +def recent_sessions( + conn, + limit=10 +): + + sql = """ + + SELECT + + id + + FROM capture_sessions + + ORDER BY + + start_time DESC + + LIMIT ? + + """ + + rows = conn.execute( + sql, + ( + limit, + ) + ).fetchall() + + result = [] + + for row in rows: + + card = session_card_data( + + conn, + + row[0] + + ) + + if card: + + result.append(card) + + return result + +# ============================================================ +# Самая длинная поездка +# ============================================================ + +def longest_session(conn): + + sql = """ + + SELECT + + id, + + start_time, + + end_time + + FROM capture_sessions + + WHERE end_time IS NOT NULL + + """ + + rows = conn.execute(sql).fetchall() + + winner = None + + seconds = -1 + + for ident, start, end in rows: + + try: + + s = datetime.fromisoformat(start) + + e = datetime.fromisoformat(end) + + except Exception: + + continue + + diff = (e - s).total_seconds() + + if diff > seconds: + + seconds = diff + + winner = ident + + if winner is None: + + return None + + return session_statistics( + conn, + winner + ) + + +# ============================================================ +# Самая короткая поездка +# ============================================================ + +def shortest_session(conn): + + sql = """ + + SELECT + + id, + + start_time, + + end_time + + FROM capture_sessions + + WHERE end_time IS NOT NULL + + """ + + rows = conn.execute(sql).fetchall() + + winner = None + + seconds = None + + for ident, start, end in rows: + + try: + + s = datetime.fromisoformat(start) + + e = datetime.fromisoformat(end) + + except Exception: + + continue + + diff = (e - s).total_seconds() + + if seconds is None or diff < seconds: + + seconds = diff + + winner = ident + + if winner is None: + + return None + + return session_statistics( + conn, + winner + ) + + +# ============================================================ +# Карточка поездки +# ============================================================ + +def session_card_data( + conn, + session_id +): + + stat = session_statistics( + conn, + session_id + ) + + if stat is None: + + return None + + files = existing_files( + conn, + session_id + ) + + stat["files"] = files + + trip_start, trip_end = trip_time( + conn, + session_id + ) + + if trip_start: + stat["trip_start"] = trip_start + + if trip_end: + stat["trip_end"] = trip_end + + if trip_start and trip_end: + stat["duration"] = format_duration( + trip_start, + trip_end + ) + + stat["directory_size"] = format_size( + + session_directory_size( + conn, + session_id + ) + + ) + + return stat + + +# ============================================================ +# Карточки всех поездок +# ============================================================ + +def all_sessions( + conn +): + + sql = """ + + SELECT + + id + + FROM capture_sessions + + ORDER BY + + start_time DESC + + """ + + rows = conn.execute( + sql + ).fetchall() + + result = [] + + for row in rows: + + card = session_card_data( + conn, + row[0] + ) + + if card: + + result.append(card) + + return result + +def all_session_cards(conn): + + sql = """ + + SELECT + + id + + FROM capture_sessions + + ORDER BY + + start_time DESC + + """ + + rows = conn.execute(sql).fetchall() + + result = [] + + for row in rows: + + card = session_card_data( + + conn, + + row[0] + + ) + + if card: + + result.append(card) + + return result + + +# ============================================================ +# Поиск поездки по ID +# ============================================================ + +def find_session( + conn, + session_id +): + + for session in all_session_cards(conn): + + if session["id"] == session_id: + + return session + + return None + + +# ============================================================ +# Всего поездок +# ============================================================ + +def sessions_count(conn): + + return query_value( + + conn, + + """ + + SELECT COUNT(*) + + FROM capture_sessions + + """, + + default=0 + + ) \ No newline at end of file diff --git a/reports/static/fonts/Bender-Bold.woff b/reports/static/fonts/Bender-Bold.woff new file mode 100644 index 0000000..cde28f9 Binary files /dev/null and b/reports/static/fonts/Bender-Bold.woff differ diff --git a/reports/static/fonts/Bender-Bold.woff2 b/reports/static/fonts/Bender-Bold.woff2 new file mode 100644 index 0000000..1caf36c Binary files /dev/null and b/reports/static/fonts/Bender-Bold.woff2 differ diff --git a/reports/static/fonts/Bender-Light.woff b/reports/static/fonts/Bender-Light.woff new file mode 100644 index 0000000..1ed6dd5 Binary files /dev/null and b/reports/static/fonts/Bender-Light.woff differ diff --git a/reports/static/fonts/Bender-Light.woff2 b/reports/static/fonts/Bender-Light.woff2 new file mode 100644 index 0000000..bbae05d Binary files /dev/null and b/reports/static/fonts/Bender-Light.woff2 differ diff --git a/reports/static/fonts/Bender.otf b/reports/static/fonts/Bender.otf new file mode 100644 index 0000000..e2ae7ee Binary files /dev/null and b/reports/static/fonts/Bender.otf differ diff --git a/reports/static/fonts/Bender.woff b/reports/static/fonts/Bender.woff new file mode 100644 index 0000000..92f4b54 Binary files /dev/null and b/reports/static/fonts/Bender.woff differ diff --git a/reports/static/fonts/Bender.woff2 b/reports/static/fonts/Bender.woff2 new file mode 100644 index 0000000..39df036 Binary files /dev/null and b/reports/static/fonts/Bender.woff2 differ diff --git a/reports/static/maplibre/maplibre-gl.css b/reports/static/maplibre/maplibre-gl.css new file mode 100644 index 0000000..c7138c2 --- /dev/null +++ b/reports/static/maplibre/maplibre-gl.css @@ -0,0 +1 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0,0,0,0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media (hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}}.maplibregl-ctrl button:not(:disabled):active{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px;white-space:nowrap}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}[dir=rtl] .maplibregl-popup-anchor-left{flex-direction:row-reverse}[dir=rtl] .maplibregl-popup-anchor-right{flex-direction:row}[dir=rtl] .maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-start}[dir=rtl] .maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-start}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@media (prefers-reduced-motion:reduce){.maplibregl-user-location-dot:before{animation:none}}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/reports/static/maplibre/maplibre-gl.js b/reports/static/maplibre/maplibre-gl.js new file mode 100644 index 0000000..3ffbfaf --- /dev/null +++ b/reports/static/maplibre/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.22.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(t){try{l(r.next(t));}catch(t){s(t);}}function a(t){try{l(r.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e);}))).then(o,a);}l((r=r.apply(t,e||[])).next());}))}function n(t,e){this.x=t,this.y=e;}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,n.prototype={clone(){return new n(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,n=t.y-this.y;return e*e+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),n=Math.sin(t),r=n*this.x+e*this.y;return this.x=e*this.x-n*this.y,this.y=r,this},_rotateAround(t,e){const n=Math.cos(t),r=Math.sin(t),i=e.y+r*(this.x-e.x)+n*(this.y-e.y);return this.x=e.x+n*(this.x-e.x)-r*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:n},n.convert=function(t){if(t instanceof n)return t;if(Array.isArray(t))return new n(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new n(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var o=function(){if(s)return i;function t(t,e,n,r){this.cx=3*t,this.bx=3*(n-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=n,this.p2y=r;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var n=t,r=0;r<8;r++){var i=this.sampleCurveX(n)-t;if(Math.abs(i)i?o=n:a=n,n=.5*(a-o)+o;return n},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),a=r(o);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let n=0;n4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,r*=s,n*=s;var o=Math.sin(e),a=Math.cos(e),l=Math.sin(n),u=Math.cos(n),c=Math.sin(r),h=Math.cos(r);switch(i){case "xyz":t[0]=o*u*h+a*l*c,t[1]=a*l*h-o*u*c,t[2]=a*u*c+o*l*h,t[3]=a*u*h-o*l*c;break;case "xzy":t[0]=o*u*h-a*l*c,t[1]=a*l*h-o*u*c,t[2]=a*u*c+o*l*h,t[3]=a*u*h+o*l*c;break;case "yxz":t[0]=o*u*h+a*l*c,t[1]=a*l*h-o*u*c,t[2]=a*u*c-o*l*h,t[3]=a*u*h+o*l*c;break;case "yzx":t[0]=o*u*h+a*l*c,t[1]=a*l*h+o*u*c,t[2]=a*u*c-o*l*h,t[3]=a*u*h-o*l*c;break;case "zxy":t[0]=o*u*h-a*l*c,t[1]=a*l*h+o*u*c,t[2]=a*u*c+o*l*h,t[3]=a*u*h-o*l*c;break;case "zyx":t[0]=o*u*h-a*l*c,t[1]=a*l*h+o*u*c,t[2]=a*u*c-o*l*h,t[3]=a*u*h+o*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function E(t,e){var n=new f(2);return n[0]=t,n[1]=e,n}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),M(),M(),d(),I();const T=8192;function F(t,e,n){return e*(T/(t.tileSize*Math.pow(2,n-t.tileID.overscaledZ)))}function P(t,e){return (t%e+e)%e}function D(t,e,n){return t*(1-n)+e*n}function z(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,n=e*t;return 4*(t<.5?n:3*(t-e)+n-.75)}function B(t,e,n,r){const i=new a(t,e,n,r);return t=>i.solve(t)}const C=B(.25,.1,.25,1);function V(t,e,n){return Math.min(n,Math.max(e,t))}function L(t,e,n){const r=n-e,i=((t-e)%r+r)%r+e;return i===e?n:i}function O(t,...e){for(const n of e)for(const e in n)t[e]=n[e];return t}let $=1;function R(t,e,n){const r={};for(const n in t)r[n]=e.call(this,t[n],n,t);return r}function N(t,e,n){const r={};for(const n in t)e.call(this,t[n],n,t)&&(r[n]=t[n]);return r}function U(t){return Array.isArray(t)?t.map(U):"object"==typeof t&&t?R(t,U):t}const j={};function q(t){j[t]||("undefined"!=typeof console&&console.warn(t),j[t]=!0);}function G(t,e,n){return (n.y-t.y)*(e.x-t.x)>(e.y-t.y)*(n.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Y=null;function Z(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function W(t,n,r,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const o=null==e?void 0:e.format;if(!o||!o.startsWith("BGR")&&!o.startsWith("RGB"))throw new Error(`Unrecognized format ${o}`);const a=o.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,n,r,i){const s=4*Math.max(-e,0),o=(Math.max(0,n)-n)*r*4+s,a=4*r,l=Math.max(0,e),u=Math.max(0,n);return {rect:{x:l,y:u,width:Math.min(t.width,e+r)-l,height:Math.min(t.height,n+i)-u},layout:[{offset:o,stride:a}]}}(t,n,r,i,s)),a)for(let t=0;t{t.removeEventListener(e,n,r);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const nt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},rt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";class st extends Error{constructor(t=it){super(t instanceof Error?t.message:t),this.name=it,t instanceof Error&&t.stack&&(this.stack=t.stack);}}function ot(t){return t.name===it}function at(t){if(t.aborted)throw new st(t.reason)}const lt={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ut(t){return lt.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const ct="global-dispatcher";class ht extends Error{constructor(t,e,n,r){super(`AJAXError: ${e} (${t}): ${n}`),this.status=t,this.statusText=e,this.url=n,this.body=r;}}const pt=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ft=function(t,n){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ut(t.url);if(e)return e(t,n);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:ct},n)}if(!(/^file:/.test(r=t.url)||/^file:/.test(pt())&&!/^\w+:/.test(r))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,n){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:pt(),referrerPolicy:t.referrerPolicy,signal:n.signal});let r,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{r=yield fetch(e);}catch(e){if(ot(e))throw e;throw new ht(0,e.message,t.url,new Blob)}if(!r.ok){const e=yield r.blob();throw new ht(r.status,r.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text();const s=yield i;return at(n.signal),{data:s,cacheControl:r.headers.get("Cache-Control"),expires:r.headers.get("Expires"),etag:r.headers.get("ETag")}}))}(t,n);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:ct},n)}var r;return function(t,e){return new Promise(((n,r)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{r(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void r(t)}n({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires"),etag:s.getResponseHeader("ETag")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});r(new ht(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),r(new st(e.signal.reason));})),s.send(t.body);}))}(t,n)};function dt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),n=window.location;return e.protocol===n.protocol&&e.host===n.host}function yt(t,e,n){n[t]&&-1!==n[t].indexOf(e)||(n[t]=n[t]||[],n[t].push(e));}function mt(t,e,n){if(n&&n[t]){const r=n[t].indexOf(e);-1!==r&&n[t].splice(r,1);}}class gt{constructor(t,e={}){O(this,e),this.type=t;}}class xt extends gt{constructor(t,e={}){super("error",O({error:t},e));}}class vt{on(t,e){return this._listeners=this._listeners||{},yt(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return mt(t,e,this._listeners),mt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},yt(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new gt(t,e||{}));const n=t.type;if(this.listens(n)){t.target=this;const e=this._listeners&&this._listeners[n]?this._listeners[n].slice():[];for(const n of e)n.call(this,t);const r=this._oneTimeListeners&&this._oneTimeListeners[n]?this._oneTimeListeners[n].slice():[];for(const e of r)mt(n,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(O(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof xt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var bt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number",length:2},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},encoding:{type:"enum",values:{mvt:{},mlt:{}},default:"mvt"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"filter"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},filter:{type:"boolean",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"expression_name",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}},interpolation:{type:"array",value:"interpolation_name",minimum:1},interpolation_name:{type:"enum",values:{linear:{syntax:{overloads:[{parameters:[],"output-type":"interpolation"}],parameters:[]}},exponential:{syntax:{overloads:[{parameters:["base"],"output-type":"interpolation"}],parameters:[{name:"base",type:"number literal"}]}},"cubic-bezier":{syntax:{overloads:[{parameters:["x1","y1","x2","y2"],"output-type":"interpolation"}],parameters:[{name:"x1",type:"number literal"},{name:"y1",type:"number literal"},{name:"x2",type:"number literal"},{name:"y2",type:"number literal"}]}}}}};const wt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function _t(t,e){const n={};for(const e in t)"ref"!==e&&(n[e]=t[e]);return wt.forEach((t=>{t in e&&(n[t]=e[t]);})),n}function St(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let n=0;n`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Qt=[Vt,Lt,Ot,$t,Rt,Nt,Gt,Ut,Kt(jt),Xt,Zt,Yt,Ht,Wt];function te(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!te(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Qt)if(!te(t,e))return null}return `Expected ${Jt(t)} but found ${Jt(e)} instead.`}function ee(t,e){return e.some((e=>e.kind===t.kind))}function ne(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function re(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const ie=.96422,se=.82521,oe=4/29,ae=6/29,le=3*ae*ae,ue=ae*ae*ae,ce=Math.PI/180,he=180/Math.PI;function pe(t){return (t%=360)<0&&(t+=360),t}function fe([t,e,n,r]){let i,s;const o=ye((.2225045*(t=de(t))+.7168786*(e=de(e))+.0606169*(n=de(n)))/1);t===e&&e===n?i=s=o:(i=ye((.4360747*t+.3850649*e+.1430804*n)/ie),s=ye((.0139322*t+.0971045*e+.7141733*n)/se));const a=116*o-16;return [a<0?0:a,500*(i-o),200*(o-s),r]}function de(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function ye(t){return t>ue?Math.pow(t,1/3):t/le+oe}function me([t,e,n,r]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,o=isNaN(n)?i:i-n/200;return i=1*xe(i),s=ie*xe(s),o=se*xe(o),[ge(3.1338561*s-1.6168667*i-.4906146*o),ge(-.9787684*s+1.9161415*i+.033454*o),ge(.0719453*s-.2289914*i+1.4052427*o),r]}function ge(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function xe(t){return t>ae?t*t*t:le*(t-oe)}const ve=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function be(t,e){return ve(t,e)?t[e]:void 0}function we(t){return parseInt(t.padEnd(2,t),16)/255}function _e(t,e){return Se(e?t/100:t,0,1)}function Se(t,e,n){return Math.min(Math.max(e,t),n)}function Ae(t){return !t.some(Number.isNaN)}const Me={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function ke(t,e,n){return t+n*(e-t)}function Ie(t,e,n){return t.map(((t,r)=>ke(t,e[r],n)))}class Ee{constructor(t,e,n,r=1,i=!0){this.r=t,this.g=e,this.b=n,this.a=r,i||(this.r*=r,this.g*=r,this.b*=r,r||this.overwriteGetter("rgb",[t,e,n,r]));}static parse(t){if(t instanceof Ee)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=be(Me,t);if(e){const[t,n,r]=e;return [t/255,n/255,r/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let n=1;return [we(t.slice(n,n+=e)),we(t.slice(n,n+=e)),we(t.slice(n,n+=e)),we(t.slice(n,n+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,n,r,i,s,o,a,l,u,c,h,p]=e,f=[i||" ",a||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[r,o,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[Se(+n/e,0,1),Se(+s/e,0,1),Se(+l/e,0,1),h?_e(+h,p):1];if(Ae(t))return t}}return}}const n=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(n){const[t,e,r,i,s,o,a,l,u]=n,c=[r||" ",s||" ",a].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,Se(+i,0,100),Se(+o,0,100),l?_e(+l,u):1];if(Ae(t))return function([t,e,n,r]){function i(r){const i=(r+t/30)%12,s=e*Math.min(n,1-n);return n-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=pe(t),e/=100,n/=100,[i(0),i(8),i(4),r]}(t)}}}(t);return e?new Ee(...e,!1):void 0}get rgb(){const{r:t,g:e,b:n,a:r}=this,i=r||1/0;return this.overwriteGetter("rgb",[t/i,e/i,n/i,r])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,n,r,i]=fe(t),s=Math.sqrt(n*n+r*r);return [Math.round(1e4*s)?pe(Math.atan2(r,n)*he):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",fe(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,n,r]=this.rgb;return `rgba(${[t,e,n].map((t=>Math.round(255*t))).join(",")},${r})`}static interpolate(t,e,n,r="rgb"){switch(r){case "rgb":{const[r,i,s,o]=Ie(t.rgb,e.rgb,n);return new Ee(r,i,s,o,!1)}case "hcl":{const[r,i,s,o]=t.hcl,[a,l,u,c]=e.hcl;let h,p;if(isNaN(r)||isNaN(a))isNaN(r)?isNaN(a)?h=NaN:(h=a,1!==s&&0!==s||(p=l)):(h=r,1!==u&&0!==u||(p=i));else {let t=a-r;a>r&&t>180?t-=360:a180&&(t+=360),h=r+n*t;}const[f,d,y,m]=function([t,e,n,r]){return t=isNaN(t)?0:t*ce,me([n,Math.cos(t)*e,Math.sin(t)*e,r])}([h,null!=p?p:ke(i,l,n),ke(s,u,n),ke(o,c,n)]);return new Ee(f,d,y,m,!1)}case "lab":{const[r,i,s,o]=me(Ie(t.lab,e.lab,n));return new Ee(r,i,s,o,!1)}}}}Ee.black=new Ee(0,0,0,1),Ee.white=new Ee(1,1,1,1),Ee.transparent=new Ee(0,0,0,0),Ee.red=new Ee(1,0,0,1);class Te{constructor(t,e,n){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=n,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const Fe=["bottom","center","top"];class Pe{constructor(t,e,n,r,i,s){this.text=t,this.image=e,this.scale=n,this.fontStack=r,this.textColor=i,this.verticalAlign=s;}}class De{constructor(t){this.sections=t;}static fromString(t){return new De([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof De?t:De.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class ze{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof ze)return t;if("number"==typeof t)return new ze([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new ze(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new ze(Ie(t.values,e.values,n))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("number"==typeof t)return new Be([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Be(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new Be(Ie(t.values,e.values,n))}}class Ce{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ce)return t;if("string"==typeof t){const e=Ee.parse(t);if(!e)return;return new Ce([e])}if(!Array.isArray(t))return;const e=[];for(const n of t){if("string"!=typeof n)return;const t=Ee.parse(n);if(!t)return;e.push(t);}return new Ce(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n,r="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof n&&n>=0&&n<=255?void 0===r||"number"==typeof r&&r>=0&&r<=1?null:`Invalid rgba value [${[t,e,n,r].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof r?[t,e,n,r]:[t,e,n]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Ue(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Re||t instanceof Ee||t instanceof Te||t instanceof De||t instanceof ze||t instanceof Be||t instanceof Ce||t instanceof Oe||t instanceof $e)return !0;if(Array.isArray(t)){for(const e of t)if(!Ue(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Ue(t[e]))return !1;return !0}return !1}function je(t){if(null===t)return Vt;if("string"==typeof t)return Ot;if("boolean"==typeof t)return $t;if("number"==typeof t)return Lt;if(t instanceof Ee)return Rt;if(t instanceof Re)return Nt;if(t instanceof Te)return qt;if(t instanceof De)return Gt;if(t instanceof ze)return Xt;if(t instanceof Be)return Zt;if(t instanceof Ce)return Yt;if(t instanceof Oe)return Wt;if(t instanceof $e)return Ht;if(Array.isArray(t)){const e=t.length;let n;for(const e of t){const t=je(e);if(n){if(n===t)continue;n=jt;break}n=t;}return Kt(n||jt,e)}return Ut}function qe(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Ee||t instanceof Re||t instanceof De||t instanceof ze||t instanceof Be||t instanceof Ce||t instanceof Oe||t instanceof $e?t.toString():JSON.stringify(t)}class Ge{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Ue(t[1]))return e.error("invalid value");const n=t[1];let r=je(n);const i=e.expectedType;return "array"!==r.kind||0!==r.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(r=i),new Ge(r,n)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const Xe={string:Ot,number:Lt,boolean:$t,object:Ut};class Ye{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n,r=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const n=t[1];if("string"!=typeof n||!(n in Xe)||"object"===n)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=Xe[n],r++;}else i=jt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],r++;}n=Kt(i,s);}else {if(!Xe[i])throw new Error(`Types doesn't contain name = ${i}`);n=Xe[i];}const s=[];for(;rt.outputDefined()))}}const Ze={"to-boolean":$t,"to-color":Rt,"to-number":Lt,"to-string":Ot};class He{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[0];if(!Ze[n])throw new Error(`Can't parse ${n} as it is not part of the known types`);if(("to-boolean"===n||"to-string"===n)&&2!==t.length)return e.error("Expected one argument.");const r=Ze[n],i=[];for(let n=1;n4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Ne(e[0],e[1],e[2],e[3]),!n))return new Ee(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(n||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const n of this.args){e=n.evaluate(t);const r=ze.parse(e);if(r)return r}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=Be.parse(e);if(r)return r}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=Ce.parse(e);if(r)return r}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const n of this.args){e=n.evaluate(t);const r=Oe.parse(e);if(r)return r}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const n of this.args){if(e=n.evaluate(t),null===e)return 0;const r=Number(e);if(!isNaN(r))return r}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return De.fromString(qe(this.args[0].evaluate(t)));case "resolvedImage":return $e.fromString(qe(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return qe(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const We=["Unknown","Point","LineString","Polygon"];class Ke{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?We[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Ee.parse(t),this._parseColorCache.set(t,e)),e}}class Je{constructor(t,e,n=[],r,i=new Ct,s=[]){this.registry=t,this.path=n,this.key=n.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=r,this._isConstant=e;}parse(t,e,n,r,i={}){return e?this.concat(e,n,r)._parse(t,i):this._parse(t,i)}_parse(t,e){function n(t,e,n){return "assert"===n?new Ye(e,[t]):"coerce"===n?new He(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const r=t[0];if("string"!=typeof r)return this.error(`Expression name must be a string, but found ${typeof r} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[r];if(i){let r=i.parse(t,this);if(!r)return null;if(this.expectedType){const t=this.expectedType,i=r.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))r=n(r,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else r=n(r,t,e.typeAnnotation||"assert");}if(!(r instanceof Ge)&&"resolvedImage"!==r.type.kind&&this._isConstant(r)){const t=new Ke;try{r=new Ge(r.type,r.evaluate(t));}catch(t){return this.error(t.message),null}}return r}return this.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,n){const r="number"==typeof t?this.path.concat(t):this.path,i=n?this.scope.concat(n):this.scope;return new Je(this.registry,this._isConstant,r,e||null,i,this.errors)}error(t,...e){const n=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Bt(n,t));}checkSubtype(t,e){const n=te(t,e);return n&&this.error(n),n}}class Qe{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const n=[];for(let r=1;r=n.length)throw new Ve(`Array index out of bounds: ${e} > ${n.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return n[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class nn{constructor(t,e){this.type=$t,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,jt),r=e.parse(t[2],2,jt);return n&&r?ee(n.type,[$t,Ot,Lt,Vt,jt])?new nn(n,r):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Jt(n.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!n)return !1;if(!ne(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Jt(je(e))} instead.`);if(!ne(n,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Jt(je(n))} instead.`);return n.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class rn{constructor(t,e,n){this.type=Lt,this.needle=t,this.haystack=e,this.fromIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,jt),r=e.parse(t[2],2,jt);if(!n||!r)return null;if(!ee(n.type,[$t,Ot,Lt,Vt,jt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Jt(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Lt);return i?new rn(n,r,i):null}return new rn(n,r)}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!ne(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Jt(je(e))} instead.`);let r;if(this.fromIndex&&(r=this.fromIndex.evaluate(t)),ne(n,["string"])){const t=n.indexOf(e,r);return -1===t?-1:[...n.slice(0,t)].length}if(ne(n,["array"]))return n.indexOf(e,r);throw new Ve(`Expected second argument to be of type array or string, but found ${Jt(je(n))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class sn{constructor(t,e,n,r,i,s){this.inputType=t,this.type=e,this.input=n,this.cases=r,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let n,r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const i={},s=[];for(let o=2;oNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(n){if(u.checkSubtype(n,je(t)))return null}else n=je(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,o,r);if(!c)return null;r=r||c.type,s.push(c);}const o=e.parse(t[1],1,jt);if(!o)return null;const a=e.parse(t[t.length-1],t.length-1,r);return a?"value"!==o.type.kind&&e.concat(1).checkSubtype(n,o.type)?null:new sn(n,r,o,i,s,a):null}evaluate(t){const e=this.input.evaluate(t);return (je(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class on{constructor(t,e,n){this.type=t,this.branches=e,this.otherwise=n;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const r=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class an{constructor(t,e,n,r){this.type=t,this.input=e,this.beginIndex=n,this.endIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,jt),r=e.parse(t[2],2,Lt);if(!n||!r)return null;if(!ee(n.type,[Kt(jt),Ot,jt]))return e.error(`Expected first argument to be of type array or string, but found ${Jt(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Lt);return i?new an(n.type,n,r,i):null}return new an(n.type,n,r)}evaluate(t){const e=this.input.evaluate(t),n=this.beginIndex.evaluate(t);let r;if(this.endIndex&&(r=this.endIndex.evaluate(t)),ne(e,["string"]))return [...e].slice(n,r).join("");if(ne(e,["array"]))return e.slice(n,r);throw new Ve(`Expected first argument to be of type array or string, but found ${Jt(je(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function ln(t,e){const n=t.length-1;let r,i,s=0,o=n,a=0;for(;s<=o;)if(a=Math.floor((s+o)/2),r=t[a],i=t[a+1],r<=e){if(a===n||ee))throw new Ve("Input is not a number.");o=a-1;}return 0}class un{constructor(t,e,n){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of n)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const n=e.parse(t[1],1,Lt);if(!n)return null;const r=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let n=1;n=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const u=e.parse(o,l,i);if(!u)return null;i=i||u.type,r.push([s,u]);}return new un(i,n,r)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;return r>=e[i-1]?n[i-1].evaluate(t):n[ln(e,r)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function cn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var hn,pn,fn=function(){if(pn)return hn;function t(t,e,n,r){this.cx=3*t,this.bx=3*(n-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=n,this.p2y=r;}return pn=1,hn=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var n=t,r=0;r<8;r++){var i=this.sampleCurveX(n)-t;if(Math.abs(i)i?o=n:a=n,n=.5*(a-o)+o;return n},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},hn}(),dn=cn(fn);class yn{constructor(t,e,n,r,i){this.type=t,this.operator=e,this.interpolation=n,this.input=r,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,n,r){let i=0;if("exponential"===t.name)i=mn(e,t.base,n,r);else if("linear"===t.name)i=mn(e,1,n,r);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new dn(s[0],s[1],s[2],s[3]).solve(mn(e,1,n,r));}return i}static parse(t,e){let[n,r,i,...s]=t;if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){const t=r[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:t};}else {if("cubic-bezier"!==r[0])return e.error(`Unknown interpolation type ${String(r[0])}`,1,0);{const t=r.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Lt),!i)return null;const o=[];let a=null;"interpolate-hcl"!==n&&"interpolate-lab"!==n||e.expectedType==Yt?e.expectedType&&"value"!==e.expectedType.kind&&(a=e.expectedType):a=Rt;for(let t=0;t=n)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(r,l,a);if(!u)return null;a=a||u.type,o.push([n,u]);}return re(a,Lt)||re(a,Nt)||re(a,Rt)||re(a,Xt)||re(a,Zt)||re(a,Yt)||re(a,Wt)||re(a,Kt(Lt))?new yn(a,n,r,i,o):e.error(`Type ${Jt(a)} is not interpolatable.`)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;if(r>=e[i-1])return n[i-1].evaluate(t);const s=ln(e,r),o=yn.interpolationFactor(this.interpolation,r,e[s],e[s+1]),a=n[s].evaluate(t),l=n[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return ke(a,l,o);case "color":return Ee.interpolate(a,l,o);case "padding":return ze.interpolate(a,l,o);case "colorArray":return Ce.interpolate(a,l,o);case "numberArray":return Be.interpolate(a,l,o);case "variableAnchorOffsetCollection":return Oe.interpolate(a,l,o);case "array":return Ie(a,l,o);case "projectionDefinition":return Re.interpolate(a,l,o)}case "interpolate-hcl":switch(this.type.kind){case "color":return Ee.interpolate(a,l,o,"hcl");case "colorArray":return Ce.interpolate(a,l,o,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Ee.interpolate(a,l,o,"lab");case "colorArray":return Ce.interpolate(a,l,o,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function mn(t,e,n,r){const i=r-n,s=t-n;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const gn={color:Ee.interpolate,number:ke,padding:ze.interpolate,numberArray:Be.interpolate,colorArray:Ce.interpolate,variableAnchorOffsetCollection:Oe.interpolate,array:Ie};class xn{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n=null;const r=e.expectedType;r&&"value"!==r.kind&&(n=r);const i=[];for(const r of t.slice(1)){const t=e.parse(r,1+i.length,n,void 0,{typeAnnotation:"omit"});if(!t)return null;n=n||t.type,i.push(t);}if(!n)throw new Error("No output type");const s=r&&i.some((t=>te(r,t.type)));return new xn(s?jt:n,i)}evaluate(t){let e,n=null,r=0;for(const i of this.args)if(r++,n=i.evaluate(t),n&&n instanceof $e&&!n.available&&(e||(e=n.name),n=null,r===this.args.length&&(n=e)),null!==n)break;return n}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function vn(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function bn(t,e,n,r){return 0===r.compare(e,n)}function wn(t,e,n){const r="=="!==t&&"!="!==t;return class i{constructor(t,e,n){this.type=$t,this.lhs=t,this.rhs=e,this.collator=n,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const n=t[0];let s=e.parse(t[1],1,jt);if(!s)return null;if(!vn(n,s.type))return e.concat(1).error(`"${n}" comparisons are not supported for type '${Jt(s.type)}'.`);let o=e.parse(t[2],2,jt);if(!o)return null;if(!vn(n,o.type))return e.concat(2).error(`"${n}" comparisons are not supported for type '${Jt(o.type)}'.`);if(s.type.kind!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error(`Cannot compare types '${Jt(s.type)}' and '${Jt(o.type)}'.`);r&&("value"===s.type.kind&&"value"!==o.type.kind?s=new Ye(o.type,[s]):"value"!==s.type.kind&&"value"===o.type.kind&&(o=new Ye(s.type,[o])));let a=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(a=e.parse(t[3],3,qt),!a)return null}return new i(s,o,a)}evaluate(i){const s=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(r&&this.hasUntypedArgument){const e=je(s),n=je(o);if(e.kind!==n.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${n.kind}) instead.`)}if(this.collator&&!r&&this.hasUntypedArgument){const t=je(s),n=je(o);if("string"!==t.kind||"string"!==n.kind)return e(i,s,o)}return this.collator?n(i,s,o,this.collator.evaluate(i)):e(i,s,o)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const _n=wn("==",(function(t,e,n){return e===n}),bn),Sn=wn("!=",(function(t,e,n){return e!==n}),(function(t,e,n,r){return !bn(0,e,n,r)})),An=wn("<",(function(t,e,n){return e",(function(t,e,n){return e>n}),(function(t,e,n,r){return r.compare(e,n)>0})),kn=wn("<=",(function(t,e,n){return e<=n}),(function(t,e,n,r){return r.compare(e,n)<=0})),In=wn(">=",(function(t,e,n){return e>=n}),(function(t,e,n,r){return r.compare(e,n)>=0}));class En{constructor(t,e,n){this.type=qt,this.locale=n,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const n=t[1];if("object"!=typeof n||Array.isArray(n))return e.error("Collator options argument must be an object.");const r=e.parse(void 0!==n["case-sensitive"]&&n["case-sensitive"],1,$t);if(!r)return null;const i=e.parse(void 0!==n["diacritic-sensitive"]&&n["diacritic-sensitive"],1,$t);if(!i)return null;let s=null;return n.locale&&(s=e.parse(n.locale,1,Ot),!s)?null:new En(r,i,s)}evaluate(t){return new Te(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Tn{constructor(t,e,n,r,i,s){this.type=Ot,this.number=t,this.locale=e,this.currency=n,this.unit=r,this.minFractionDigits=i,this.maxFractionDigits=s;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,Lt);if(!n)return null;const r=t[2];if("object"!=typeof r||Array.isArray(r))return e.error("NumberFormat options argument must be an object.");let i=null;if(r.locale&&(i=e.parse(r.locale,1,Ot),!i))return null;let s=null;if(r.currency&&(s=e.parse(r.currency,1,Ot),!s))return null;let o=null;if(r.unit&&(o=e.parse(r.unit,1,Ot),!o))return null;if(s&&o)return e.error("NumberFormat options `currency` and `unit` are mutually exclusive");let a=null;if(r["min-fraction-digits"]&&(a=e.parse(r["min-fraction-digits"],1,Lt),!a))return null;let l=null;return r["max-fraction-digits"]&&(l=e.parse(r["max-fraction-digits"],1,Lt),!l)?null:new Tn(n,i,s,o,a,l)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":this.unit?"unit":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,unit:this.unit?this.unit.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.unit&&t(this.unit),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Fn{constructor(t){this.type=Gt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[1];if(!Array.isArray(n)&&"object"==typeof n)return e.error("First argument must be an image or text section.");const r=[];let i=!1;for(let n=1;n<=t.length-1;++n){const s=t[n];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Lt),!t))return null;let n=null;if(s["text-font"]&&(n=e.parse(s["text-font"],1,Kt(Ot)),!n))return null;let o=null;if(s["text-color"]&&(o=e.parse(s["text-color"],1,Rt),!o))return null;let a=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!Fe.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(a=e.parse(s["vertical-align"],1,Ot),!a)return null}const l=r[r.length-1];l.scale=t,l.font=n,l.textColor=o,l.verticalAlign=a;}else {const s=e.parse(t[n],1,jt);if(!s)return null;const o=s.type.kind;if("string"!==o&&"value"!==o&&"null"!==o&&"resolvedImage"!==o)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,r.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Fn(r)}evaluate(t){return new De(this.sections.map((e=>{const n=e.content.evaluate(t);return je(n)===Ht?new Pe("",n,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(qe(n),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class Pn{constructor(t){this.type=Ht,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,Ot);return n?new Pn(n):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),n=$e.fromString(e);return n&&t.availableImages&&(n.available=t.availableImages.indexOf(e)>-1),n}eachChild(t){t(this.input);}outputDefined(){return !1}}class Dn{constructor(t){this.type=Lt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=e.parse(t[1],1);return n?"array"!==n.type.kind&&"string"!==n.type.kind&&"value"!==n.type.kind?e.error(`Expected argument of type string or array, but found ${Jt(n.type)} instead.`):new Dn(n):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Jt(je(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const zn=8192;function Bn(t,e){const n=(180+t[0])/360,r=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(n*i*zn),Math.round(r*i*zn)]}function Cn(t,e){const n=Math.pow(2,e.z);return [(i=(t[0]/zn+e.x)/n,360*i-180),(r=(t[1]/zn+e.y)/n,360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90)];var r,i;}function Vn(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Ln(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function On(t,e,n){const r=t[0]-e[0],i=t[1]-e[1],s=t[0]-n[0],o=t[1]-n[1];return r*o-s*i==0&&r*s<=0&&i*o<=0}function $n(t,e,n,r){return 0!=(i=[r[0]-n[0],r[1]-n[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!Gn(t,e,n,r)||!Gn(n,r,t,e));var i,s;}function Rn(t,e,n){for(const r of n)for(let n=0;n(i=t)[1]!=(o=a[e+1])[1]>i[1]&&i[0]<(o[0]-s[0])*(i[1]-s[1])/(o[1]-s[1])+s[0]&&(r=!r);}var i,s,o;return r}function Un(t,e){for(const n of e)if(Nn(t,n))return !0;return !1}function jn(t,e){for(const n of t)if(!Nn(n,e))return !1;for(let n=0;n0&&a<0||o<0&&a>0}function Xn(t,e,n){const r=[];for(let i=0;in[2]){const e=.5*r;let i=t[0]-n[0]>e?-r:n[0]-t[0]>e?r:0;0===i&&(i=t[0]-n[2]>e?-r:n[2]-t[0]>e?r:0),t[0]+=i;}Vn(e,t);}function Hn(t,e,n,r){const i=Math.pow(2,r.z)*zn,s=[r.x*zn,r.y*zn],o=[];for(const r of t)for(const t of r){const r=[t.x+s[0],t.y+s[1]];Zn(r,e,n,i),o.push(r);}return o}function Wn(t,e,n,r){const i=Math.pow(2,r.z)*zn,s=[r.x*zn,r.y*zn],o=[];for(const n of t){const t=[];for(const r of n){const n=[r.x+s[0],r.y+s[1]];Vn(e,n),t.push(n);}o.push(t);}if(e[2]-e[0]<=i/2){(a=e)[0]=a[1]=1/0,a[2]=a[3]=-1/0;for(const t of o)for(const r of t)Zn(r,e,n,i);}var a;return o}class Kn{constructor(t,e){this.type=$t,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const n of e.features){const{type:e,coordinates:r}=n.geometry;"Polygon"===e&&t.push(r),"MultiPolygon"===e&&t.push(...r);}if(t.length)return new Kn(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Kn(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Kn(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Xn(e.coordinates,r,i),o=Hn(t.geometry(),n,r,i);if(!Ln(n,r))return !1;for(const t of o)if(!Nn(t,s))return !1}if("MultiPolygon"===e.type){const s=Yn(e.coordinates,r,i),o=Hn(t.geometry(),n,r,i);if(!Ln(n,r))return !1;for(const t of o)if(!Un(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Xn(e.coordinates,r,i),o=Wn(t.geometry(),n,r,i);if(!Ln(n,r))return !1;for(const t of o)if(!jn(t,s))return !1}if("MultiPolygon"===e.type){const s=Yn(e.coordinates,r,i),o=Wn(t.geometry(),n,r,i);if(!Ln(n,r))return !1;for(const t of o)if(!qn(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Jn=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:n}=this,r=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(n(r,s)>=0)break;e[t]=s,t=i;}e[t]=r;}_down(t){const{data:e,compare:n}=this,r=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[r],t=r;}e[t]=i;}};function Qn(t,e,n=0,r=t.length-1,i=er){for(;r>n;){if(r-n>600){const s=r-n+1,o=e-n+1,a=Math.log(s),l=.5*Math.exp(2*a/3),u=.5*Math.sqrt(a*l*(s-l)/s)*(o-s/2<0?-1:1);Qn(t,e,Math.max(n,Math.floor(e-o*l/s+u)),Math.min(r,Math.floor(e+(s-o)*l/s+u)),i);}const s=t[e];let o=n,a=r;for(tr(t,n,e),i(t[r],s)>0&&tr(t,n,r);o0;)a--;}0===i(t[n],s)?tr(t,n,a):(a++,tr(t,a,r)),a<=e&&(n=a+1),e<=a&&(r=a-1);}}function tr(t,e,n){const r=t[e];t[e]=t[n],t[n]=r;}function er(t,e){return te?1:0}function nr(t,e){if(t.length<=1)return [t];const n=[];let r,i;for(const e of t){const t=ir(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(r&&n.push(r),r=[e]):r.push(e));}if(r&&n.push(r),e>1)for(let t=0;t1?(l=t[a+1][0],u=t[a+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function ur(t,e){return e[0]-t[0]}function cr(t){return t[1]-t[0]+1}function hr(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const n=cr(t);if(e){if(2===n)return [t,null];const e=Math.floor(n/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===n)return [t,null];const r=Math.floor(n/2)-1;return [[t[0],t[0]+r],[t[0]+r+1,t[1]]]}function fr(t,e){if(!hr(e,t.length))return [1/0,1/0,-1/0,-1/0];const n=[1/0,1/0,-1/0,-1/0];for(let r=e[0];r<=e[1];++r)Vn(n,t[r]);return n}function dr(t){const e=[1/0,1/0,-1/0,-1/0];for(const n of t)for(const t of n)Vn(e,t);return e}function yr(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function mr(t,e,n){if(!yr(t)||!yr(e))return NaN;let r=0,i=0;return t[2]e[2]&&(r=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=r)return r;if(Ln(i,s)){if(Sr(t,e))return 0}else if(Sr(e,t))return 0;let o=1/0;for(const r of t)for(let t=0,i=r.length,s=i-1;t0;){const i=o.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(cr(l)<=u){if(!hr(l,t.length))return NaN;if(e){const e=_r(t,l,n,r);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=wr(t[e],n,r);if(s=Math.min(s,i),0===s)return 0}}else {const n=pr(l,e);Mr(o,s,r,t,a,n[0]),Mr(o,s,r,t,a,n[1]);}}return s}function Er(t,e,n,r,i,s=1/0){let o=Math.min(s,i.distance(t[0],n[0]));if(0===o)return o;const a=new Jn([[0,[0,t.length-1],[0,n.length-1]]],ur);for(;a.length>0;){const s=a.pop();if(s[0]>=o)continue;const l=s[1],u=s[2],c=e?50:100,h=r?50:100;if(cr(l)<=c&&cr(u)<=h){if(!hr(l,t.length)&&hr(u,n.length))return NaN;let s;if(e&&r)s=vr(t,l,n,u,i),o=Math.min(o,s);else if(e&&!r){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=gr(n[t],e,i),o=Math.min(o,s),0===o)return o}else if(!e&&r){const e=n.slice(u[0],u[1]+1);for(let n=l[0];n<=l[1];++n)if(s=gr(t[n],e,i),o=Math.min(o,s),0===o)return o}else s=br(t,l,n,u,i),o=Math.min(o,s);}else {const s=pr(l,e),c=pr(u,r);kr(a,o,i,t,n,s[0],c[0]),kr(a,o,i,t,n,s[0],c[1]),kr(a,o,i,t,n,s[1],c[0]),kr(a,o,i,t,n,s[1],c[1]);}}return o}function Tr(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class Fr{constructor(t,e){this.type=Lt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new Fr(e,e.features.map((t=>Tr(t.geometry))).flat());if("Feature"===e.type)return new Fr(e,Tr(e.geometry));if("type"in e&&"coordinates"in e)return new Fr(e,Tr(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map((e=>Cn([e.x,e.y],t.canonical)));if(0===n.length)return NaN;const i=new lr(r[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Er(r,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Er(r,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,Ir(r,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map((e=>Cn([e.x,e.y],t.canonical)));if(0===n.length)return NaN;const i=new lr(r[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Er(r,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Er(r,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,Ir(r,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const n=t.geometry();if(0===n.length||0===n[0].length)return NaN;const r=nr(n,0).map((e=>e.map((e=>e.map((e=>Cn([e.x,e.y],t.canonical))))))),i=new lr(r[0][0][0][1]);let s=1/0;for(const t of e)for(const e of r){switch(t.type){case "Point":s=Math.min(s,Ir([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,Ir(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,Ar(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pr{constructor(t){this.type=jt,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=t[1];return null==n?e.error("Global state property must be defined."):"string"!=typeof n?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pr(n)}evaluate(t){var e;const n=null===(e=t.globals)||void 0===e?void 0:e.globalState;return n&&0!==Object.keys(n).length?be(n,this.key):null}eachChild(){}outputDefined(){return !1}}const Dr={"==":_n,"!=":Sn,">":Mn,"<":An,">=":In,"<=":kn,array:Ye,at:en,boolean:Ye,case:on,coalesce:xn,collator:En,format:Fn,image:Pn,in:nn,"index-of":rn,interpolate:yn,"interpolate-hcl":yn,"interpolate-lab":yn,length:Dn,let:Qe,literal:Ge,match:sn,number:Ye,"number-format":Tn,object:Ye,slice:an,step:un,string:Ye,"to-boolean":He,"to-color":He,"to-number":He,"to-string":He,var:tn,within:Kn,distance:Fr,"global-state":Pr};class zr{constructor(t,e,n,r){this.name=t,this.type=e,this._evaluate=n,this.args=r;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const n=t[0],r=zr.definitions[n];if(!r)return e.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(r)?r[0]:r.type,s=Array.isArray(r)?[[r[1],r[2]]]:r.overloads,o=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let a=null;for(const[r,s]of o){a=new Je(e.registry,Or,e.path,null,e.scope);const o=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Jt).join(", ")})`:`(${Jt(e.type)}...)`;var e;})).join(" | "),r=[];for(let n=1;n{n=e?n&&Or(t):n&&t instanceof Ge;})),!!n&&$r(t)&&Nr(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function $r(t){if(t instanceof zr){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Kn)return !1;if(t instanceof Fr)return !1;let e=!0;return t.eachChild((t=>{e&&!$r(t)&&(e=!1);})),e}function Rr(t){if(t instanceof zr&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Rr(t)&&(e=!1);})),e}function Nr(t,e){if(t instanceof zr&&e.indexOf(t.name)>=0)return !1;let n=!0;return t.eachChild((t=>{n&&!Nr(t,e)&&(n=!1);})),n}function Ur(t){return {result:"success",value:t}}function jr(t){return {result:"error",value:t}}function qr(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Gr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Xr(t){return !!t.expression&&t.expression.interpolated}function Yr(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Zr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&je(t)===Ut}function Hr(t){return t}function Wr(t,e){const n=t.stops&&"object"==typeof t.stops[0][0],r=n||!(n||void 0!==t.property),i=t.type||(Xr(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Ee.parse;case "padding":return ze.parse;case "numberArray":return Be.parse;case "colorArray":return Ce.parse;default:return null}}(e);if(s&&((t=zt({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(o=t.colorSpace)&&"hcl"!==o&&"lab"!==o)throw new Error(`Unknown color space: "${t.colorSpace}"`);var o;const a=function(t){switch(t){case "exponential":return ti;case "interval":return Qr;case "categorical":return Jr;case "identity":return ei;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(n){const n={},r=[];for(let e=0;et[0])),evaluate:({zoom:n},r)=>ti({stops:i,base:t.base},e,n).evaluate(n,r)}}if(r){const n="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:n,interpolationFactor:yn.interpolationFactor.bind(void 0,n),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:n})=>a(t,e,n,l,u)}}return {kind:"source",evaluate(n,r){const i=r&&r.properties?r.properties[t.property]:void 0;return void 0===i?Kr(t.default,e.default):a(t,e,i,l,u)}}}function Kr(t,e,n){return void 0!==t?t:void 0!==e?e:void 0!==n?n:void 0}function Jr(t,e,n,r,i){return Kr(typeof n===i?r[n]:void 0,t.default,e.default)}function Qr(t,e,n){if("number"!==Yr(n))return Kr(t.default,e.default);const r=t.stops.length;if(1===r)return t.stops[0][1];if(n<=t.stops[0][0])return t.stops[0][1];if(n>=t.stops[r-1][0])return t.stops[r-1][1];const i=ln(t.stops.map((t=>t[0])),n);return t.stops[i][1]}function ti(t,e,n){const r=void 0!==t.base?t.base:1;if("number"!==Yr(n))return Kr(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(n<=t.stops[0][0])return t.stops[0][1];if(n>=t.stops[i-1][0])return t.stops[i-1][1];const s=ln(t.stops.map((t=>t[0])),n),o=function(t,e,n,r){const i=r-n,s=t-n;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(n,r,t.stops[s][0],t.stops[s+1][0]),a=t.stops[s][1],l=t.stops[s+1][1],u=gn[e.type]||Hr;return "function"==typeof a.evaluate?{evaluate(...e){const n=a.evaluate.apply(void 0,e),r=l.evaluate.apply(void 0,e);if(void 0!==n&&void 0!==r)return u(n,r,o,t.colorSpace)}}:u(a,l,o,t.colorSpace)}function ei(t,e,n){switch(e.type){case "color":n=Ee.parse(n);break;case "formatted":n=De.fromString(n.toString());break;case "resolvedImage":n=$e.fromString(n.toString());break;case "padding":n=ze.parse(n);break;case "colorArray":n=Ce.parse(n);break;case "numberArray":n=Be.parse(n);break;default:Yr(n)===e.type||"enum"===e.type&&e.values[n]||(n=void 0);}return Kr(n,t.default,e.default)}zr.register(Dr,{error:[{kind:"error"},[Ot],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[Ot,[jt],(t,[e])=>Jt(je(e.evaluate(t)))],"to-rgba":[Kt(Lt,4),[Rt],(t,[e])=>{const[n,r,i,s]=e.evaluate(t).rgb;return [255*n,255*r,255*i,s]}],rgb:[Rt,[Lt,Lt,Lt],Br],rgba:[Rt,[Lt,Lt,Lt,Lt],Br],has:{type:$t,overloads:[[[Ot],(t,[e])=>Cr(e.evaluate(t),t.properties())],[[Ot,Ut],(t,[e,n])=>Cr(e.evaluate(t),n.evaluate(t))]]},get:{type:jt,overloads:[[[Ot],(t,[e])=>Vr(e.evaluate(t),t.properties())],[[Ot,Ut],(t,[e,n])=>Vr(e.evaluate(t),n.evaluate(t))]]},"feature-state":[jt,[Ot],(t,[e])=>Vr(e.evaluate(t),t.featureState||{})],properties:[Ut,[],t=>t.properties()],"geometry-type":[Ot,[],t=>t.geometryType()],id:[jt,[],t=>t.id()],zoom:[Lt,[],t=>t.globals.zoom],"heatmap-density":[Lt,[],t=>t.globals.heatmapDensity||0],elevation:[Lt,[],t=>t.globals.elevation||0],"line-progress":[Lt,[],t=>t.globals.lineProgress||0],accumulated:[jt,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Lt,Lr(Lt),(t,e)=>{let n=0;for(const r of e)n+=r.evaluate(t);return n}],"*":[Lt,Lr(Lt),(t,e)=>{let n=1;for(const r of e)n*=r.evaluate(t);return n}],"-":{type:Lt,overloads:[[[Lt,Lt],(t,[e,n])=>e.evaluate(t)-n.evaluate(t)],[[Lt],(t,[e])=>-e.evaluate(t)]]},"/":[Lt,[Lt,Lt],(t,[e,n])=>e.evaluate(t)/n.evaluate(t)],"%":[Lt,[Lt,Lt],(t,[e,n])=>e.evaluate(t)%n.evaluate(t)],ln2:[Lt,[],()=>Math.LN2],pi:[Lt,[],()=>Math.PI],e:[Lt,[],()=>Math.E],"^":[Lt,[Lt,Lt],(t,[e,n])=>Math.pow(e.evaluate(t),n.evaluate(t))],sqrt:[Lt,[Lt],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Lt,[Lt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Lt,[Lt],(t,[e])=>Math.log(e.evaluate(t))],log2:[Lt,[Lt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Lt,[Lt],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Lt,[Lt],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Lt,[Lt],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Lt,[Lt],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Lt,[Lt],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Lt,[Lt],(t,[e])=>Math.atan(e.evaluate(t))],min:[Lt,Lr(Lt),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Lt,Lr(Lt),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Lt,[Lt],(t,[e])=>Math.abs(e.evaluate(t))],round:[Lt,[Lt],(t,[e])=>{const n=e.evaluate(t);return n<0?-Math.round(-n):Math.round(n)}],floor:[Lt,[Lt],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Lt,[Lt],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[$t,[Ot,jt],(t,[e,n])=>t.properties()[e.value]===n.value],"filter-id-==":[$t,[jt],(t,[e])=>t.id()===e.value],"filter-type-==":[$t,[Ot],(t,[e])=>t.geometryType()===e.value],"filter-<":[$t,[Ot,jt],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r{const n=t.id(),r=e.value;return typeof n==typeof r&&n":[$t,[Ot,jt],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>i}],"filter-id->":[$t,[jt],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>r}],"filter-<=":[$t,[Ot,jt],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r<=i}],"filter-id-<=":[$t,[jt],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n<=r}],"filter->=":[$t,[Ot,jt],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>=i}],"filter-id->=":[$t,[jt],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>=r}],"filter-has":[$t,[jt],(t,[e])=>e.value in t.properties()],"filter-has-id":[$t,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[$t,[Kt(Ot)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[$t,[Kt(jt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[$t,[Ot,Kt(jt)],(t,[e,n])=>n.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[$t,[Ot,Kt(jt)],(t,[e,n])=>function(t,e,n,r){for(;n<=r;){const i=n+r>>1;if(e[i]===t)return !0;e[i]>t?r=i-1:n=i+1;}return !1}(t.properties()[e.value],n.value,0,n.value.length-1)],all:{type:$t,overloads:[[[$t,$t],(t,[e,n])=>e.evaluate(t)&&n.evaluate(t)],[Lr($t),(t,e)=>{for(const n of e)if(!n.evaluate(t))return !1;return !0}]]},any:{type:$t,overloads:[[[$t,$t],(t,[e,n])=>e.evaluate(t)||n.evaluate(t)],[Lr($t),(t,e)=>{for(const n of e)if(n.evaluate(t))return !0;return !1}]]},"!":[$t,[$t],(t,[e])=>!e.evaluate(t)],"is-supported-script":[$t,[Ot],(t,[e])=>{const n=t.globals&&t.globals.isSupportedScript;return !n||n(e.evaluate(t))}],upcase:[Ot,[Ot],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[Ot,[Ot],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[Ot,Lr(jt),(t,e)=>e.map((e=>qe(e.evaluate(t)))).join("")],split:[Kt(Ot),[Ot,Ot],(t,[e,n])=>e.evaluate(t).split(n.evaluate(t))],join:[Ot,[Kt(Ot),Ot],(t,[e,n])=>e.evaluate(t).join(n.evaluate(t))],"resolved-locale":[Ot,[qt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ni{constructor(t,e,n){this.expression=t,this._warningHistory={},this._evaluator=new Ke,this._defaultValue=e?function(t){if("color"===t.type&&Zr(t.default))return new Ee(0,0,0,0);switch(t.type){case "color":return Ee.parse(t.default)||null;case "padding":return ze.parse(t.default)||null;case "numberArray":return Be.parse(t.default)||null;case "colorArray":return Ce.parse(t.default)||null;case "variableAnchorOffsetCollection":return Oe.parse(t.default)||null;case "projectionDefinition":return Re.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=n;}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._globalState&&(t=hi(t,this._globalState)),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=n,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,n,r,i,s){this._globalState&&(t=hi(t,this._globalState)),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=n||null,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ri(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Dr}function ii(t,e,n){const r=new Je(Dr,Or,[],e?function(t){const e={color:Rt,string:Ot,number:Lt,enum:Ot,boolean:$t,formatted:Gt,padding:Xt,numberArray:Zt,colorArray:Yt,projectionDefinition:Nt,resolvedImage:Ht,variableAnchorOffsetCollection:Wt};return "array"===t.type?Kt(e[t.value]||jt,t.length):e[t.type]}(e):void 0),i=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Ur(new ni(i,e,n)):jr(r.errors)}class si{constructor(t,e,n){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Rr(e.expression),this.globalStateRefs=ci(e.expression),this._globalState=n;}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._globalState&&(t=hi(t,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._globalState&&(t=hi(t,this._globalState)),this._styleExpression.evaluate(t,e,n,r,i,s)}}class oi{constructor(t,e,n,r,i){this.kind=t,this.zoomStops=n,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Rr(e.expression),this.globalStateRefs=ci(e.expression),this.interpolationType=r,this._globalState=i;}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._globalState&&(t=hi(t,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._globalState&&(t=hi(t,this._globalState)),this._styleExpression.evaluate(t,e,n,r,i,s)}interpolationFactor(t,e,n){return this.interpolationType?yn.interpolationFactor(this.interpolationType,t,e,n):0}}function ai(t,e,n){const r=ii(t,e,n);if("error"===r.result)return r;const i=r.value.expression,s=$r(i);if(!s&&!qr(e))return jr([new Bt("","data expressions not supported")]);const o=Nr(i,["zoom"]);if(!o&&!Gr(e))return jr([new Bt("","zoom expressions not supported")]);const a=ui(i);return a||o?a instanceof Bt?jr([a]):a instanceof yn&&!Xr(e)?jr([new Bt("",'"interpolate" expressions cannot be used with this property')]):Ur(a?new oi(s?"camera":"composite",r.value,a.labels,a instanceof yn?a.interpolation:void 0,n):new si(s?"constant":"source",r.value,n)):jr([new Bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class li{constructor(t,e){this._parameters=t,this._specification=e,zt(this,Wr(this._parameters,this._specification));}static deserialize(t){return new li(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function ui(t){let e=null;if(t instanceof Qe)e=ui(t.result);else if(t instanceof xn){for(const n of t.args)if(e=ui(n),e)break}else (t instanceof un||t instanceof yn)&&t.input instanceof zr&&"zoom"===t.input.name&&(e=t);return e instanceof Bt||t.eachChild((t=>{const n=ui(t);n instanceof Bt?e=n:!e&&n?e=new Bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&n&&e!==n&&(e=new Bt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function ci(t,e=new Set){return t instanceof Pr&&e.add(t.key),t.eachChild((t=>{ci(t,e);})),e}function hi(t,e){const{zoom:n,heatmapDensity:r,elevation:i,lineProgress:s,isSupportedScript:o,accumulated:a}=null!=t?t:{};return {zoom:n,heatmapDensity:r,elevation:i,lineProgress:s,isSupportedScript:o,accumulated:a,globalState:e}}function pi(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!pi(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const fi={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function di(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};pi(t)||(t=gi(t));const n=ii(t,fi,e);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,r)=>n.value.evaluate(t,e,{},r),needGeometry:mi(t),getGlobalStateRefs:()=>ci(n.value.expression)}}function yi(t,e){return te?1:0}function mi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?xi(t[1],t[2],e):"any"===e?(n=t.slice(1),["any"].concat(n.map(gi))):"all"===e?["all"].concat(t.slice(1).map(gi)):"none"===e?["all"].concat(t.slice(1).map(gi).map(wi)):"in"===e?vi(t[1],t.slice(2)):"!in"===e?wi(vi(t[1],t.slice(2))):"has"===e?bi(t[1]):"!has"!==e||wi(bi(t[1]));var n;}function xi(t,e,n){switch(t){case "$type":return [`filter-type-${n}`,e];case "$id":return [`filter-id-${n}`,e];default:return [`filter-${n}`,t,e]}}function vi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(yi)]]:["filter-in-small",t,["literal",e]]}}function bi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function wi(t){return ["!",t]}function _i(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const n of t)e+=`${_i(n)},`;return `${e}]`}const n=Object.keys(t).sort();let r="{";for(let e=0;er.maximum?[new Dt(e,n,`${n} is greater than the maximum value ${r.maximum}`)]:[]}function Fi(t){const e=t.valueSpec,n=Mi(t.value.type);let r,i,s,o={};const a="categorical"!==n&&void 0===t.value.property,l=!a,u="array"===Yr(t.value.stops)&&"array"===Yr(t.value.stops[0])&&"object"===Yr(t.value.stops[0][0]),c=Ii({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===n)return [new Dt(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const r=t.value;return e=e.concat(Ei({key:t.key,value:r,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Yr(r)&&0===r.length&&e.push(new Dt(t.key,r,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===n&&a&&c.push(new Dt(t.key,t.value,'missing required property "property"')),"identity"===n||t.value.stops||c.push(new Dt(t.key,t.value,'missing required property "stops"')),"exponential"===n&&t.valueSpec.expression&&!Xr(t.valueSpec)&&c.push(new Dt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!qr(t.valueSpec)?c.push(new Dt(t.key,t.value,"property functions not supported")):a&&!Gr(t.valueSpec)&&c.push(new Dt(t.key,t.value,"zoom functions not supported"))),"categorical"!==n&&!u||void 0!==t.value.property||c.push(new Dt(t.key,t.value,'"property" property is required')),c;function h(t){let n=[];const r=t.value,a=t.key;if("array"!==Yr(r))return [new Dt(a,r,`array expected, ${Yr(r)} found`)];if(2!==r.length)return [new Dt(a,r,`array length 2 expected, length ${r.length} found`)];if(u){if("object"!==Yr(r[0]))return [new Dt(a,r,`object expected, ${Yr(r[0])} found`)];if(void 0===r[0].zoom)return [new Dt(a,r,"object stop key must have zoom")];if(void 0===r[0].value)return [new Dt(a,r,"object stop key must have value")];if(s&&s>Mi(r[0].zoom))return [new Dt(a,r[0].zoom,"stop zoom values must appear in ascending order")];Mi(r[0].zoom)!==s&&(s=Mi(r[0].zoom),i=void 0,o={}),n=n.concat(Ii({key:`${a}[0]`,value:r[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Ti,value:p}}));}else n=n.concat(p({key:`${a}[0]`,value:r[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},r));return ri(ki(r[1]))?n.concat([new Dt(`${a}[1]`,r[1],"expressions are not allowed in function stops.")]):n.concat(t.validateSpec({key:`${a}[1]`,value:r[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const a=Yr(t.value),l=Mi(t.value),u=null!==t.value?t.value:s;if(r){if(a!==r)return [new Dt(t.key,u,`${a} stop domain type must match previous stop domain type ${r}`)]}else r=a;if("number"!==a&&"string"!==a&&"boolean"!==a)return [new Dt(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==a&&"categorical"!==n){let r=`number expected, ${a} found`;return qr(e)&&void 0===n&&(r+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Dt(t.key,u,r)]}return "categorical"!==n||"number"!==a||isFinite(l)&&Math.floor(l)===l?"categorical"!==n&&"number"===a&&void 0!==i&&lnew Dt(`${t.key}${e.key}`,t.value,e.message)));const n=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!n.outputDefined())return [new Dt(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Rr(n))return [new Dt(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Rr(n))return [new Dt(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!Nr(n,["zoom","feature-state"]))return [new Dt(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!$r(n))return [new Dt(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Di(t){const e=t.key,n=t.value,r=Yr(n);return "string"!==r?[new Dt(e,n,`color expected, ${r} found`)]:Ee.parse(String(n))?[]:[new Dt(e,n,`color expected, "${n}" found`)]}function zi(t){const e=t.key,n=t.value,r=t.valueSpec,i=[];return Array.isArray(r.values)?-1===r.values.indexOf(Mi(n))&&i.push(new Dt(e,n,`expected one of [${r.values.join(", ")}], ${JSON.stringify(n)} found`)):-1===Object.keys(r.values).indexOf(Mi(n))&&i.push(new Dt(e,n,`expected one of [${Object.keys(r.values).join(", ")}], ${JSON.stringify(n)} found`)),i}function Bi(t){return pi(ki(t.value))?Pi(zt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ci(t)}function Ci(t){const e=t.value,n=t.key;if("array"!==Yr(e))return [new Dt(n,e,`array expected, ${Yr(e)} found`)];const r=t.styleSpec;let i,s=[];if(e.length<1)return [new Dt(n,e,"filter array must have at least 1 element")];switch(s=s.concat(zi({key:`${n}[0]`,value:e[0],valueSpec:r.filter_operator,style:t.style,styleSpec:t.styleSpec})),Mi(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===Mi(e[1])&&s.push(new Dt(n,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Dt(n,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Yr(e[1]),"string"!==i&&s.push(new Dt(`${n}[1]`,e[1],`string expected, ${i} found`)));for(let o=2;o{t in i&&r.push(new Dt(s,i[t],`"${t}" is prohibited for ref layers`));})),o.layers.forEach((e=>{Mi(e.id)===u&&(t=e);})),t?t.ref?r.push(new Dt(s,i.ref,"ref cannot reference another ref layer")):l=Mi(t.type):r.push(new Dt(s,i.ref,`ref layer "${u}" not found`));}else if("background"!==l)if(i.source){const t=o.sources&&o.sources[i.source],e=t&&Mi(t.type);t?"vector"===e&&"raster"===l?r.push(new Dt(s,i.source,`layer "${i.id}" requires a raster source`)):"raster-dem"!==e&&"hillshade"===l||"raster-dem"!==e&&"color-relief"===l?r.push(new Dt(s,i.source,`layer "${i.id}" requires a raster-dem source`)):"raster"===e&&"raster"!==l?r.push(new Dt(s,i.source,`layer "${i.id}" requires a vector source`)):"vector"!==e||i["source-layer"]?"raster-dem"===e&&"hillshade"!==l&&"color-relief"!==l?r.push(new Dt(s,i.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==l||!i.paint||!i.paint["line-gradient"]||"geojson"===e&&t.lineMetrics||r.push(new Dt(s,i,`layer "${i.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):r.push(new Dt(s,i,`layer "${i.id}" must specify a "source-layer"`)):r.push(new Dt(s,i.source,`source "${i.source}" not found`));}else r.push(new Dt(s,i,'missing required property "source"'));return "raster"===l&&(null===(e=i.paint)||void 0===e?void 0:e.resampling)&&(null===(n=i.paint)||void 0===n?void 0:n["raster-resampling"])&&r.push(new Dt(s,i.paint,`layer "${i.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`)),r=r.concat(Ii({key:s,value:i,valueSpec:a.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${s}.type`,value:i.type,valueSpec:a.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:i,objectKey:"type"}),filter:Bi,layout:t=>Ii({layer:i,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Oi(zt({layerType:l},t))}}),paint:t=>Ii({layer:i,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Li(zt({layerType:l},t))}})}})),r}function Ri(t){const e=t.value,n=t.key,r=Yr(e);return "string"!==r?[new Dt(n,e,`string expected, ${r} found`)]:[]}const Ni={promoteId:function({key:t,value:e}){if("string"===Yr(e))return Ri({key:t,value:e});{const n=[];for(const r in e)n.push(...Ri({key:`${t}.${r}`,value:e[r]}));return n}}};function Ui(t){const e=t.value,n=t.key,r=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Dt(n,e,'"type" is required')];const o=Mi(e.type);let a;switch(o){case "vector":case "raster":return a=Ii({key:n,value:e,valueSpec:r[`source_${o.replace("-","_")}`],style:t.style,styleSpec:r,objectElementValidators:Ni,validateSpec:s}),a;case "raster-dem":return a=function(t){var e;const n=null!==(e=t.sourceName)&&void 0!==e?e:"",r=t.value,i=t.styleSpec,s=i.source_raster_dem,o=t.style;let a=[];const l=Yr(r);if(void 0===r)return a;if("object"!==l)return a.push(new Dt("source_raster_dem",r,`object expected, ${l} found`)),a;const u="custom"===Mi(r.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in r)!u&&c.includes(e)?a.push(new Dt(e,r[e],`In "${n}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?a=a.concat(t.validateSpec({key:e,value:r[e],valueSpec:s[e],validateSpec:t.validateSpec,style:o,styleSpec:i})):a.push(new Dt(e,r[e],`unknown property "${e}"`));return a}({sourceName:n,value:e,style:t.style,styleSpec:r,validateSpec:s}),a;case "geojson":if(a=Ii({key:n,value:e,valueSpec:r.source_geojson,style:i,styleSpec:r,validateSpec:s,objectElementValidators:Ni}),e.cluster)for(const t in e.clusterProperties){const[r,i]=e.clusterProperties[t],s="string"==typeof r?[r,["accumulated"],["get",t]]:r;a.push(...Pi({key:`${n}.${t}.map`,value:i,expressionContext:"cluster-map"})),a.push(...Pi({key:`${n}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return a;case "video":return Ii({key:n,value:e,valueSpec:r.source_video,style:i,validateSpec:s,styleSpec:r});case "image":return Ii({key:n,value:e,valueSpec:r.source_image,style:i,validateSpec:s,styleSpec:r});case "canvas":return [new Dt(n,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return zi({key:`${n}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function ji(t){const e=t.value,n=t.styleSpec,r=n.light,i=t.style;let s=[];const o=Yr(e);if(void 0===e)return s;if("object"!==o)return s=s.concat([new Dt("light",e,`object expected, ${o} found`)]),s;for(const o in e){const a=o.match(/^(.*)-transition$/);s=s.concat(a&&r[a[1]]&&r[a[1]].transition?t.validateSpec({key:o,value:e[o],valueSpec:n.transition,validateSpec:t.validateSpec,style:i,styleSpec:n}):r[o]?t.validateSpec({key:o,value:e[o],valueSpec:r[o],validateSpec:t.validateSpec,style:i,styleSpec:n}):[new Dt(o,e[o],`unknown property "${o}"`)]);}return s}function qi(t){const e=t.value,n=t.styleSpec,r=n.sky,i=t.style,s=Yr(e);if(void 0===e)return [];if("object"!==s)return [new Dt("sky",e,`object expected, ${s} found`)];let o=[];for(const s in e)o=o.concat(r[s]?t.validateSpec({key:s,value:e[s],valueSpec:r[s],style:i,styleSpec:n}):[new Dt(s,e[s],`unknown property "${s}"`)]);return o}function Gi(t){const e=t.value,n=t.styleSpec,r=n.terrain,i=t.style;let s=[];const o=Yr(e);if(void 0===e)return s;if("object"!==o)return s=s.concat([new Dt("terrain",e,`object expected, ${o} found`)]),s;for(const o in e)s=s.concat(r[o]?t.validateSpec({key:o,value:e[o],valueSpec:r[o],validateSpec:t.validateSpec,style:i,styleSpec:n}):[new Dt(o,e[o],`unknown property "${o}"`)]);return s}function Xi(t){let e=[];const n=t.value,r=t.key;if(Array.isArray(n)){const i=[],s=[];for(const o in n)n[o].id&&i.includes(n[o].id)&&e.push(new Dt(r,n,`all the sprites' ids must be unique, but ${n[o].id} is duplicated`)),i.push(n[o].id),n[o].url&&s.includes(n[o].url)&&e.push(new Dt(r,n,`all the sprites' URLs must be unique, but ${n[o].url} is duplicated`)),s.push(n[o].url),e=e.concat(Ii({key:`${r}[${o}]`,value:n[o],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Ri({key:r,value:n})}function Yi(t){return Boolean(t)&&t.constructor===Object}function Zi(t){return Yi(t.value)?[]:[new Dt(t.key,t.value,`object expected, ${Yr(t.value)} found`)]}const Hi={"*":()=>[],array:Ei,boolean:function(t){const e=t.value,n=t.key,r=Yr(e);return "boolean"!==r?[new Dt(n,e,`boolean expected, ${r} found`)]:[]},number:Ti,color:Di,constants:Ai,enum:zi,filter:Bi,function:Fi,layer:$i,object:Ii,source:Ui,light:ji,sky:qi,terrain:Gi,projection:function(t){const e=t.value,n=t.styleSpec,r=n.projection,i=t.style,s=Yr(e);if(void 0===e)return [];if("object"!==s)return [new Dt("projection",e,`object expected, ${s} found`)];let o=[];for(const s in e)o=o.concat(r[s]?t.validateSpec({key:s,value:e[s],valueSpec:r[s],style:i,styleSpec:n}):[new Dt(s,e[s],`unknown property "${s}"`)]);return o},projectionDefinition:function(t){const e=t.key;let n=t.value;n=n instanceof String?n.valueOf():n;const r=Yr(n);return "array"!==r||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(n)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(n)?["array","string"].includes(r)?[]:[new Dt(e,n,`projection expected, invalid type "${r}" found`)]:[new Dt(e,n,`projection expected, invalid array ${JSON.stringify(n)} found`)]},string:Ri,formatted:function(t){return 0===Ri(t).length?[]:Pi(t)},resolvedImage:function(t){return 0===Ri(t).length?[]:Pi(t)},padding:function(t){const e=t.key,n=t.value;if("array"===Yr(n)){if(n.length<1||n.length>4)return [new Dt(e,n,`padding requires 1 to 4 values; ${n.length} values found`)];const r={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(n=n.concat(Ai({key:"constants",value:t.constants}))),ts(n)}function Qi(t){return function(e){return t(Object.assign({},e,{validateSpec:Wi}))}}function ts(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function es(t){return function(...e){return ts(t.apply(this,e))}}Ji.source=es(Qi(Ui)),Ji.sprite=es(Qi(Xi)),Ji.glyphs=es(Qi(Ki)),Ji.light=es(Qi(ji)),Ji.sky=es(Qi(qi)),Ji.terrain=es(Qi(Gi)),Ji.state=es(Qi(Zi)),Ji.layer=es(Qi($i)),Ji.filter=es(Qi(Bi)),Ji.paintProperty=es(Qi(Li)),Ji.layoutProperty=es(Qi(Oi));const ns={type:"enum","property-type":"data-constant",expression:{interpolated:!1,parameters:["global-state"]},values:{visible:{},none:{}},transition:!1,default:"visible"};class rs{constructor(t,e){this._globalState=e,this.setValue(t);}evaluate(){var t;return null!==(t=this._literalValue)&&void 0!==t?t:this._compiledValue.evaluate({})}setValue(t){if(null==t||"visible"===t||"none"===t)return this._literalValue="none"===t?"none":"visible",this._compiledValue=void 0,void(this._globalStateRefs=new Set);const e=ii(t,ns,this._globalState);if("error"===e.result)throw this._literalValue="visible",this._compiledValue=void 0,new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));this._literalValue=void 0,this._compiledValue=e.value,this._globalStateRefs=ci(e.value.expression);}getGlobalStateRefs(){return this._globalStateRefs}}const is=bt,ss=Ji,os=ss.light,as=ss.sky,ls=ss.paintProperty,us=ss.layoutProperty;function cs(t,e){let n=!1;if(e&&e.length)for(const r of e)t.fire(new xt(new Error(r.message))),n=!0;return n}class hs{constructor(t,e,n){const r=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(n=i[2]);for(let t=0;t=u[l+0]&&r>=u[l+1])?(o[h]=!0,s.push(i[h])):o[h]=!1;}}}}_forEachCell(t,e,n,r,i,s,o,a){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(n),h=this._convertToCellCoord(r);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!a||a(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,n,r,u,s,o,a))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let n=0;for(let t=0;t=0)continue;const s=t[r];i[r]=ps[n].shallow.indexOf(r)>=0?s:gs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==n&&(i.$name=n),i}function xs(t){if(ms(t))return t;if(Array.isArray(t))return t.map(xs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ys(t)||"Object";if(!ps[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:n}=ps[e];if(!n)throw new Error(`can't deserialize unregistered class ${e}`);if(n.deserialize)return n.deserialize(t);const r=Object.create(n.prototype);for(const n of Object.keys(t)){if("$name"===n)continue;const i=t[n];r[n]=ps[e].shallow.indexOf(n)>=0?i:xs(i);}return r}class vs{constructor(){this.first=!0;}update(t,e){const n=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=n,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=n,!0):(this.lastFloorZoom>n?(this.lastIntegerZoom=n+1,this.lastIntegerZoomTime=e):this.lastFloorZoom{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const ks=Ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function Is(t){return !ks.test(String.fromCodePoint(t))}function Es(t){return !(ws(t)||(e=t,/[\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(e))));var e;}const Ts=Ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Fs(t){return Ts.test(String.fromCodePoint(t))}function Ps(t,e){return !(!e&&Fs(t)||/[\u0900-\u0DFF\u0F00-\u109F\u1780-\u17FF]/gim.test(String.fromCodePoint(t)))}function Ds(t){for(const e of t)if(Fs(e.codePointAt(0)))return !0;return !1}const zs=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(zs.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,n){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,r=new Promise((t=>{this.loadScriptResolve=t;}));n(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([r,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Bs{constructor(t,e){this.isSupportedScript=Cs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new vs,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new vs,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),n=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*n}:{fromScale:.5,toScale:1,t:1-(1-n)*e}}}function Cs(t){return function(t,e){for(const n of t)if(!Ps(n.codePointAt(0),e))return !1;return !0}(t,"loaded"===zs.getRTLTextPluginStatus())}const Vs="-transition";class Ls{constructor(t,e,n){this.property=t,this.value=e,this.expression=function(t,e,n){if(Zr(t))return new li(t,e);if(ri(t)){const r=ai(t,e,n);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let n=t;return "color"===e.type&&"string"==typeof t?n=Ee.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?n=Oe.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(n=Re.parse(t)):n=Ce.parse(t):n=Be.parse(t):n=ze.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>n}}}(void 0===e?t.specification.default:e,t.specification,n);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,n){return this.property.possiblyEvaluate(this,t,e,n)}}class Os{constructor(t,e){this.property=t,this.value=new Ls(t,void 0,e);}transitioned(t,e){return new Rs(this.property,this.value,e,O({},t.transition,this.transition),t.now)}untransitioned(){return new Rs(this.property,this.value,null,{},0)}}class $s{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}hasProperty(t){return t in this._properties.defaultTransitionablePropertyValues}getValue(t){return U(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Os(this._values[t].property,this._globalState)),this._values[t].value=new Ls(this._values[t].property,null===e?void 0:U(e),this._globalState);}getTransition(t){return U(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Os(this._values[t].property,this._globalState)),this._values[t].transition=U(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const n=this.getValue(e);void 0!==n&&(t[e]=n);const r=this.getTransition(e);void 0!==r&&(t[`${e}${Vs}`]=r);}return t}transitioned(t,e){const n=new Ns(this._properties);for(const r of Object.keys(this._values))n._values[r]=this._values[r].transitioned(t,e._values[r]);return n}untransitioned(){const t=new Ns(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Rs{constructor(t,e,n,r,i){this.property=t,this.value=e,this.begin=i+r.delay||0,this.end=this.begin+r.duration||0,t.specification.transition&&(r.delay||r.duration)&&(this.prior=n);}possiblyEvaluate(t,e,n){const r=t.now||0,i=this.value.possiblyEvaluate(t,e,n),s=this.prior;if(s){if(r>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(rr.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:n,to:e}}interpolate(t){return t}}class Zs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,n,r){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},n,r);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Bs(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Bs(Math.floor(e.zoom),e)),t.expression.evaluate(new Bs(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,n,r){return r.zoom>r.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:n,to:e}}interpolate(t){return t}}class Hs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,n,r){return !!t.expression.evaluate(e,null,{},n,r)}interpolate(){return !1}}class Ws{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const n=t[e];n.specification.overridable&&this.overridableProperties.push(e);const r=this.defaultPropertyValues[e]=new Ls(n,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Os(n,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=r.possiblyEvaluate({});}}}fs("DataDrivenProperty",Xs),fs("DataConstantProperty",Gs),fs("CrossFadedDataDrivenProperty",Ys),fs("CrossFadedProperty",Zs),fs("ColorRampProperty",Hs);const Ks=" is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?",Js=" is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?";class Qs extends vt{constructor(t,e,n){if(super(),this.id=t.id,this.type=t.type,this._globalState=n,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},this._visibilityExpression=function(t,e){return new rs(t,e)}(this.visibility,n),"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=di(t.filter,n)),e.layout&&(this._unevaluatedLayout=new Us(e.layout,n)),e.paint)){this._transitionablePaint=new $s(e.paint,n);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new qs(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=di(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){var e;if("visibility"===t)return this.visibility;if(null===(e=this._transitionablePaint)||void 0===e?void 0:e.hasProperty(t))throw new Error(t+Ks);if(!this._unevaluatedLayout)throw new Error(`Cannot get layout property "${t}" on layer type "${this.type}" which has no layout properties.`);return this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;for(const e of this._visibilityExpression.getGlobalStateRefs())t.add(e);if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const n=this._unevaluatedLayout._values[e];for(const e of n.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const n in this._transitionablePaint._values){const r=this._transitionablePaint._values[n].value;for(const i of r.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:n,value:r.value}),e.set(i,s);}}return e}getVisibilityAffectingGlobalStateRefs(){return this._visibilityExpression.getGlobalStateRefs()}setLayoutProperty(t,e,n={}){var r;if("visibility"===t)return this.visibility=e,this._visibilityExpression.setValue(e),void this.recalculateVisibility();(null===(r=this._transitionablePaint)||void 0===r?void 0:r.hasProperty(t))?this.fire(new xt(new Error(t+Ks))):null!=e&&this._validate(us,`layers.${this.id}.layout.${t}`,t,e,n)||this._unevaluatedLayout.setValue(t,e);}getPaintProperty(t){var e,n;if(t.endsWith(Vs)){const n=t.slice(0,-11);if("visibility"===n||(null===(e=this._unevaluatedLayout)||void 0===e?void 0:e.hasProperty(n)))throw new Error(t+Js);return this._transitionablePaint.getTransition(n)}if("visibility"===t||(null===(n=this._unevaluatedLayout)||void 0===n?void 0:n.hasProperty(t)))throw new Error(t+Js);return this._transitionablePaint.getValue(t)}setPaintProperty(t,e,n={}){var r;if("visibility"===t||(null===(r=this._unevaluatedLayout)||void 0===r?void 0:r.hasProperty(t)))return this.fire(new xt(new Error(t+Js))),!1;if(null!=e&&this._validate(ls,`layers.${this.id}.paint.${t}`,t,e,n))return !1;if(t.endsWith(Vs))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const n=this._transitionablePaint._values[t],r="cross-faded-data-driven"===n.property.specification["property-type"],i=n.value.isDataDriven(),s=n.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const o=this._transitionablePaint._values[t].value;return o.isDataDriven()||i||r||this._handleOverridablePaintPropertyUpdate(t,s,o)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,n){return !1}isHidden(t=this.minzoom,e=!1){return !!(this.minzoom&&t<(e?Math.floor(this.minzoom):this.minzoom))||!!(this.maxzoom&&t>=this.maxzoom)||"none"===this._evaluatedVisibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculateVisibility(){this._evaluatedVisibility=this._visibilityExpression.evaluate();}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){var t,e;const n={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:null===(t=this._unevaluatedLayout)||void 0===t?void 0:t.serialize(),paint:null===(e=this._transitionablePaint)||void 0===e?void 0:e.serialize()};return this.visibility&&(n.layout=n.layout||{},n.layout.visibility=this.visibility),N(n,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,n,r,i={}){return !1!==(null==i?void 0:i.validate)&&cs(this,t.call(ss,{key:e,layerType:this.type,objectKey:n,value:r,styleSpec:bt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof js&&qr(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}let to;var eo={get paint(){return to=to||new Ws({"raster-opacity":new Gs(bt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Gs(bt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Gs(bt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Gs(bt.paint_raster["raster-brightness-max"]),"raster-saturation":new Gs(bt.paint_raster["raster-saturation"]),"raster-contrast":new Gs(bt.paint_raster["raster-contrast"]),resampling:new Gs(bt.paint_raster.resampling),"raster-resampling":new Gs(bt.paint_raster["raster-resampling"]),"raster-fade-duration":new Gs(bt.paint_raster["raster-fade-duration"])})}};class no extends Qs{constructor(t,e){super(t,eo,e);}}const ro={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class io{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class so{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}freeBufferAfterUpload(){this.arrayBuffer=new ArrayBuffer(0),this._refreshViews();}}function oo(t,e=1){let n=0,r=0;return {members:t.map((t=>{const i=ro[t.type].BYTES_PER_ELEMENT,s=n=ao(n,Math.max(e,i)),o=t.components||1;return r=Math.max(r,i),n+=i*o,{name:t.name,type:t.type,components:o,offset:s}})),size:ao(n,Math.max(r,e)),alignment:e}}function ao(t,e){return Math.ceil(t/e)*e}class lo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const n=this.length;return this.resize(n+1),this.emplace(n,t,e)}emplace(t,e,n){const r=2*t;return this.int16[r+0]=e,this.int16[r+1]=n,t}}lo.prototype.bytesPerElement=4,fs("StructArrayLayout2i4",lo);class uo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,n)}emplace(t,e,n,r){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=n,this.int16[i+2]=r,t}}uo.prototype.bytesPerElement=6,fs("StructArrayLayout3i6",uo);class co extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,n,r)}emplace(t,e,n,r,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=n,this.int16[s+2]=r,this.int16[s+3]=i,t}}co.prototype.bytesPerElement=8,fs("StructArrayLayout4i8",co);class ho extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,n,r,i,s)}emplace(t,e,n,r,i,s,o){const a=6*t;return this.int16[a+0]=e,this.int16[a+1]=n,this.int16[a+2]=r,this.int16[a+3]=i,this.int16[a+4]=s,this.int16[a+5]=o,t}}ho.prototype.bytesPerElement=12,fs("StructArrayLayout2i4i12",ho);class po extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,n,r,i,s)}emplace(t,e,n,r,i,s,o){const a=4*t,l=8*t;return this.int16[a+0]=e,this.int16[a+1]=n,this.uint8[l+4]=r,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=o,t}}po.prototype.bytesPerElement=8,fs("StructArrayLayout2i4ub8",po);class fo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const n=this.length;return this.resize(n+1),this.emplace(n,t,e)}emplace(t,e,n){const r=2*t;return this.float32[r+0]=e,this.float32[r+1]=n,t}}fo.prototype.bytesPerElement=8,fs("StructArrayLayout2f8",fo);class yo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,n,r,i,s,o,a,l,u)}emplace(t,e,n,r,i,s,o,a,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=n,this.uint16[h+2]=r,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=o,this.uint16[h+6]=a,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}yo.prototype.bytesPerElement=20,fs("StructArrayLayout10ui20",yo);class mo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a){const l=this.length;return this.resize(l+1),this.emplace(l,t,e,n,r,i,s,o,a)}emplace(t,e,n,r,i,s,o,a,l){const u=8*t;return this.uint16[u+0]=e,this.uint16[u+1]=n,this.uint16[u+2]=r,this.uint16[u+3]=i,this.uint16[u+4]=s,this.uint16[u+5]=o,this.uint16[u+6]=a,this.uint16[u+7]=l,t}}mo.prototype.bytesPerElement=16,fs("StructArrayLayout8ui16",mo);class go extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,n,r,i,s,o,a,l,u,c,h)}emplace(t,e,n,r,i,s,o,a,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=n,this.int16[f+2]=r,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=o,this.uint16[f+6]=a,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}go.prototype.bytesPerElement=24,fs("StructArrayLayout4i4ui4i24",go);class xo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,n){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,n)}emplace(t,e,n,r){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=n,this.float32[i+2]=r,t}}xo.prototype.bytesPerElement=12,fs("StructArrayLayout3f12",xo);class vo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}vo.prototype.bytesPerElement=4,fs("StructArrayLayout1ul4",vo);class bo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,n,r,i,s,o,a,l)}emplace(t,e,n,r,i,s,o,a,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=n,this.int16[c+2]=r,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=o,this.uint32[h+3]=a,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}bo.prototype.bytesPerElement=20,fs("StructArrayLayout6i1ul2ui20",bo);class wo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,n,r,i,s)}emplace(t,e,n,r,i,s,o){const a=6*t;return this.int16[a+0]=e,this.int16[a+1]=n,this.int16[a+2]=r,this.int16[a+3]=i,this.int16[a+4]=s,this.int16[a+5]=o,t}}wo.prototype.bytesPerElement=12,fs("StructArrayLayout2i2i2i12",wo);class _o extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,n,r,i)}emplace(t,e,n,r,i,s){const o=4*t,a=8*t;return this.float32[o+0]=e,this.float32[o+1]=n,this.float32[o+2]=r,this.int16[a+6]=i,this.int16[a+7]=s,t}}_o.prototype.bytesPerElement=16,fs("StructArrayLayout2f1f2i16",_o);class So extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,n,r,i,s)}emplace(t,e,n,r,i,s,o){const a=16*t,l=4*t,u=8*t;return this.uint8[a+0]=e,this.uint8[a+1]=n,this.float32[l+1]=r,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=o,t}}So.prototype.bytesPerElement=16,fs("StructArrayLayout2ub2f2i16",So);class Ao extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,n)}emplace(t,e,n,r){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=n,this.uint16[i+2]=r,t}}Ao.prototype.bytesPerElement=6,fs("StructArrayLayout3ui6",Ao);class Mo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m)}emplace(t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=n,this.uint16[x+2]=r,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=o,this.uint32[v+4]=a,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}Mo.prototype.bytesPerElement=48,fs("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Mo);class ko extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,M,k,I){const E=this.length;return this.resize(E+1),this.emplace(E,t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,M,k,I)}emplace(t,e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,M,k,I,E){const T=32*t,F=16*t;return this.int16[T+0]=e,this.int16[T+1]=n,this.int16[T+2]=r,this.int16[T+3]=i,this.int16[T+4]=s,this.int16[T+5]=o,this.int16[T+6]=a,this.int16[T+7]=l,this.uint16[T+8]=u,this.uint16[T+9]=c,this.uint16[T+10]=h,this.uint16[T+11]=p,this.uint16[T+12]=f,this.uint16[T+13]=d,this.uint16[T+14]=y,this.uint16[T+15]=m,this.uint16[T+16]=g,this.uint16[T+17]=x,this.uint16[T+18]=v,this.uint16[T+19]=b,this.uint16[T+20]=w,this.uint16[T+21]=_,this.uint16[T+22]=S,this.uint32[F+12]=A,this.float32[F+13]=M,this.float32[F+14]=k,this.uint16[T+30]=I,this.uint16[T+31]=E,t}}ko.prototype.bytesPerElement=64,fs("StructArrayLayout8i15ui1ul2f2ui64",ko);class Io extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}Io.prototype.bytesPerElement=4,fs("StructArrayLayout1f4",Io);class Eo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,n){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,n)}emplace(t,e,n,r){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=n,this.float32[i+2]=r,t}}Eo.prototype.bytesPerElement=12,fs("StructArrayLayout1ui2f12",Eo);class To extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,n){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,n)}emplace(t,e,n,r){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=n,this.uint16[i+3]=r,t}}To.prototype.bytesPerElement=8,fs("StructArrayLayout1ul2ui8",To);class Fo extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const n=this.length;return this.resize(n+1),this.emplace(n,t,e)}emplace(t,e,n){const r=2*t;return this.uint16[r+0]=e,this.uint16[r+1]=n,t}}Fo.prototype.bytesPerElement=4,fs("StructArrayLayout2ui4",Fo);class Po extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}Po.prototype.bytesPerElement=2,fs("StructArrayLayout1ui2",Po);class Do extends so{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,n,r){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,n,r)}emplace(t,e,n,r,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=n,this.float32[s+2]=r,this.float32[s+3]=i,t}}Do.prototype.bytesPerElement=16,fs("StructArrayLayout4f16",Do);class zo extends io{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new n(this.anchorPointX,this.anchorPointY)}}zo.prototype.size=20;class Bo extends bo{get(t){return new zo(this,t)}}fs("CollisionBoxArray",Bo);class Co extends io{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}Co.prototype.size=48;class Vo extends Mo{get(t){return new Co(this,t)}}fs("PlacedSymbolArray",Vo);class Lo extends io{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Lo.prototype.size=64;class Oo extends ko{get(t){return new Lo(this,t)}}fs("SymbolInstanceArray",Oo);class $o extends Io{getoffsetX(t){return this.float32[1*t+0]}}fs("GlyphOffsetArray",$o);class Ro extends uo{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}fs("SymbolLineVertexArray",Ro);class No extends io{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}No.prototype.size=12;class Uo extends Eo{get(t){return new No(this,t)}}fs("TextAnchorOffsetArray",Uo);class jo extends io{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}jo.prototype.size=8;class qo extends To{get(t){return new jo(this,t)}}fs("FeatureIndexArray",qo);class Go extends lo{}class Xo extends lo{}class Yo extends lo{}class Zo extends ho{}class Ho extends po{}class Wo extends fo{}class Ko extends yo{}class Jo extends mo{}class Qo extends go{}class ta extends xo{}class ea extends vo{}class na extends wo{}class ra extends So{}class ia extends Ao{}class sa extends Fo{}const oa=oo([{name:"a_pos",components:2,type:"Int16"}],4),{members:aa}=oa;class la{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,n,r){const i=this.segments[this.segments.length-1];return t>la.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${la.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${la.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>la.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==r?this.createNewSegment(e,n,r):i}createNewSegment(t,e,n){const r={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==n&&(r.sortKey=n),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(r),r}getOrCreateLatestSegment(t,e,n){return this.prepareSegment(0,t,e,n)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,n,r){return new la([{vertexOffset:t,primitiveOffset:e,vertexLength:n,primitiveLength:r,vaos:{},sortKey:0}])}}function ua(t,e){return 256*(t=V(Math.floor(t),0,255))+V(Math.floor(e),0,255)}la.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,fs("SegmentVector",la);const ca=oo([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]),ha=oo([{name:"a_dasharray_from",components:4,type:"Uint16"},{name:"a_dasharray_to",components:4,type:"Uint16"}]);var pa,fa,da,ya={exports:{}},ma={exports:{}},ga={exports:{}},xa=function(){if(da)return ya.exports;da=1;var t=(pa||(pa=1,ma.exports=function(t,e){var n,r,i,s,o,a,l,u;for(r=t.length-(n=3&t.length),i=e,o=3432918353,a=461845907,u=0;u>>16)*o&65535)<<16)&4294967295)<<15|l>>>17))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,n){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<15|l>>>17))*a+(((l>>>16)*a&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),ma.exports),e=(fa||(fa=1,ga.exports=function(t,e){for(var n,r=t.length,i=e^r,s=0;r>=4;)n=1540483477*(65535&(n=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(n>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(n=1540483477*(65535&(n^=n>>>24))+((1540483477*(n>>>16)&65535)<<16)),r-=4,++s;switch(r){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),ga.exports);return ya.exports=t,ya.exports.murmur3=t,ya.exports.murmur2=e,ya.exports}(),va=r(xa);class ba{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,n,r){this.ids.push(wa(t)),this.positions.push(e,n,r);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=wa(t);let n=0,r=this.ids.length-1;for(;n>1;this.ids[t]>=e?r=t:n=t+1;}const i=[];for(;this.ids[n]===e;)i.push({index:this.positions[3*n],start:this.positions[3*n+1],end:this.positions[3*n+2]}),n++;return i}static serialize(t,e){const n=new Float64Array(t.ids),r=new Uint32Array(t.positions);return _a(n,r,0,n.length-1),e&&e.push(n.buffer,r.buffer),{ids:n,positions:r}}static deserialize(t){const e=new ba;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function wa(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:va(String(t))}function _a(t,e,n,r){for(;n>1];let s=n-1,o=r+1;for(;;){do{s++;}while(t[s]i);if(s>=o)break;Sa(t,s,o),Sa(e,3*s,3*o),Sa(e,3*s+1,3*o+1),Sa(e,3*s+2,3*o+2);}o-n`u_${t}`)),this.type=n;}setUniform(t,e,n){t.set(n.constantOr(this.value));}getBinding(t,e,n){return "color"===this.type?new Ia(t,e):new Ma(t,e)}}class Pa{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setConstantDashPositions(t,e){this.dashTo=[0,t.y,t.height,t.width],this.dashFrom=[0,e.y,e.height,e.width];}setUniform(t,e,n,r){let i=null;"u_pattern_to"===r?i=this.patternTo:"u_pattern_from"===r?i=this.patternFrom:"u_dasharray_to"===r?i=this.dashTo:"u_dasharray_from"===r?i=this.dashFrom:"u_pixel_ratio_to"===r?i=this.pixelRatioTo:"u_pixel_ratio_from"===r&&(i=this.pixelRatioFrom),null!==i&&t.set(i);}getBinding(t,e,n){return n.startsWith("u_pattern")||n.startsWith("u_dasharray_")?new ka(t,e):new Ma(t,e)}}class Da{constructor(t,e,n,r){this.expression=t,this.type=n,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===n?2:1,offset:0}))),this.paintVertexArray=new r;}populatePaintArray(t,e,n){const r=this.paintVertexArray.length,i=this.expression.evaluate(new Bs(0,n),e,{},n.canonical,[],n.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(r,t,i);}updatePaintArray(t,e,n,r,i){const s=this.expression.evaluate(new Bs(0,i),n,r);this._setPaintValue(t,e,s);}_setPaintValue(t,e,n){if("color"===this.type){const r=Ta(n);for(let n=t;n`u_${t}_t`)),this.type=n,this.useIntegerZoom=r,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===n?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,n){const r=this.expression.evaluate(new Bs(this.zoom,n),e,{},n.canonical,[],n.formattedSection),i=this.expression.evaluate(new Bs(this.zoom+1,n),e,{},n.canonical,[],n.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,r,i);}updatePaintArray(t,e,n,r,i){const s=this.expression.evaluate(new Bs(this.zoom,i),n,r),o=this.expression.evaluate(new Bs(this.zoom+1,i),n,r);this._setPaintValue(t,e,s,o);}_setPaintValue(t,e,n,r){if("color"===this.type){const i=Ta(n),s=Ta(r);for(let n=t;n`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const n=this.binders[e];if(n instanceof Da||n instanceof za)for(let e=0;e!0){this.programConfigurations={};for(const r of t)this.programConfigurations[r.id]=new La(r,e,n);this.needsUpload=!1,this._featureMap=new ba,this._bufferOffset=0;}populatePaintArrays(t,e,n,r){for(const n in this.programConfigurations)this.programConfigurations[n].populatePaintArrays(t,e,r);void 0!==e.id&&this._featureMap.add(e.id,n,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,n,r){for(const i of n)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,r)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function $a(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-dasharray":["dasharray_to","dasharray_from"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function Ra(t,e,n){const r={color:{source:fo,composite:Do},number:{source:Io,composite:fo}},i=function(t){return {"line-pattern":{source:Ko,composite:Ko},"fill-pattern":{source:Ko,composite:Ko},"fill-extrusion-pattern":{source:Ko,composite:Ko},"line-dasharray":{source:Jo,composite:Jo}}[t]}(t);return i&&i[n]||r[e][n]}fs("ConstantBinder",Fa),fs("CrossFadedConstantBinder",Pa),fs("SourceExpressionBinder",Da),fs("CrossFadedPatternBinder",Ca),fs("CrossFadedDasharrayBinder",Va),fs("CompositeExpressionBinder",za),fs("ProgramConfiguration",La,{omit:["_buffers"]}),fs("ProgramConfigurationSet",Oa);const Na=Math.pow(2,14)-1,Ua=-Na-1;function ja(t){const e=T/t.extent,n=t.loadGeometry();for(let t=0;tn.x+1||sn.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return n}function qa(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?ja(t):[]}}const Ga=-32768;function Xa(t,e,n,r,i){t.emplaceBack(Ga+8*e+r,Ga+8*n+i);}class Ya{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasDependencies=!1,this.layoutVertexArray=new Xo,this.indexArray=new ia,this.segments=new la,this.programConfigurations=new Oa(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,n){const r=this.layers[0],i=[];let s=null,o=!1,a="heatmap"===r.type;if("circle"===r.type){const t=r;s=t.layout.get("circle-sort-key"),o=!s.isConstant(),a=a||"map"===t.paint.get("circle-pitch-alignment");}const l=a?e.subdivisionGranularity.circle:1;for(const{feature:e,id:r,index:a,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=qa(e,t);if(!this.layers[0]._featureFilter.filter(new Bs(this.zoom),u,n))continue;const c=o?s.evaluate(u,{},n):void 0,h={id:r,properties:e.properties,type:e.type,sourceLayerIndex:l,index:a,geometry:t?u.geometry:ja(e),patterns:{},sortKey:c};i.push(h);}o&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of i){const{geometry:i,index:s,sourceLayerIndex:o}=r,a=t[s].feature;this.addFeature(r,i,s,n,l),e.featureIndex.insert(a,i,s,o,this.index);}}update(t,e,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:n});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,aa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,n,r,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const o=s.length;for(const n of e)for(const e of n){const n=e.x,r=e.y;if(n<0||n>=T||r<0||r>=T)continue;const i=this.segments.prepareSegment(o*o,this.layoutVertexArray,this.indexArray,t.sortKey),a=i.vertexLength;for(let t=0;t1){if(Ja(t,e))return !0;for(let r=0;r1?n:n.sub(e)._mult(i)._add(e))}function nl(t,e){let n,r,i,s=!1;for(let o=0;oe.y!=i.y>e.y&&e.x<(i.x-r.x)*(e.y-r.y)/(i.y-r.y)+r.x&&(s=!s);}return s}function rl(t,e){let n=!1;for(let r=0,i=t.length-1;re.y!=o.y>e.y&&e.x<(o.x-s.x)*(e.y-s.y)/(o.y-s.y)+s.x&&(n=!n);}return n}function il(t,e,n){const r=n[0],i=n[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,n[0]);return s!==G(t,e,n[1])||s!==G(t,e,n[2])||s!==G(t,e,n[3])}function sl(t,e,n){const r=e.paint.get(t).value;return "constant"===r.kind?r.value:n.programConfigurations.get(e.id).getMaxValue(t)}function ol(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function al(t,e,r,i,s){if(!e[0]&&!e[1])return t;const o=n.convert(e)._mult(s);"viewport"===r&&o._rotate(-i);const a=[];for(let e=0;edl(t,e,n,r)))}(l,i,o,a),f=u),fl({queryGeometry:p,size:f,transform:i,unwrappedTileID:o,getElevation:a,pitchAlignment:h,pitchScale:c},r)}}class vl extends Ya{}let bl;fs("HeatmapBucket",vl,{omit:["layers"]});var wl={get paint(){return bl=bl||new Ws({"heatmap-radius":new Xs(bt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Xs(bt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Gs(bt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Hs(bt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Gs(bt.paint_heatmap["heatmap-opacity"])})}};function _l(t,{width:e,height:n},r,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*n*r)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*n*r}`)}else i=new Uint8Array(e*n*r);return t.width=e,t.height=n,t.data=i,t}function Sl(t,{width:e,height:n},r){if(e===t.width&&n===t.height)return;const i=_l({},{width:e,height:n},r);Al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,n)},r),t.width=e,t.height=n,t.data=i.data;}function Al(t,e,n,r,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||n.x>t.width-i.width||n.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||r.x>e.width-i.width||r.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const o=t.data,a=e.data;if(o===a)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=o;const a=t.expression.evaluate(e);i.setPixel(r/4/n,s/4,a);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=n),n=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError(`Out of range source coordinates for DEM data. x: ${t}, y: ${e}, dim: ${this.dim}`);return (e+1)*this.stride+(t+1)}unpack(t,e,n){return t*this.redFactor+e*this.greenFactor+n*this.blueFactor-this.baseShift}pack(t){return $l(t,this.getUnpackVector())}getPixels(){return new kl({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,n){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let r=e*this.dim,i=e*this.dim+this.dim,s=n*this.dim,o=n*this.dim+this.dim;switch(e){case -1:r=i-1;break;case 1:i=r+1;}switch(n){case -1:s=o-1;break;case 1:o=s+1;}const a=-e*this.dim,l=-n*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=r)s=fu(i/r|0,t[i],t[i+1],s);return s&&au(s,s.next)&&(du(s),s=s.next),s}function Xl(t,e){if(!t)return t;e||(e=t);let n,r=t;do{if(n=!1,r.steiner||!au(r,r.next)&&0!==ou(r.prev,r,r.next))r=r.next;else {if(du(r),r=e=r.prev,r===r.next)break;n=!0;}}while(n||r!==e);return e}function Yl(t,e,n,r,i,s,o){if(!t)return;!o&&s&&function(t,e,n,r){let i=t;do{0===i.z&&(i.z=eu(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,n=1;do{let r,i=t;t=null;let s=null;for(e=0;i;){e++;let o=i,a=0;for(let t=0;t0||l>0&&o;)0!==a&&(0===l||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;i=o;}s.nextZ=null,n*=2;}while(e>1)}(i);}(t,r,i,s);let a=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Hl(t,r,i,s):Zl(t))e.push(l.i,t.i,u.i),du(t),t=u.next,a=u.next;else if((t=u)===a){o?1===o?Yl(t=Wl(Xl(t),e),e,n,r,i,s,2):2===o&&Kl(t,e,n,r,i,s):Yl(Xl(t),e,n,r,i,s,1);break}}}function Zl(t){const e=t.prev,n=t,r=t.next;if(ou(e,n,r)>=0)return !1;const i=e.x,s=n.x,o=r.x,a=e.y,l=n.y,u=r.y,c=Math.min(i,s,o),h=Math.min(a,l,u),p=Math.max(i,s,o),f=Math.max(a,l,u);let d=r.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&iu(i,a,s,l,o,u,d.x,d.y)&&ou(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Hl(t,e,n,r){const i=t.prev,s=t,o=t.next;if(ou(i,s,o)>=0)return !1;const a=i.x,l=s.x,u=o.x,c=i.y,h=s.y,p=o.y,f=Math.min(a,l,u),d=Math.min(c,h,p),y=Math.max(a,l,u),m=Math.max(c,h,p),g=eu(f,d,e,n,r),x=eu(y,m,e,n,r);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==o&&iu(a,c,l,h,u,p,v.x,v.y)&&ou(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==o&&iu(a,c,l,h,u,p,b.x,b.y)&&ou(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==o&&iu(a,c,l,h,u,p,v.x,v.y)&&ou(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==o&&iu(a,c,l,h,u,p,b.x,b.y)&&ou(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Wl(t,e){let n=t;do{const r=n.prev,i=n.next.next;!au(r,i)&&lu(r,n,n.next,i)&&hu(r,i)&&hu(i,r)&&(e.push(r.i,n.i,i.i),du(n),du(n.next),n=t=i),n=n.next;}while(n!==t);return Xl(n)}function Kl(t,e,n,r,i,s){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&su(o,t)){let a=pu(o,t);return o=Xl(o,o.next),a=Xl(a,a.next),Yl(o,e,n,r,i,s,0),void Yl(a,e,n,r,i,s,0)}t=t.next;}o=o.next;}while(o!==t)}function Jl(t,e){let n=t.x-e.x;return 0===n&&(n=t.y-e.y,0===n)&&(n=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),n}function Ql(t,e){const n=function(t,e){let n=e;const r=t.x,i=t.y;let s,o=-1/0;if(au(t,n))return n;do{if(au(t,n.next))return n.next;if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){const t=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(t<=r&&t>o&&(o=t,s=n.x=n.x&&n.x>=l&&r!==n.x&&ru(is.x||n.x===s.x&&tu(s,n)))&&(s=n,c=e);}n=n.next;}while(n!==a);return s}(t,e);if(!n)return e;const r=pu(n,t);return Xl(r,r.next),Xl(n,n.next)}function tu(t,e){return ou(t.prev,t,e.prev)<0&&ou(e.next,t,t.next)<0}function eu(t,e,n,r,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function nu(t){let e=t,n=t;do{(e.x=(t-o)*(s-a)&&(t-o)*(r-a)>=(n-o)*(e-a)&&(n-o)*(s-a)>=(i-o)*(r-a)}function iu(t,e,n,r,i,s,o,a){return !(t===o&&e===a)&&ru(t,e,n,r,i,s,o,a)}function su(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&lu(n,n.next,t,e))return !0;n=n.next;}while(n!==t);return !1}(t,e)&&(hu(t,e)&&hu(e,t)&&function(t,e){let n=t,r=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&i<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next;}while(n!==t);return r}(t,e)&&(ou(t.prev,t,e.prev)||ou(t,e.prev,e))||au(t,e)&&ou(t.prev,t,t.next)>0&&ou(e.prev,e,e.next)>0)}function ou(t,e,n){return (e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function au(t,e){return t.x===e.x&&t.y===e.y}function lu(t,e,n,r){const i=cu(ou(t,e,n)),s=cu(ou(t,e,r)),o=cu(ou(n,r,t)),a=cu(ou(n,r,e));return i!==s&&o!==a||!(0!==i||!uu(t,n,e))||!(0!==s||!uu(t,r,e))||!(0!==o||!uu(n,t,r))||!(0!==a||!uu(n,e,r))}function uu(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function cu(t){return t>0?1:t<0?-1:0}function hu(t,e){return ou(t.prev,t,t.next)<0?ou(t,e,t.next)>=0&&ou(t,t.prev,e)>=0:ou(t,e,t.prev)<0||ou(t,t.next,e)<0}function pu(t,e){const n=yu(t.i,t.x,t.y),r=yu(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,s.next=r,r.prev=s,r}function fu(t,e,n,r){const i=yu(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function du(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function yu(t,e,n){return {i:t,x:e,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class mu{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const n=0|Math.round(t),r=0|Math.round(e),i=this._getKey(n,r);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(n,r),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const n=[];for(let r=0;r0?(n.push(i),n.push(o),n.push(s)):(n.push(i),n.push(s),n.push(o));}return n}(this._vertexBuffer,t);const e=[],n=t.length;for(let r=0;r=1||v<=0)||y&&(ai)){u>=r&&u<=i&&s.push(n[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(o+p*x,a+f*x));const b=o+p*Math.max(x,0),w=o+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,o,a,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(o+p*v,a+f*v)),(y||u>=r&&u<=i)&&s.push(n[(t+1)%3]),!y&&(u<=r||u>=i)&&this._generateInterEdgeVertices(s,o,a,l,u,c,h,w,r,i);}return s}_generateIntraEdgeVertices(t,e,n,r,i,s,o){const a=r-e,l=i-n,u=0===l,c=u?Math.min(e,r):Math.min(s,o),h=u?Math.max(e,r):Math.max(s,o),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;r--){const i=r*this._granularityCellSize;t.push(this._vertexToIndex(i,n+l*(i-e)/a));}}_generateInterEdgeVertices(t,e,n,r,i,s,o,a,l,u){const c=i-n,h=s-r,p=o-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=r+h*y;let x=Math.floor(Math.min(g,a)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,a)/this._granularityCellSize)-1,b=a=1||m<=0){const t=n-o,r=s+(e-s)*Math.min((l-o)/t,(u-o)/t);x=Math.floor(Math.min(r,a)/this._granularityCellSize)+1,v=Math.ceil(Math.max(r,a)/this._granularityCellSize)-1,b=a0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const n of t){const t=_u(n,this._granularity,!0),r=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===xu)?(t.push(e),t.push(n),t.push(this._vertexToIndex(r,s)),t.push(n),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(r,s))):(t.push(n),t.push(e),t.push(this._vertexToIndex(r,s)),t.push(this._vertexToIndex(i,s)),t.push(n),t.push(this._vertexToIndex(r,s)));}_fillPoles(t,e,n){const r=this._vertexBuffer,i=T,s=t.length;for(let o=2;o80*n){a=t[0],l=t[1];let e=a,r=l;for(let s=n;se&&(e=n),i>r&&(r=i);}u=Math.max(e-a,r-l),u=0!==u?32767/u:0;}return Yl(s,o,n,a,l,u,0),o}(n,r),e=this._convertIndices(n,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const n=[];for(let r=0;r0?(Math.floor(x/a)+1)*a:(Math.ceil(x/a)-1)*a,e=y>0?(Math.floor(v/a)+1)*a:(Math.ceil(v/a)-1)*a,r=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),o=Math.abs(v-h),u=p?r/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=r||!p)&&(o<=i||!f))break;if(u=0?o-1:s-1,i=(a+1)%s,l=t[2*e[r]],u=t[2*e[i]],c=t[2*e[o]],h=t[2*e[o]+1],p=t[2*e[a]+1];let f=!1;if(lu)f=!1;else {const n=p-h,s=-(t[2*e[a]]-c),o=h((u-c)*n+(t[2*e[i]+1]-h)*s)*o&&(f=!0);}if(f){const t=e[r],i=e[o],l=e[a];t!==i&&t!==l&&i!==l&&n.push(l,i,t),o--,o<0&&(o=s-1);}else {const t=e[i],r=e[o],l=e[a];t!==r&&t!==l&&r!==l&&n.push(l,r,t),a++,a>=s&&(a=0);}if(r===i)break}}function Au(t,e,n,r,i,s,o,a,l){const u=i.length/2,c=o&&a&&l;if(ula.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,n),l=a.count,y=!0,m=!0,g=!0,c=0);const x=Mu(o,r,s,a,p,y,u),v=Mu(o,r,s,a,f,m,u),b=Mu(o,r,s,a,d,g,u);n.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,n,r,i,s,t),c&&function(t,e,n,r,i,s){const o=[];for(let t=0;tla.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,n),l=a.count,d=!0,y=!0,c=0);const m=Mu(o,r,s,a,i,d,u),g=Mu(o,r,s,a,h,y,u);n.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(o,n,a,i,l,t),e.forceNewSegmentOnNextPrepare(),null==o||o.forceNewSegmentOnNextPrepare();}function Mu(t,e,n,r,i,s,o){if(s){const s=r.count;return n(e[2*i],e[2*i+1]),t[i]=r.count,r.count++,o.vertexLength++,s}return t[i]}class ku{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasDependencies=!1,this.patternFeatures=[],this.layoutVertexArray=new Yo,this.indexArray=new ia,this.indexArray2=new sa,this.programConfigurations=new Oa(t.layers,t.zoom),this.segments=new la,this.segments2=new la,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,n){this.hasDependencies=jl("fill",this.layers,e);const r=this.layers[0].layout.get("fill-sort-key"),i=!r.isConstant(),s=[];for(const{feature:o,id:a,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=qa(o,t);if(!this.layers[0]._featureFilter.filter(new Bs(this.zoom),c,n))continue;const h=i?r.evaluate(c,{},n,e.availableImages):void 0,p={id:a,properties:o.properties,type:o.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:ja(o),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of s){const{geometry:i,index:s,sourceLayerIndex:o}=r;if(this.hasDependencies){const t=ql("fill",this.layers,r,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(r,i,s,n,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,o,this.index);}}update(t,e,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:n});}addFeatures(t,e,n){for(const r of this.patternFeatures)this.addFeature(r,r.geometry,r.index,e,n,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ul),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,n,r,i,s){for(const t of nr(e,500)){const e=wu(t,r,s.fill.getGranularityForZoomLevel(r.z)),n=this.layoutVertexArray;Au(((t,e)=>{n.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,n,{imagePositions:i,canonical:r});}}let Iu,Eu;fs("FillBucket",ku,{omit:["layers","patternFeatures"]});var Tu={get paint(){return Eu=Eu||new Ws({"fill-antialias":new Gs(bt.paint_fill["fill-antialias"]),"fill-opacity":new Xs(bt.paint_fill["fill-opacity"]),"fill-color":new Xs(bt.paint_fill["fill-color"]),"fill-outline-color":new Xs(bt.paint_fill["fill-outline-color"]),"fill-translate":new Gs(bt.paint_fill["fill-translate"]),"fill-translate-anchor":new Gs(bt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Ys(bt.paint_fill["fill-pattern"])})},get layout(){return Iu=Iu||new Ws({"fill-sort-key":new Xs(bt.layout_fill["fill-sort-key"])})}};class Fu extends Qs{constructor(t,e){super(t,Tu,e);}recalculate(t,e){super.recalculate(t,e);const n=this.paint._values["fill-outline-color"];"constant"===n.value.kind&&void 0===n.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new ku(t)}queryRadius(){return ol(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:n,pixelsToTileUnits:r}){return Wa(al(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-n.bearingInRadians,r),e)}isTileClipped(){return !0}}const Pu=oo([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Du=oo([{name:"a_centroid",components:2,type:"Int16"}],4),{members:zu}=Pu;class Bu{constructor(t,e,n,r,i){this.properties={},this.extent=n,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=r,this._values=i,t.readFields(Cu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,r=[];let i,s=1,o=0,a=0,l=0;for(;t.pos>3;}if(o--,1===s||2===s)a+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&r.push(i),i=[]),i&&i.push(new n(a,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&r.push(i),r}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let n=1,r=0,i=0,s=0,o=1/0,a=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(r--,1===n||2===n)i+=t.readSVarint(),s+=t.readSVarint(),ia&&(a=i),su&&(u=s);else if(7!==n)throw new Error(`unknown command ${n}`)}return [o,l,a,u]}toGeoJSON(t,e,n){const r=this.extent*Math.pow(2,n),i=this.extent*t,s=this.extent*e,o=this.loadGeometry();function a(t){return [360*(t.x+i)/r-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/r)*Math.PI))-90]}function l(t){return t.map(a)}let u;if(1===this.type){const t=[];for(const e of o)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=o.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=Vu(o),e=[];for(const n of t)e.push(n.map(l));u=1===e.length?{type:"Polygon",coordinates:e[0]}:{type:"MultiPolygon",coordinates:e};}}const c={type:"Feature",geometry:u,properties:this.properties};return null!=this.id&&(c.id=this.id),c}}function Cu(t,e,n){1===t?e.id=n.readVarint():2===t?function(t,e){const n=t.readVarint()+t.pos;for(;t.pos=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new Bu(this._pbf,e,this.extent,this._keys,this._values)}}function $u(t,e,n){15===t?e.version=n.readVarint():1===t?e.name=n.readString():5===t?e.extent=n.readVarint():2===t?e._features.push(n.pos):3===t?e._keys.push(n.readString()):4===t&&e._values.push(function(t){let e=null;const n=t.readVarint()+t.pos;for(;t.pos>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(n));}class Ru{constructor(t,e){this.layers=t.readFields(Nu,{},e);}}function Nu(t,e,n){if(3===t){const t=new Ou(n,n.readVarint()+n.pos);t.length&&(e[t.name]=t);}}const Uu=Math.pow(2,13);function ju(t,e,n,r,i,s,o,a){t.emplaceBack(e,n,2*Math.floor(r*Uu)+o,i*Uu*2,s*Uu*2,Math.round(a));}class qu{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasDependencies=!1,this.layoutVertexArray=new Zo,this.centroidVertexArray=new Go,this.indexArray=new ia,this.programConfigurations=new Oa(t.layers,t.zoom),this.segments=new la,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,n){this.features=[],this.hasDependencies=jl("fill-extrusion",this.layers,e);for(const{feature:r,id:i,index:s,sourceLayerIndex:o}of t){const t=this.layers[0]._featureFilter.needGeometry,a=qa(r,t);if(!this.layers[0]._featureFilter.filter(new Bs(this.zoom),a,n))continue;const l={id:i,sourceLayerIndex:o,index:s,geometry:t?a.geometry:ja(r),properties:r.properties,type:r.type,patterns:{}};this.hasDependencies?this.features.push(ql("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,n,{},e.subdivisionGranularity),e.featureIndex.insert(r,l.geometry,s,o,this.index,!0);}}addFeatures(t,e,n){for(const r of this.features){const{geometry:i}=r;this.addFeature(r,i,r.index,e,n,t.subdivisionGranularity);}}update(t,e,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:n});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,zu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,Du.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,n,r,i,s){for(const n of nr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,r,t,n,s);const o=this.layoutVertexArray.length-i,a=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{ju(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let n=0;for(let r=1;rla.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const o=i.sub(s)._perp()._unit(),a=s.dist(i);n+a>32768&&(n=0),ju(this.layoutVertexArray,i.x,i.y,o.x,o.y,0,0,n),ju(this.layoutVertexArray,i.x,i.y,o.x,o.y,0,1,n),n+=a,ju(this.layoutVertexArray,s.x,s.y,o.x,o.y,0,0,n),ju(this.layoutVertexArray,s.x,s.y,o.x,o.y,0,1,n);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Gu(t,e){for(let n=0;nT)||t.y===e.y&&(t.y<0||t.y>T)}function Yu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>T))||t.every((t=>t.y<0))||t.every((t=>t.y>T))}let Zu;fs("FillExtrusionBucket",qu,{omit:["layers","features"]});var Hu={get paint(){return Zu=Zu||new Ws({"fill-extrusion-opacity":new Gs(bt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Xs(bt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Gs(bt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Gs(bt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Ys(bt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Xs(bt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Xs(bt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Gs(bt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Wu extends Qs{constructor(t,e){super(t,Hu,e);}createBucket(t){return new qu(t)}queryRadius(){return ol(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:i,transform:s,pixelsToTileUnits:o,pixelPosMatrix:a}){const l=al(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,o),u=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e){const r=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),r.push(new n(t[0]/t[3],t[1]/t[3]));}return r}(l,a),p=function(t,e,r,i){const s=[],o=[],a=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*r,p=i[9]*r,f=i[10]*r,d=i[11]*r;for(const e of t){const t=[],r=[];for(const s of e){const e=s.x,o=s.y,y=i[0]*e+i[4]*o+i[12],m=i[1]*e+i[5]*o+i[13],g=i[2]*e+i[6]*o+i[14],x=i[3]*e+i[7]*o+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,M=new n((y+a)/b,(m+l)/b);M.z=v/b,t.push(M);const k=new n(w/A,_/A);k.z=S/A,r.push(k);}s.push(t),o.push(r);}return [s,o]}(i,c,u,a);return function(t,e,n){let r=1/0;Wa(n,e)&&(r=Ju(n,e[0]));for(let i=0;i>4;if(1!==r)throw new Error(`Got v${r} data when expected v1.`);const i=Qu[15&n];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[o]=new Uint32Array(t,4,1);return new tc(o,s,i,t)}constructor(t,e=64,n=Float64Array,r){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=n,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=Qu.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,o=t*this.IndexArrayType.BYTES_PER_ELEMENT,a=(8-o%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${n}.`);r&&r instanceof ArrayBuffer?(this.data=r,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+o+a,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+o+a),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+o+a,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const n=this._pos>>1;return this.ids[n]=n,this.coords[this._pos++]=t,this.coords[this._pos++]=e,n}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return ec(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,n,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:o}=this,a=[0,i.length-1,0],l=[];for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=o){for(let o=h;o<=c;o++){const a=s[2*o],u=s[2*o+1];a>=t&&a<=n&&u>=e&&u<=r&&l.push(i[o]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=n&&d>=e&&d<=r&&l.push(i[p]),(0===u?t<=f:e<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?n>=f:r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return l}within(t,e,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:r,coords:i,nodeSize:s}=this,o=[0,r.length-1,0],a=[],l=n*n;for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=s){for(let n=h;n<=c;n++)sc(i[2*n],i[2*n+1],t,e)<=l&&a.push(r[n]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];sc(f,d,t,e)<=l&&a.push(r[p]),(0===u?t-n<=f:e-n<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?t+n>=f:e+n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return a}}function ec(t,e,n,r,i,s){if(i-r<=n)return;const o=r+i>>1;nc(t,e,o,r,i,s),ec(t,e,n,r,o-1,1-s),ec(t,e,n,o+1,i,1-s);}function nc(t,e,n,r,i,s){for(;i>r;){if(i-r>600){const o=i-r+1,a=n-r+1,l=Math.log(o),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(o-u)/o)*(a-o/2<0?-1:1);nc(t,e,n,Math.max(r,Math.floor(n-a*u/o+c)),Math.min(i,Math.floor(n+(o-a)*u/o+c)),s);}const o=e[2*n+s];let a=r,l=i;for(rc(t,e,r,n),e[2*i+s]>o&&rc(t,e,r,i);ao;)l--;}e[2*r+s]===o?rc(t,e,r,l):(l++,rc(t,e,l,i)),l<=n&&(r=l+1),n<=l&&(i=l-1);}}function rc(t,e,n,r){ic(t,n,r),ic(e,2*n,2*r),ic(e,2*n+1,2*r+1);}function ic(t,e,n){const r=t[e];t[e]=t[n],t[n]=r;}function sc(t,e,n,r){const i=t-n,s=e-r;return i*i+s*s}function oc(t,e,n,r){let i=r;const s=e+(n-e>>1);let o,a=n-e;const l=t[e],u=t[e+1],c=t[n],h=t[n+1];for(let r=e+3;ri)o=r,i=e;else if(e===i){const t=Math.abs(r-s);tr&&(o-e>3&&oc(t,e,o,r),t[o+2]=i,n-o>3&&oc(t,o,n,r));}function ac(t,e,n,r,i,s){let o=i-n,a=s-r;if(0!==o||0!==a){const l=((t-n)*o+(e-r)*a)/(o*o+a*a);l>1?(n=i,r=s):l>0&&(n+=o*l,r+=a*l);}return o=t-n,a=e-r,o*o+a*a}function lc(t,e,n,r){const i={type:e,geom:n},s={id:null==t?null:t,type:i.type,geometry:i.geom,tags:r,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};switch(i.type){case "Point":case "MultiPoint":case "LineString":uc(s,i.geom);break;case "Polygon":uc(s,i.geom[0]);break;case "MultiLineString":for(const t of i.geom)uc(s,t);break;case "MultiPolygon":for(const t of i.geom)uc(s,t[0]);}return s}function uc(t,e){for(let n=0;n0&&(o+=r?(i*l-a*s)/2:Math.sqrt(Math.pow(a-i,2)+Math.pow(l-s,2))),i=a,s=l;}const a=e.length-3;e[2]=1,n>0&&oc(e,0,a,n),e[a+2]=1,e.size=Math.abs(o),e.start=0,e.end=e.size;}function fc(t,e,n,r){for(let i=0;i1?1:n}function mc(t){const e={type:"Feature",geometry:gc(t),properties:t.tags};return null!=t.id&&(e.id=t.id),e}function gc(t){const{type:e,geometry:n}=t;switch(e){case "Point":return {type:e,coordinates:vc(n[0],n[1])};case "MultiPoint":case "LineString":return {type:e,coordinates:xc(n)};case "MultiLineString":case "Polygon":return {type:e,coordinates:n.map((t=>xc(t)))};case "MultiPolygon":return {type:e,coordinates:n.map((t=>t.map((t=>xc(t)))))}}}function xc(t){const e=[];for(let n=0;n=(n/=e)&&o=r)return null;const l=[];for(const e of t){const t=i===_c.X?e.minX:e.minY,s=i===_c.X?e.maxX:e.maxY;if(t>=n&&s=r))switch(e.type){case "Point":case "MultiPoint":Ac(e,l,n,r,i);continue;case "LineString":Mc(e,l,n,r,i,a);continue;case "MultiLineString":kc(e,l,n,r,i);continue;case "Polygon":Ic(e,l,n,r,i);continue;case "MultiPolygon":Ec(e,l,n,r,i);continue}}return l.length?l:null}function Ac(t,e,n,r,i){const s=[];((function(t,e,n,r,i){for(let s=0;s=n&&o<=r&&Dc(e,t[s],t[s+1],t[s+2]);}}))(t.geometry,s,n,r,i),s.length&&e.push(lc(t.id,3===s.length?"Point":"MultiPoint",s,t.tags));}function Mc(t,e,n,r,i,s){const o=[];if(Tc(t.geometry,o,n,r,i,!1,s.lineMetrics),o.length)if(s.lineMetrics)for(const n of o)e.push(lc(t.id,"LineString",n,t.tags));else e.push(o.length>1?lc(t.id,"MultiLineString",o,t.tags):lc(t.id,"LineString",o[0],t.tags));}function kc(t,e,n,r,i){const s=[];Pc(t.geometry,s,n,r,i,!1),s.length&&e.push(1!==s.length?lc(t.id,"MultiLineString",s,t.tags):lc(t.id,"LineString",s[0],t.tags));}function Ic(t,e,n,r,i){const s=[];Pc(t.geometry,s,n,r,i,!0),s.length&&e.push(lc(t.id,"Polygon",s,t.tags));}function Ec(t,e,n,r,i){const s=[];for(const e of t.geometry){const t=[];Pc(e,t,n,r,i,!0),t.length&&s.push(t);}s.length&&e.push(lc(t.id,"MultiPolygon",s,t.tags));}function Tc(t,e,n,r,i,s,o){let a=Fc(t);const l=i===_c.X?zc:Bc;let u,c,h=t.start;for(let p=0;pn&&(c=l(a,f,d,m,g,n),o&&(a.start=h+u*c)):x>r?v=n&&(c=l(a,f,d,m,g,n),b=!0),v>r&&x<=r&&(c=l(a,f,d,m,g,r),b=!0),!s&&b&&(o&&(a.end=h+u*c),e.push(a),a=Fc(t)),o&&(h+=u);}let p=t.length-3;const f=t[p],d=t[p+1],y=i===_c.X?f:d;y>=n&&y<=r&&Dc(a,f,d,t[p+2]),p=a.length-3,s&&p>=3&&(a[p]!==a[0]||a[p+1]!==a[1])&&Dc(a,a[0],a[1],a[2]),a.length&&e.push(a);}function Fc(t){const e=[];return e.size=t.size,e.start=t.start,e.end=t.end,e}function Pc(t,e,n,r,i,s){for(const o of t)Tc(o,e,n,r,i,s,!1);}function Dc(t,e,n,r){t.push(e,n,r);}function zc(t,e,n,r,i,s){const o=(s-e)/(r-e);return Dc(t,s,n+(i-n)*o,1),o}function Bc(t,e,n,r,i,s){const o=(s-n)/(i-n);return Dc(t,e+(r-e)*o,s,1),o}function Cc(t,e){const n=e.buffer/e.extent;let r=t;const i=Sc(t,1,-1-n,n,_c.X,-1,2,e),s=Sc(t,1,1-n,2+n,_c.X,-1,2,e);return i||s?(r=Sc(t,1,-n,1+n,_c.X,-1,2,e)||[],i&&(r=Vc(i,1).concat(r)),s&&(r=r.concat(Vc(s,-1))),r):r}function Vc(t,e){const n=[];for(const r of t)switch(r.type){case "Point":case "MultiPoint":case "LineString":{const t=Lc(r.geometry,e);n.push(lc(r.id,r.type,t,r.tags));continue}case "MultiLineString":case "Polygon":{const t=[];for(const n of r.geometry)t.push(Lc(n,e));n.push(lc(r.id,r.type,t,r.tags));continue}case "MultiPolygon":{const t=[];for(const n of r.geometry){const r=[];for(const t of n)r.push(Lc(t,e));t.push(r);}n.push(lc(r.id,r.type,t,r.tags));continue}}return n}function Lc(t,e){const n=[];n.size=t.size,void 0!==t.start&&(n.start=t.start,n.end=t.end);for(let r=0;r0||e.addOrUpdateProperties?.length>0;if(r){const r=t[0];let s=cc({type:"FeatureCollection",features:[{type:"Feature",id:r.id,geometry:e.newGeometry,properties:i?$c(r.tags,e):r.tags}]},n);return s=Cc(s,n),s}if(i){const n=[];for(const r of t){const t={...r};t.tags=$c(t.tags,e),n.push(t);}return n}return []}function $c(t,e){if(e.removeAllProperties)return {};const n={...t||{}};if(e.removeProperties)for(const t of e.removeProperties)delete n[t];if(e.addOrUpdateProperties)for(const{key:t,value:r}of e.addOrUpdateProperties)n[t]=r;return n}!function(t){t[t.X=0]="X",t[t.Y=1]="Y";}(_c||(_c={}));const Rc={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:t=>t};class Nc{constructor(t){this.options=Object.assign(Object.create(Rc),t),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[],this.points=[];}load(t){const e=[];for(const n of t){if(!n.geometry)continue;const[t,r]=n.geometry.coordinates,[i,s]=[dc(t),yc(r)];e.push({id:n.id,type:"Point",geometry:[i,s],tags:n.properties});}this.createIndex(e);}initialize(t){const e=[];for(const n of t)"Point"===n.type&&e.push(n);this.createIndex(e);}updateIndex(t,e,n){this.options=Object.assign(Object.create(Rc),n.clusterOptions),this.initialize(t);}createIndex(t){const{log:e,minZoom:n,maxZoom:r}=this.options;e&&console.time("total time");const i=`prepare ${t.length} points`;e&&console.time(i),this.points=t;const s=[];for(let e=0;e=n;t--){const n=Date.now();o=this.trees[t]=this.createTree(this.cluster(o,t)),e&&console.log("z%d: %d clusters in %dms",t,o.numItems,Date.now()-n);}e&&console.timeEnd("total time");}getClusters(t,e){return this.getClustersInternal(t,e).map((t=>mc(t)))}getClustersInternal(t,e){let n=((t[0]+180)%360+360)%360-180;const r=Math.max(-90,Math.min(90,t[1]));let i=180===t[2]?180:((t[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,t[3]));if(t[2]-t[0]>=360)n=-180,i=180;else if(n>i){const t=this.getClustersInternal([n,r,180,s],e),o=this.getClustersInternal([-180,r,i,s],e);return t.concat(o)}const o=this.trees[this.limitZoom(e)],a=o.range(dc(n),yc(s),dc(i),yc(r)),l=o.flatData,u=[];for(const t of a){const e=this.stride*t;u.push(l[e+5]>1?Uc(l,e,this.clusterProps):this.points[l[e+3]]);}return u}getChildren(t){const e=this.getOriginId(t),n=this.getOriginZoom(t),r=new Error("No cluster with the specified id: "+t),i=this.trees[n];if(!i)throw r;const s=i.flatData;if(e*this.stride>=s.length)throw r;const o=this.options.radius/(this.options.extent*Math.pow(2,n-1)),a=i.within(s[e*this.stride],s[e*this.stride+1],o),l=[];for(const e of a){const n=e*this.stride;s[n+4]===t&&l.push(s[n+5]>1?jc(s,n,this.clusterProps):mc(this.points[s[n+3]]));}if(0===l.length)throw r;return l}getLeaves(t,e,n){const r=[];return this.appendLeaves(r,t,e=e||10,n=n||0,0),r}getTile(t,e,n){const r=this.trees[this.limitZoom(t)];if(!r)return null;const i=Math.pow(2,t),{extent:s,radius:o}=this.options,a=o/s,l=(n-a)/i,u=(n+1+a)/i,c={transformed:!0,features:[],source:null,x:e,y:n,z:t};return this.addTileFeatures(r.range((e-a)/i,l,(e+1+a)/i,u),r.flatData,e,n,i,c),0===e&&this.addTileFeatures(r.range(1-a/i,l,1,u),r.flatData,i,n,i,c),e===i-1&&this.addTileFeatures(r.range(0,l,a/i,u),r.flatData,-1,n,i,c),c}getClusterExpansionZoom(t){return this.getOriginZoom(t)}appendLeaves(t,e,n,r,i){const s=this.getChildren(e);for(const e of s){const s=e.properties;if(s?.cluster?i+s.point_count<=r?i+=s.point_count:i=this.appendLeaves(t,s.cluster_id,n,r,i):i1;let l,u,c;if(a)l=qc(e,t,this.clusterProps),u=e[t],c=e[t+1];else {const n=this.points[e[t+3]];l=n.tags,[u,c]=n.geometry;}const h={type:1,geometry:[[Math.round(this.options.extent*(u*i-n)),Math.round(this.options.extent*(c*i-r))]],tags:l};let p;p=a||this.options.generateId?e[t+3]:this.points[e[t+3]].id,void 0!==p&&(h.id=p),s.features.push(h);}}limitZoom(t){return Math.max(this.options.minZoom,Math.min(Math.floor(+t),this.options.maxZoom+1))}cluster(t,e){const{radius:n,extent:r,reduce:i,minPoints:s}=this.options,o=n/(r*Math.pow(2,e)),a=t.flatData,l=[],u=this.stride;for(let n=0;ne&&(f+=a[n+5]);}if(f>p&&f>=s){let t,s=r*p,o=c*p,d=-1;const y=(n/u<<5)+(e+1)+this.points.length;for(const r of h){const l=r*u;if(a[l+2]<=e)continue;a[l+2]=e;const c=a[l+5];s+=a[l]*c,o+=a[l+1]*c,a[l+4]=y,i&&(t||(t=this.map(a,n,!0),d=this.clusterProps.length,this.clusterProps.push(t)),i(t,this.map(a,l)));}a[n+4]=y,l.push(s/f,o/f,1/0,y,-1,f),i&&l.push(d);}else {for(let t=0;t1)for(const t of h){const n=t*u;if(!(a[n+2]<=e)){a[n+2]=e;for(let t=0;t>5}getOriginZoom(t){return (t-this.points.length)%32}map(t,e,n){if(t[e+5]>1){const r=this.clusterProps[t[e+6]];return n?Object.assign({},r):r}const r=this.points[t[e+3]].tags,i=this.options.map(r);return n&&i===r?Object.assign({},i):i}}function Uc(t,e,n){return {id:t[e+3],type:"Point",tags:qc(t,e,n),geometry:[t[e],t[e+1]]}}function jc(t,e,n){return {type:"Feature",id:t[e+3],properties:qc(t,e,n),geometry:{type:"Point",coordinates:[bc(t[e]),wc(t[e+1])]}}}function qc(t,e,n){const r=t[e+5],i=r>=1e4?`${Math.round(r/1e3)}k`:r>=1e3?Math.round(r/100)/10+"k":r,s=t[e+6],o=-1===s?{}:Object.assign({},n[s]);return Object.assign(o,{cluster:!0,cluster_id:t[e+3],point_count:r,point_count_abbreviated:i})}const Gc="geojsonvt_clip_start",Xc="geojsonvt_clip_end";function Yc(t,e,n,r,i){const s=e===i.maxZoom?0:i.tolerance/((1<0&&e.size<(i?o:r))return void(n.numPoints+=e.length/3);const a=[];for(let t=0;to)&&(n.numSimplified++,a.push(e[t],e[t+1])),n.numPoints++;i&&function(t,e){let n=0;for(let e=0,r=t.length,i=r-2;e0===e)for(let e=0,n=t.length;e1&&(console.log("invalidating tiles"),console.time("invalidating")),this.invalidateTiles(e),n.debug>1&&console.timeEnd("invalidating");const[r,i,s]=[0,0,0],o=Yc(t,r,i,s,n);o.source=t;const a=eh(r,i,s);if(this.tiles[a]=o,this.tileCoords.push({z:r,x:i,y:s,id:a}),n.debug){const t=`z${r}`;this.stats[t]=(this.stats[t]||0)+1,this.total++;}}getClusterExpansionZoom(t){return null}getChildren(t){return null}getLeaves(t,e,n){return null}getTile(t,e,n){const{extent:r,debug:i}=this.options,s=1<1&&console.log("drilling down to z%d-%d-%d",t,e,n);let a,l=t,u=e,c=n;for(;!a&&l>0;)l--,u>>=1,c>>=1,a=this.tiles[eh(l,u,c)];return a?.source?(i>1&&(console.log("found parent tile z%d-%d-%d",l,u,c),console.time("drilling down")),this.splitTile(a.source,l,u,c,t,e,n),i>1&&console.timeEnd("drilling down"),this.tiles[o]?Wc(this.tiles[o],r):null):null}splitTile(t,e,n,r,i,s,o){const a=[t,e,n,r],l=this.options,u=l.debug;for(;a.length;){r=a.pop(),n=a.pop(),e=a.pop(),t=a.pop();const c=1<1&&console.time("creation"),p=this.tiles[h]=Yc(t,e,n,r,l),this.tileCoords.push({z:e,x:n,y:r,id:h}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,n,r,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));const t=`z${e}`;this.stats[t]=(this.stats[t]||0)+1,this.total++;}if(p.source=t,null==i){if(e===l.indexMaxZoom||p.numPoints<=l.indexMaxPoints)continue}else {if(e===l.maxZoom||e===i)continue;if(null!=i){const t=i-e;if(n!==s>>t||r!==o>>t)continue}}if(p.source=null,!t.length)continue;u>1&&console.time("clipping");const f=.5*l.buffer/l.extent,d=.5-f,y=.5+f,m=1+f;let g=null,x=null,v=null,b=null;const w=Sc(t,c,n-f,n+y,_c.X,p.minX,p.maxX,l),_=Sc(t,c,n+d,n+m,_c.X,p.minX,p.maxX,l);w&&(g=Sc(w,c,r-f,r+y,_c.Y,p.minY,p.maxY,l),x=Sc(w,c,r+d,r+m,_c.Y,p.minY,p.maxY,l)),_&&(v=Sc(_,c,r-f,r+y,_c.Y,p.minY,p.maxY,l),b=Sc(_,c,r+d,r+m,_c.Y,p.minY,p.maxY,l)),u>1&&console.timeEnd("clipping"),a.push(g||[],e+1,2*n,2*r),a.push(x||[],e+1,2*n,2*r+1),a.push(v||[],e+1,2*n+1,2*r),a.push(b||[],e+1,2*n+1,2*r+1);}}invalidateTiles(t){if(!t.length)return;const e=this.options,{debug:n}=e;let r=1/0,i=-1/0,s=1/0,o=-1/0;for(const e of t)r=Math.min(r,e.minX),i=Math.max(i,e.maxX),s=Math.min(s,e.minY),o=Math.max(o,e.maxY);const a=e.buffer/e.extent,l=new Set;for(const e in this.tiles){const u=this.tiles[e],c=1<=p||o=d)continue;let y=!1;for(const e of t)if(e.maxX>=h&&e.minX=f&&e.minY1&&console.log("invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",u.z,u.x,u.y,u.numFeatures,u.numPoints,u.numSimplified);const t=`z${u.z}`;this.stats[t]=(this.stats[t]||0)-1,this.total--;}delete this.tiles[e],l.add(e);}}l.size&&(this.tileCoords=this.tileCoords.filter((t=>!l.has(t.id))));}}function eh(t,e,n){return 32*((1<t.id)),this.index=t.index,this.hasDependencies=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Ho,this.layoutVertexArray2=new Wo,this.indexArray=new ia,this.programConfigurations=new Oa(t.layers,t.zoom),this.segments=new la,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,n){this.hasDependencies=jl("line",this.layers,e)||this.hasLineDasharray(this.layers);const r=this.layers[0].layout.get("line-sort-key"),i=!r.isConstant(),s=[];for(const{feature:e,id:o,index:a,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=qa(e,t);if(!this.layers[0]._featureFilter.filter(new Bs(this.zoom),u,n))continue;const c=i?r.evaluate(u,{},n):void 0,h={id:o,properties:e.properties,type:e.type,sourceLayerIndex:l,index:a,geometry:t?u.geometry:ja(e),patterns:{},dashes:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of s){const{geometry:i,index:s,sourceLayerIndex:o}=r;this.hasDependencies?(jl("line",this.layers,e)?ql("line",this.layers,r,{zoom:this.zoom},e):this.hasLineDasharray(this.layers)&&this.addLineDashDependencies(this.layers,r,this.zoom,e),this.patternFeatures.push(r)):this.addFeature(r,i,s,n,{},{},e.subdivisionGranularity),e.featureIndex.insert(t[s].feature,i,s,o,this.index);}}update(t,e,n,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:n,dashPositions:r});}addFeatures(t,e,n,r){for(const i of this.patternFeatures)this.addFeature(i,i.geometry,i.index,e,n,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,oh)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ih),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,Gc)&&Object.prototype.hasOwnProperty.call(t.properties,Xc))return {start:+t.properties[Gc],end:+t.properties[Xc]}}addFeature(t,e,n,r,i,s,o){const a=this.layers[0].layout,l=a.get("line-join").evaluate(t,{}),u=a.get("line-cap").evaluate(t,{}),c=a.get("line-miter-limit").evaluate(t,{}),h=a.get("line-round-limit").evaluate(t,{});this.lineClips=this.lineFeatureClips(t);for(const n of e)this.addLine(n,t,l,u,c,h,r,o);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,n,{imagePositions:i,dashPositions:s,canonical:r});}addLine(t,e,n,r,i,s,o,a){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=_u(t,o?a.line.getGranularityForZoomLevel(o.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?n:l?"butt":r;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)o=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();o._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,o,0,0,p),this.addCurrentVertex(f,o.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,n=_?0:t;if(d&&this.addCurrentVertex(f,m,e,n,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,n,r,i,s=!1){const o=e.y*r-e.x,a=-e.y-e.x*r;this.addHalfVertex(t,e.x+e.y*n,e.y-e.x*n,s,!1,n,i),this.addHalfVertex(t,o,a,s,!0,-r,i),this.distance>lh/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,n,r,i,s));}addHalfVertex({x:t,y:e},n,r,i,s,o,a){const l=.5*(this.lineClips?this.scaledDistance*(lh-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*n)+128,Math.round(63*r)+128,1+(0===o?0:o<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=a.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),a.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}hasLineDasharray(t){for(const e of t){const t=e.paint.get("line-dasharray");if(t&&!t.isConstant())return !0}return !1}addLineDashDependencies(t,e,n,r){for(const i of t){const t=i.paint.get("line-dasharray");if(!t||"constant"===t.value.kind)continue;const s="round"===i.layout.get("line-cap").evaluate(e,{}),o={dasharray:t.value.evaluate({zoom:n-1},e,{}),round:s},a={dasharray:t.value.evaluate({zoom:n},e,{}),round:s},l={dasharray:t.value.evaluate({zoom:n+1},e,{}),round:s},u=`${o.dasharray.join(",")},${o.round}`,c=`${a.dasharray.join(",")},${a.round}`,h=`${l.dasharray.join(",")},${l.round}`;r.dashDependencies[u]=o,r.dashDependencies[c]=a,r.dashDependencies[h]=l,e.dashes[i.id]={min:u,mid:c,max:h};}}}let ch,hh;fs("LineBucket",uh,{omit:["layers","patternFeatures"]});var ph={get paint(){return hh=hh||new Ws({"line-opacity":new Xs(bt.paint_line["line-opacity"]),"line-color":new Xs(bt.paint_line["line-color"]),"line-translate":new Gs(bt.paint_line["line-translate"]),"line-translate-anchor":new Gs(bt.paint_line["line-translate-anchor"]),"line-width":new Xs(bt.paint_line["line-width"]),"line-gap-width":new Xs(bt.paint_line["line-gap-width"]),"line-offset":new Xs(bt.paint_line["line-offset"]),"line-blur":new Xs(bt.paint_line["line-blur"]),"line-dasharray":new Ys(bt.paint_line["line-dasharray"]),"line-pattern":new Ys(bt.paint_line["line-pattern"]),"line-gradient":new Hs(bt.paint_line["line-gradient"])})},get layout(){return ch=ch||new Ws({"line-cap":new Xs(bt.layout_line["line-cap"]),"line-join":new Xs(bt.layout_line["line-join"]),"line-miter-limit":new Xs(bt.layout_line["line-miter-limit"]),"line-round-limit":new Xs(bt.layout_line["line-round-limit"]),"line-sort-key":new Xs(bt.layout_line["line-sort-key"])})}};class fh extends Xs{possiblyEvaluate(t,e){return e=new Bs(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,n,r){return e=O({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,n,r)}}let dh;class yh extends Qs{constructor(t,e){super(t,ph,e),this.gradientVersion=0,dh||(dh=new fh(ph.paint.properties["line-width"].specification),dh.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof un,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=dh.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new uh(t)}queryRadius(t){const e=t,n=mh(sl("line-width",this,e),sl("line-gap-width",this,e)),r=sl("line-offset",this,e);return n/2+Math.abs(r)+ol(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:i,transform:s,pixelsToTileUnits:o}){const a=al(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,o),l=o/2*mh(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),u=this.paint.get("line-offset").evaluate(e,r);return u&&(i=function(t,e){const r=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const gh=oo([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),xh=oo([{name:"a_projected_pos",components:3,type:"Float32"}],4);oo([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const vh=oo([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);oo([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const bh=oo([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),wh=oo([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function _h(t,e,n){return t.sections.forEach((t=>{t.text=function(t,e,n){const r=e.layout.get("text-transform").evaluate(n,{});return "uppercase"===r?t=t.toLocaleUpperCase():"lowercase"===r&&(t=t.toLocaleLowerCase()),zs.applyArabicShaping&&(t=zs.applyArabicShaping(t)),t}(t.text,e,n);})),t}oo([{name:"triangle",components:3,type:"Uint16"}]),oo([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),oo([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),oo([{type:"Float32",name:"offsetX"}]),oo([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),oo([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);var Sh=24;const Ah={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","⋯":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"},Mh={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},kh={40:!0};function Ih(t,e,n,r,i,s){if("fontStack"in e){const r=n[e.fontStack],s=r&&r[t];return s?s.metrics.advance*e.scale+i:0}{const t=r[e.imageName];return t?t.displaySize[0]*e.scale*Sh/s+i:0}}function Eh(t,e,n,r){const i=Math.pow(t-e,2);return r?tMath.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,n=0;for(let r=0;rn)));}addImageSection(t){const e=t.image?t.image.name:"";if(0===e.length)return void q("Can't add FormattedSection with an empty image.");const n=this.getNextImageSectionCharCode();n?(this.text+=String.fromCharCode(n),this.sections.push({scale:1,verticalAlign:t.verticalAlign||"bottom",imageName:e}),this.sectionIndex.push(this.sections.length-1)):q("Reached maximum number of images 6401");}getNextImageSectionCharCode(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}determineLineBreaks(t,e,n,r,i){const s=[],o=this.determineAverageLineWidth(t,e,n,r,i),a=this.hasZeroWidthSpaces();let l=0,u=0;const c=this.text[Symbol.iterator]();let h=c.next();const p=this.text[Symbol.iterator]();p.next();let f=p.next();const d=this.text[Symbol.iterator]();d.next(),d.next();let y=d.next();for(;!h.done;){const e=this.getSection(u),m=h.value.codePointAt(0);if(_s(m)||(l+=Ih(m,e,n,r,t,i)),!f.done){const t=bs(m),n=f.value.codePointAt(0);(Mh[m]||t||"imageName"in e||!y.done&&kh[n])&&s.push(Fh(u+1,l,o,s,Th(m,n,t&&a),!1));}u++,h=c.next(),f=p.next(),y=d.next();}return Ph(Fh(this.length(),l,o,s,0,!0))}determineAverageLineWidth(t,e,n,r,i){let s=0,o=0;for(const e of this.text){const a=this.getSection(o);s+=Ih(e.codePointAt(0),a,n,r,t,i),o++;}return s/Math.max(1,Math.ceil(s/e))}}const zh=4294967296,Bh=1/zh,Ch="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class Vh{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,n=this.length){for(;this.pos>3,i=this.pos;this.type=7&n,t(r,e,this),this.pos===i&&this.skip(n);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*zh;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*zh;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let n,r;return r=e[this.pos++],n=127&r,r<128?n:(r=e[this.pos++],n|=(127&r)<<7,r<128?n:(r=e[this.pos++],n|=(127&r)<<14,r<128?n:(r=e[this.pos++],n|=(127&r)<<21,r<128?n:(r=e[this.pos],n|=(15&r)<<28,function(t,e,n){const r=n.buf;let i,s;if(s=r[n.pos++],i=(112&s)>>4,s<128)return Lh(t,i,e);if(s=r[n.pos++],i|=(127&s)<<3,s<128)return Lh(t,i,e);if(s=r[n.pos++],i|=(127&s)<<10,s<128)return Lh(t,i,e);if(s=r[n.pos++],i|=(127&s)<<17,s<128)return Lh(t,i,e);if(s=r[n.pos++],i|=(127&s)<<24,s<128)return Lh(t,i,e);if(s=r[n.pos++],i|=(1&s)<<31,s<128)return Lh(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(n,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Ch?Ch.decode(this.buf.subarray(e,t)):function(t,e,n){let r="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>n)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],o=t[i+2],128==(192&s)&&128==(192&o)&&(l=(15&e)<<12|(63&s)<<6|63&o,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],o=t[i+2],a=t[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(l=(15&e)<<18|(63&s)<<12|(63&o)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,r+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),r+=String.fromCharCode(l),i+=u;}return r}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const n=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let n,r;if(t>=0?(n=t%4294967296|0,r=t/4294967296|0):(n=~(-t%4294967296),r=~(-t/4294967296),4294967295^n?n=n+1|0:(n=0,r=r+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,n){n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,n.buf[n.pos]=127&(t>>>=7);}(n,0,e),function(t,e){const n=(7&t)<<4;e.buf[e.pos++]|=n|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(r,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));}writeSVarint(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,n){for(let r,i,s=0;s55295&&r<57344){if(!i){r>56319||s+1===e.length?(t[n++]=239,t[n++]=191,t[n++]=189):i=r;continue}if(r<56320){t[n++]=239,t[n++]=191,t[n++]=189,i=r;continue}r=i-55296<<10|r-56320|65536,i=null;}else i&&(t[n++]=239,t[n++]=191,t[n++]=189,i=null);r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:(r<65536?t[n++]=r>>12|224:(t[n++]=r>>18|240,t[n++]=r>>12&63|128),t[n++]=r>>6&63|128),t[n++]=63&r|128);}return n}(this.buf,t,this.pos);const n=this.pos-e;n>=128&&Oh(e,n,this),this.pos=e-1,this.writeVarint(n),this.pos+=n;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let n=0;n=128&&Oh(n,r,this),this.pos=n-1,this.writeVarint(r),this.pos+=r;}writeMessage(t,e,n){this.writeTag(t,2),this.writeRawMessage(e,n);}writePackedVarint(t,e){e.length&&this.writeMessage(t,$h,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,Rh,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,jh,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,Nh,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,Uh,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,qh,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,Gh,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,Xh,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,Yh,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function Lh(t,e,n){return n?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Oh(t,e,n){const r=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));n.realloc(r);for(let e=n.pos-1;e>=t;e--)n.buf[e+r]=n.buf[e];}function $h(t,e){for(let n=0;ne.h-t.h));const r=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),n),h:1/0}];let i=0,s=0;for(const e of t)for(let t=r.length-1;t>=0;t--){const n=r[t];if(!(e.w>n.w||e.h>n.h)){if(e.x=n.x,e.y=n.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===n.w&&e.h===n.h){const e=r.pop();e&&tm.toCodeUnitIndex(t)));const t=v(m.toString(),x);for(const e of t){const t=[...e].map((()=>0));g.push(new Dh(e,m.sections,t));}}else if(b){g=[],x=x.map((t=>m.toCodeUnitIndex(t)));let t=0;const e=[];for(const n of m.text)e.push(...Array(n.length).fill(m.sectionIndex[t])),t++;const n=b(m.text,e,x);for(const t of n){const e=[];let n="";for(const r of t[0])e.push(t[1][n.length]),n+=r;g.push(new Dh(t[0],m.sections,e));}}else g=function(t,e){const n=[];let r=0;for(const i of e)n.push(t.substring(r,i)),r=i;return ru){const t=Math.ceil(s/u);i*=t/o,o=t;}return {x1:r,y1:i,x2:r+s,y2:i+o}}function hp(t,e,n,r,i,s){const o=t.image;let a;if(o.content){const t=o.content,e=o.pixelRatio||1;a=[t[0]/e,t[1]/e,o.displaySize[0]-t[2]/e,o.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===n||"both"===n?(f=i[0]+l-r[3],h=i[0]+u+r[1]):(f=i[0]+(l+u-o.displaySize[0])/2,h=f+o.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===n||"both"===n?(c=i[1]+d-r[0],p=i[1]+y+r[2]):(c=i[1]+(d+y-o.displaySize[1])/2,p=c+o.displaySize[1]),{image:o,top:c,right:h,bottom:p,left:f,collisionPadding:a}}fs("ImagePosition",Jh),fs("ImageAtlas",Qh),t.aw=void 0,(tp=t.aw||(t.aw={}))[tp.none=0]="none",tp[tp.horizontal=1]="horizontal",tp[tp.vertical=2]="vertical",tp[tp.horizontalOnly=3]="horizontalOnly";const pp=128,fp=32640;function dp(t,e){const{expression:n}=e;if("constant"===n.kind)return {kind:"constant",layoutSize:n.evaluate(new Bs(t+1))};if("source"===n.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:r}=n;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasDependencies=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const n=this.layers[0]._unevaluatedLayout._values;this.textSizeData=dp(this.zoom,n["text-size"]),this.iconSizeData=dp(this.zoom,n["icon-size"]);const r=this.layers[0].layout,i=r.get("symbol-sort-key"),s=r.get("symbol-z-order");this.canOverlap="never"!==yp(r,"text-overlap","text-allow-overlap")||"never"!==yp(r,"icon-overlap","icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===r.get("symbol-placement")&&(this.writingModes=r.get("text-writing-mode").map((e=>t.aw[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new bp(new Oa(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new bp(new Oa(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new $o,this.lineVertexArray=new Ro,this.symbolInstances=new Oo,this.textAnchorOffsets=new Uo;}calculateGlyphDependencies(t,e,n,r,i){for(const s of t)if(e[s.codePointAt(0)]=!0,(n||r)&&i){const t=Ah[s];t&&(e[t.codePointAt(0)]=!0);}}populate(e,n,r){const i=this.layers[0],s=i.layout,o=s.get("text-font"),a=s.get("text-field"),l=s.get("icon-image"),u=("constant"!==a.value.kind||a.value.value instanceof De&&!a.value.value.isEmpty()||a.value.value.toString().length>0)&&("constant"!==o.value.kind||o.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=n.iconDependencies,f=n.glyphDependencies,d=n.availableImages,y=new Bs(this.zoom);for(const{feature:n,id:a,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=qa(n,e);if(!i._featureFilter.filter(y,g,r))continue;let x,v;if(e||(g.geometry=ja(n)),u){const t=i.getValueAndResolveTokens("text-field",g,r,d),e=De.factory(t),n=this.hasRTLText=this.hasRTLText||vp(e);(!n||"unavailable"===zs.getRTLTextPluginStatus()||n&&zs.isParsed())&&(x=_h(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,r,d);v=t instanceof $e?t:$e.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},r):void 0;if(this.features.push({id:a,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:n.properties,type:Bu.types[n.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=o.evaluate(g,{},r).join(","),n="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.aw.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const r=Ss(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,n,this.allowVerticalPlacement,r);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},n={},r=[];let i=0;function s(e){r.push(t[e]),i++;}function o(t,e,i){const s=n[t];return delete n[t],n[e]=s,r[s].geometry[0].pop(),r[s].geometry[0]=r[s].geometry[0].concat(i[0]),s}function a(t,n,i){const s=e[n];return delete e[n],e[t]=s,r[s].geometry[0].shift(),r[s].geometry[0]=i[0].concat(r[s].geometry[0]),s}function l(t,e,n){const r=n?e[0][e[0].length-1]:e[0][0];return `${t}:${r.x}:${r.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,n){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:n}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:n}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const n=this.lineVertexArray.length;if(void 0!==t.segment){let n=t.dist(e[t.segment+1]),r=t.dist(e[t.segment]);const i={};for(let r=t.segment+1;r=0;n--)i[n]={x:e[n].x,y:e[n].y,tileUnitDistanceFromAnchor:r},n>0&&(r+=e[n-1].dist(e[n]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const n=t.placedSymbolArray.get(e),r=n.vertexStartIndex+4*n.numGlyphs;for(let e=n.vertexStartIndex;er[t]-r[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const n=this.sortKeyRanges[this.sortKeyRanges.length-1];n&&n.sortKey===e?n.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,n)=>{t>=0&&n.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let Sp,Ap;fs("SymbolBucket",_p,{omit:["layers","collisionBoxArray","features","compareText"]}),_p.MAX_GLYPHS=65535,_p.addDynamicAttributes=xp;var Mp={get paint(){return Ap=Ap||new Ws({"icon-opacity":new Xs(bt.paint_symbol["icon-opacity"]),"icon-color":new Xs(bt.paint_symbol["icon-color"]),"icon-halo-color":new Xs(bt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Xs(bt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Xs(bt.paint_symbol["icon-halo-blur"]),"icon-translate":new Gs(bt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Gs(bt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Xs(bt.paint_symbol["text-opacity"]),"text-color":new Xs(bt.paint_symbol["text-color"],{runtimeType:Rt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Xs(bt.paint_symbol["text-halo-color"]),"text-halo-width":new Xs(bt.paint_symbol["text-halo-width"]),"text-halo-blur":new Xs(bt.paint_symbol["text-halo-blur"]),"text-translate":new Gs(bt.paint_symbol["text-translate"]),"text-translate-anchor":new Gs(bt.paint_symbol["text-translate-anchor"])})},get layout(){return Sp=Sp||new Ws({"symbol-placement":new Gs(bt.layout_symbol["symbol-placement"]),"symbol-spacing":new Gs(bt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Gs(bt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Xs(bt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Gs(bt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Gs(bt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Gs(bt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Gs(bt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Gs(bt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Gs(bt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Xs(bt.layout_symbol["icon-size"]),"icon-text-fit":new Gs(bt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Gs(bt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Xs(bt.layout_symbol["icon-image"]),"icon-rotate":new Xs(bt.layout_symbol["icon-rotate"]),"icon-padding":new Xs(bt.layout_symbol["icon-padding"]),"icon-keep-upright":new Gs(bt.layout_symbol["icon-keep-upright"]),"icon-offset":new Xs(bt.layout_symbol["icon-offset"]),"icon-anchor":new Xs(bt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Gs(bt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Gs(bt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Gs(bt.layout_symbol["text-rotation-alignment"]),"text-field":new Xs(bt.layout_symbol["text-field"]),"text-font":new Xs(bt.layout_symbol["text-font"]),"text-size":new Xs(bt.layout_symbol["text-size"]),"text-max-width":new Xs(bt.layout_symbol["text-max-width"]),"text-line-height":new Gs(bt.layout_symbol["text-line-height"]),"text-letter-spacing":new Xs(bt.layout_symbol["text-letter-spacing"]),"text-justify":new Xs(bt.layout_symbol["text-justify"]),"text-radial-offset":new Xs(bt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Gs(bt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Xs(bt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Xs(bt.layout_symbol["text-anchor"]),"text-max-angle":new Gs(bt.layout_symbol["text-max-angle"]),"text-writing-mode":new Gs(bt.layout_symbol["text-writing-mode"]),"text-rotate":new Xs(bt.layout_symbol["text-rotate"]),"text-padding":new Gs(bt.layout_symbol["text-padding"]),"text-keep-upright":new Gs(bt.layout_symbol["text-keep-upright"]),"text-transform":new Xs(bt.layout_symbol["text-transform"]),"text-offset":new Xs(bt.layout_symbol["text-offset"]),"text-allow-overlap":new Gs(bt.layout_symbol["text-allow-overlap"]),"text-overlap":new Gs(bt.layout_symbol["text-overlap"]),"text-ignore-placement":new Gs(bt.layout_symbol["text-ignore-placement"]),"text-optional":new Gs(bt.layout_symbol["text-optional"])})}};class kp{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}fs("FormatSectionOverride",kp,{omit:["defaultValue"]});class Ip extends Qs{constructor(t,e){super(t,Mp,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const n of t)e.indexOf(n)<0&&e.push(n);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,n,r){const i=this.layout.get(t).evaluate(e,{},n,r),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ri(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,n)=>t&&n in t?String(t[n]):""))}(e.properties,i)}createBucket(t){return new _p(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of Mp.paint.overridableProperties){if(!Ip.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),n=new kp(e),r=new ni(n,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new si("source",r):new oi("composite",r,e.value.zoomStops),this.paint._values[t]=new js(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,n){return !(!this.layout||e.isDataDriven()||n.isDataDriven())&&Ip.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const n=t.get("text-field"),r=Mp.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(r.overrides&&r.overrides.hasOverride(e))return void(i=!0)};if("constant"===n.value.kind&&n.value.value instanceof De)s(n.value.value.sections);else if("source"===n.value.kind||"composite"===n.value.kind){const t=e=>{i||(e instanceof Ge&&je(e.value)===Gt?s(e.value.sections):e instanceof Fn?s(e.sections):e.eachChild(t));},e=n.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let Ep;var Tp={get paint(){return Ep=Ep||new Ws({"background-color":new Gs(bt.paint_background["background-color"]),"background-pattern":new Zs(bt.paint_background["background-pattern"]),"background-opacity":new Gs(bt.paint_background["background-opacity"])})}};class Fp extends Qs{constructor(t,e){super(t,Tp,e);}}class Pp extends Qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class Dp{constructor(t){this._methodToThrottle=t,this._triggered=!1,this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();};}trigger(){var t;this._triggered||(this._triggered=!0,null===(t=this._channel)||void 0===t||t.port1.postMessage(!0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const zp={once:!0},Bp=6371008.8;class Cp{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Cp(L(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,n=this.lat*e,r=t.lat*e,i=Math.sin(n)*Math.sin(r)+Math.cos(n)*Math.cos(r)*Math.cos((t.lng-this.lng)*e);return Bp*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof Cp)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Cp(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Cp(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const Vp=2*Math.PI*Bp;function Lp(t){return Vp*Math.cos(t*Math.PI/180)}function Op(t){return (180+t)/360}function $p(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Rp(t,e){return t/Lp(e)}function Np(t){return 360*t-180}function Up(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function jp(t,e){return t*Lp(Up(e))}class qp{constructor(t,e,n=0){this.x=+t,this.y=+e,this.z=+n;}static fromLngLat(t,e=0){const n=Cp.convert(t);return new qp(Op(n.lng),$p(n.lat),Rp(e,n.lat))}toLngLat(){return new Cp(Np(this.x),Up(this.y))}toAltitude(){return jp(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/Vp*(t=Up(this.y),1/Math.cos(t*Math.PI/180));var t;}}function Gp(t,e,n){var r=2*Math.PI*6378137/256/Math.pow(2,n);return [t*r-2*Math.PI*6378137/2,e*r-2*Math.PI*6378137/2]}class Xp{constructor(t,e,n){if(!function(t,e,n){return !(t<0||t>25||n<0||n>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,n))throw new Error(`x=${e}, y=${n}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=n,this.key=Hp(0,t,t,e,n);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,n){const r=(s=this.y,o=this.z,a=Gp(256*(i=this.x),256*(s=Math.pow(2,o)-s-1),o),l=Gp(256*(i+1),256*(s+1),o),a[0]+","+a[1]+","+l[0]+","+l[1]);var i,s,o,a,l;const u=function(t,e,n){let r,i="";for(let s=t;s>0;s--)r=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,r)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new n((t.x*e-this.x)*T,(t.y*e-this.y)*T)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Yp{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Hp(t,e.z,e.z,e.x,e.y);}}class Zp{constructor(t,e,n,r,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${n}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Xp(n,+r,+i),this.key=Hp(e,t,n,r,i);}clone(){return new Zp(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new Zp(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Zp(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}isOverscaled(){return this.overscaledZ>this.canonical.z}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const n=this.canonical.z-t;return t>this.canonical.z?Hp(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Hp(this.wrap*+e,t,t,this.canonical.x>>n,this.canonical.y>>n)}isChildOf(t){if(t.wrap!==this.wrap)return !1;if(this.overscaledZ-t.overscaledZ<=0)return !1;if(0===t.overscaledZ)return this.overscaledZ>0;const e=this.canonical.z-t.canonical.z;return !(e<0)&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new Zp(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,n=2*this.canonical.x,r=2*this.canonical.y;return [new Zp(e,this.wrap,e,n,r),new Zp(e,this.wrap,e,n+1,r),new Zp(e,this.wrap,e,n,r+1),new Zp(e,this.wrap,e,n+1,r+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=0&&t=0&&e=l)return null;let c=this.canonical.x+r,h=this.wrap;return c<0?(h-=Math.ceil(-c/l),c=(c%l+l)%l):c>=l&&(h+=Math.floor(c/l),c%=l),{tileID:new Zp(this.overscaledZ,h,a,c,u),x:s,y:o}}}function Hp(t,e,n,r,i){(t*=2)<0&&(t=-1*t-1);const s=1<this.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Wp;return e.extend(t(new n(this.minX,this.minY))),e.extend(t(new n(this.maxX,this.minY))),e.extend(t(new n(this.minX,this.maxY))),e.extend(t(new n(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Wp;for(const n of t)e.extend(n);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Kp{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Jp{constructor(t,e,n,r,i){this.type="Feature",this._vectorTileFeature=t,this._x=n,this._y=r,this._z=e,this.properties=t.properties,this.id=i;}projectPoint(t,e,n,r){return [360*(t.x+e)/r-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+n)/r)*Math.PI))-90]}projectLine(t,e,n,r){return t.map((t=>this.projectPoint(t,e,n,r)))}get geometry(){if(this._geometry)return this._geometry;const t=this._vectorTileFeature,e=t.extent*Math.pow(2,this._z),n=t.extent*this._x,r=t.extent*this._y,i=t.loadGeometry();switch(t.type){case 1:{const t=[];for(const e of i)t.push(e[0]);const s=this.projectLine(t,n,r,e);this._geometry=1===t.length?{type:"Point",coordinates:s[0]}:{type:"MultiPoint",coordinates:s};break}case 2:{const t=i.map((t=>this.projectLine(t,n,r,e)));this._geometry=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};break}case 3:{const t=Vu(i),s=[];for(const i of t)s.push(i.map((t=>this.projectLine(t,n,r,e))));this._geometry=1===s.length?{type:"Polygon",coordinates:s[0]}:{type:"MultiPolygon",coordinates:s};break}default:throw new Error(`unknown feature type: ${t.type}`)}return this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&"_x"!==e&&"_y"!==e&&"_z"!==e&&(t[e]=this[e]);return t}}class Qp{constructor(t,e,n){this._name=t,this.dataBuffer=e,"number"==typeof n?this._size=n:(this.nullabilityBuffer=n,this._size=n.size());}getValue(t){return this.nullabilityBuffer&&!this.nullabilityBuffer.get(t)?null:this.getValueFromBuffer(t)}has(t){return this.nullabilityBuffer?.get(t)||!this.nullabilityBuffer}get name(){return this._name}get size(){return this._size}}class tf extends Qp{}class ef extends tf{getValueFromBuffer(t){return this.dataBuffer[t]}}class nf extends tf{getValueFromBuffer(t){return this.dataBuffer[t]}}class rf extends Qp{constructor(t,e,n,r){super(t,e,r),this.delta=n;}}class sf extends rf{constructor(t,e,n,r){super(t,Int32Array.of(e),n,r);}getValueFromBuffer(t){return this.dataBuffer[0]+t*this.delta}}class of extends Qp{constructor(t,e,n,r){super(t,r?Int32Array.of(e):Uint32Array.of(e),n);}getValueFromBuffer(t){return this.dataBuffer[0]}}class af{constructor(t,e,n,r,i=4096){this._name=t,this._geometryVector=e,this._idVector=n,this._propertyVectors=r,this._extent=i;}get name(){return this._name}get idVector(){return this._idVector}get geometryVector(){return this._geometryVector}get propertyVectors(){return this._propertyVectors}getPropertyVector(t){return this.propertyVectorsMap||(this.propertyVectorsMap=new Map(this._propertyVectors.map((t=>[t.name,t])))),this.propertyVectorsMap.get(t)}get numFeatures(){return this.geometryVector.numGeometries}get extent(){return this._extent}getFeatures(){const t=[],e=this.geometryVector.getGeometries();for(let n=0;n>>32-t;const pf=hf,ff=256;function df(t,e){return t-t%e}function yf(t){const e=t>>>0;return ((255&e)<<24|(65280&e)<<8|e>>>8&65280|e>>>24&255)>>>0}const mf=function(){if(!Number.isFinite(65536))return 65536;const t=df(Math.floor(65536),ff);return 0===t?ff:t}(),gf=3*mf/ff+mf|0;function xf(){const t=new Uint8Array(gf);return {dataToBePacked:new Array(33),dataPointers:new Int32Array(33),byteContainer:t,byteContainerI32:new Int32Array(t.buffer,t.byteOffset,t.byteLength>>>2),exceptionSizes:new Int32Array(33)}}function vf(t,e,n,r,i){switch(i){case 1:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0;n[i++]=e>>>0&1,n[i++]=e>>>1&1,n[i++]=e>>>2&1,n[i++]=e>>>3&1,n[i++]=e>>>4&1,n[i++]=e>>>5&1,n[i++]=e>>>6&1,n[i++]=e>>>7&1,n[i++]=e>>>8&1,n[i++]=e>>>9&1,n[i++]=e>>>10&1,n[i++]=e>>>11&1,n[i++]=e>>>12&1,n[i++]=e>>>13&1,n[i++]=e>>>14&1,n[i++]=e>>>15&1,n[i++]=e>>>16&1,n[i++]=e>>>17&1,n[i++]=e>>>18&1,n[i++]=e>>>19&1,n[i++]=e>>>20&1,n[i++]=e>>>21&1,n[i++]=e>>>22&1,n[i++]=e>>>23&1,n[i++]=e>>>24&1,n[i++]=e>>>25&1,n[i++]=e>>>26&1,n[i++]=e>>>27&1,n[i++]=e>>>28&1,n[i++]=e>>>29&1,n[i++]=e>>>30&1,n[i++]=e>>>31&1;}}(t,e,n,r);break;case 2:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0;n[i++]=e>>>0&3,n[i++]=e>>>2&3,n[i++]=e>>>4&3,n[i++]=e>>>6&3,n[i++]=e>>>8&3,n[i++]=e>>>10&3,n[i++]=e>>>12&3,n[i++]=e>>>14&3,n[i++]=e>>>16&3,n[i++]=e>>>18&3,n[i++]=e>>>20&3,n[i++]=e>>>22&3,n[i++]=e>>>24&3,n[i++]=e>>>26&3,n[i++]=e>>>28&3,n[i++]=e>>>30&3,n[i++]=r>>>0&3,n[i++]=r>>>2&3,n[i++]=r>>>4&3,n[i++]=r>>>6&3,n[i++]=r>>>8&3,n[i++]=r>>>10&3,n[i++]=r>>>12&3,n[i++]=r>>>14&3,n[i++]=r>>>16&3,n[i++]=r>>>18&3,n[i++]=r>>>20&3,n[i++]=r>>>22&3,n[i++]=r>>>24&3,n[i++]=r>>>26&3,n[i++]=r>>>28&3,n[i++]=r>>>30&3;}}(t,e,n,r);break;case 3:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0;n[i++]=e>>>0&7,n[i++]=e>>>3&7,n[i++]=e>>>6&7,n[i++]=e>>>9&7,n[i++]=e>>>12&7,n[i++]=e>>>15&7,n[i++]=e>>>18&7,n[i++]=e>>>21&7,n[i++]=e>>>24&7,n[i++]=e>>>27&7,n[i++]=7&(e>>>30|(1&r)<<2),n[i++]=r>>>1&7,n[i++]=r>>>4&7,n[i++]=r>>>7&7,n[i++]=r>>>10&7,n[i++]=r>>>13&7,n[i++]=r>>>16&7,n[i++]=r>>>19&7,n[i++]=r>>>22&7,n[i++]=r>>>25&7,n[i++]=r>>>28&7,n[i++]=7&(r>>>31|(3&o)<<1),n[i++]=o>>>2&7,n[i++]=o>>>5&7,n[i++]=o>>>8&7,n[i++]=o>>>11&7,n[i++]=o>>>14&7,n[i++]=o>>>17&7,n[i++]=o>>>20&7,n[i++]=o>>>23&7,n[i++]=o>>>26&7,n[i++]=o>>>29&7;}}(t,e,n,r);break;case 4:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0,a=t[s++]>>>0;n[i++]=e>>>0&15,n[i++]=e>>>4&15,n[i++]=e>>>8&15,n[i++]=e>>>12&15,n[i++]=e>>>16&15,n[i++]=e>>>20&15,n[i++]=e>>>24&15,n[i++]=e>>>28&15,n[i++]=r>>>0&15,n[i++]=r>>>4&15,n[i++]=r>>>8&15,n[i++]=r>>>12&15,n[i++]=r>>>16&15,n[i++]=r>>>20&15,n[i++]=r>>>24&15,n[i++]=r>>>28&15,n[i++]=o>>>0&15,n[i++]=o>>>4&15,n[i++]=o>>>8&15,n[i++]=o>>>12&15,n[i++]=o>>>16&15,n[i++]=o>>>20&15,n[i++]=o>>>24&15,n[i++]=o>>>28&15,n[i++]=a>>>0&15,n[i++]=a>>>4&15,n[i++]=a>>>8&15,n[i++]=a>>>12&15,n[i++]=a>>>16&15,n[i++]=a>>>20&15,n[i++]=a>>>24&15,n[i++]=a>>>28&15;}}(t,e,n,r);break;case 5:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0,a=t[s++]>>>0,l=t[s++]>>>0;n[i++]=e>>>0&31,n[i++]=e>>>5&31,n[i++]=e>>>10&31,n[i++]=e>>>15&31,n[i++]=e>>>20&31,n[i++]=e>>>25&31,n[i++]=31&(e>>>30|(7&r)<<2),n[i++]=r>>>3&31,n[i++]=r>>>8&31,n[i++]=r>>>13&31,n[i++]=r>>>18&31,n[i++]=r>>>23&31,n[i++]=31&(r>>>28|(1&o)<<4),n[i++]=o>>>1&31,n[i++]=o>>>6&31,n[i++]=o>>>11&31,n[i++]=o>>>16&31,n[i++]=o>>>21&31,n[i++]=o>>>26&31,n[i++]=31&(o>>>31|(15&a)<<1),n[i++]=a>>>4&31,n[i++]=a>>>9&31,n[i++]=a>>>14&31,n[i++]=a>>>19&31,n[i++]=a>>>24&31,n[i++]=31&(a>>>29|(3&l)<<3),n[i++]=l>>>2&31,n[i++]=l>>>7&31,n[i++]=l>>>12&31,n[i++]=l>>>17&31,n[i++]=l>>>22&31,n[i++]=l>>>27&31;}}(t,e,n,r);break;case 6:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0,a=t[s++]>>>0,l=t[s++]>>>0,u=t[s++]>>>0;n[i++]=e>>>0&63,n[i++]=e>>>6&63,n[i++]=e>>>12&63,n[i++]=e>>>18&63,n[i++]=e>>>24&63,n[i++]=63&(e>>>30|(15&r)<<2),n[i++]=r>>>4&63,n[i++]=r>>>10&63,n[i++]=r>>>16&63,n[i++]=r>>>22&63,n[i++]=63&(r>>>28|(3&o)<<4),n[i++]=o>>>2&63,n[i++]=o>>>8&63,n[i++]=o>>>14&63,n[i++]=o>>>20&63,n[i++]=o>>>26&63,n[i++]=a>>>0&63,n[i++]=a>>>6&63,n[i++]=a>>>12&63,n[i++]=a>>>18&63,n[i++]=a>>>24&63,n[i++]=63&(a>>>30|(15&l)<<2),n[i++]=l>>>4&63,n[i++]=l>>>10&63,n[i++]=l>>>16&63,n[i++]=l>>>22&63,n[i++]=63&(l>>>28|(3&u)<<4),n[i++]=u>>>2&63,n[i++]=u>>>8&63,n[i++]=u>>>14&63,n[i++]=u>>>20&63,n[i++]=u>>>26&63;}}(t,e,n,r);break;case 7:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0,a=t[s++]>>>0,l=t[s++]>>>0,u=t[s++]>>>0,c=t[s++]>>>0;n[i++]=e>>>0&127,n[i++]=e>>>7&127,n[i++]=e>>>14&127,n[i++]=e>>>21&127,n[i++]=127&(e>>>28|(7&r)<<4),n[i++]=r>>>3&127,n[i++]=r>>>10&127,n[i++]=r>>>17&127,n[i++]=r>>>24&127,n[i++]=127&(r>>>31|(63&o)<<1),n[i++]=o>>>6&127,n[i++]=o>>>13&127,n[i++]=o>>>20&127,n[i++]=127&(o>>>27|(3&a)<<5),n[i++]=a>>>2&127,n[i++]=a>>>9&127,n[i++]=a>>>16&127,n[i++]=a>>>23&127,n[i++]=127&(a>>>30|(31&l)<<2),n[i++]=l>>>5&127,n[i++]=l>>>12&127,n[i++]=l>>>19&127,n[i++]=127&(l>>>26|(1&u)<<6),n[i++]=u>>>1&127,n[i++]=u>>>8&127,n[i++]=u>>>15&127,n[i++]=u>>>22&127,n[i++]=127&(u>>>29|(15&c)<<3),n[i++]=c>>>4&127,n[i++]=c>>>11&127,n[i++]=c>>>18&127,n[i++]=c>>>25&127;}}(t,e,n,r);break;case 8:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<8;e++){const e=t[s++]>>>0,r=t[s++]>>>0,o=t[s++]>>>0,a=t[s++]>>>0,l=t[s++]>>>0,u=t[s++]>>>0,c=t[s++]>>>0,h=t[s++]>>>0;n[i++]=e>>>0&255,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=r>>>0&255,n[i++]=r>>>8&255,n[i++]=r>>>16&255,n[i++]=r>>>24&255,n[i++]=o>>>0&255,n[i++]=o>>>8&255,n[i++]=o>>>16&255,n[i++]=o>>>24&255,n[i++]=a>>>0&255,n[i++]=a>>>8&255,n[i++]=a>>>16&255,n[i++]=a>>>24&255,n[i++]=l>>>0&255,n[i++]=l>>>8&255,n[i++]=l>>>16&255,n[i++]=l>>>24&255,n[i++]=u>>>0&255,n[i++]=u>>>8&255,n[i++]=u>>>16&255,n[i++]=u>>>24&255,n[i++]=c>>>0&255,n[i++]=c>>>8&255,n[i++]=c>>>16&255,n[i++]=c>>>24&255,n[i++]=h>>>0&255,n[i++]=h>>>8&255,n[i++]=h>>>16&255,n[i++]=h>>>24&255;}}(t,e,n,r);break;case 16:!function(t,e,n,r){let i=r,s=e;for(let e=0;e<128;e++){const e=t[s++]>>>0;n[i++]=65535&e,n[i++]=e>>>16&65535;}}(t,e,n,r);break;default:!function(t,e,n,r,i){const s=pf[i]>>>0;let o=e,a=0,l=t[o]>>>0,u=r;for(let e=0;e<8;e++){for(let e=0;e<32;e++)if(a+i<=32)n[u+e]=l>>>a&s,a+=i,32===a&&(a=0,o++,31!==e&&(l=t[o]>>>0));else {const r=32-a,c=l>>>a;o++,l=t[o]>>>0;const h=i-r;n[u+e]=(c|(l&-1>>>32-h>>>0)<>>0);}}(t,e,n,r,i);}return e+(i<<3)|0}function bf(t,e,n,r){if(n+2>e)throw new Error(`FastPFOR decode: byteContainer underflow at block=${r} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${n}, byteSize=${e})`);const i=t[n++],s=t[n++];if(i>32)throw new Error(`FastPFOR decode: invalid bitWidth=${i} at block=${r} (expected 0..32). This likely indicates corrupted or truncated input.`);return {bitWidth:i,exceptionCount:s,bytePosIn:n}}function wf(t,e,n,r,i,s,o,a,l){const{maxBits:u,exceptionBitWidth:c,bytePosIn:h}=function(t,e,n,r,i,s){if(n+1>e)throw new Error(`FastPFOR decode: exception header underflow at block=${s} (need 1 byte for maxBits, bytePos=${n}, byteSize=${e})`);const o=t[n++];if(o32)throw new Error(`FastPFOR decode: invalid maxBits=${o} at block=${s} (bitWidth=${r}, expected ${r}..32)`);const a=o-r|0;if(a<1||a>32)throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${a} at block=${s} (bitWidth=${r}, maxBits=${o})`);if(n+i>e)throw new Error(`FastPFOR decode: exception positions underflow at block=${s} (need=${i}, have=${e-n})`);return {maxBits:o,exceptionBitWidth:a,bytePosIn:n}}(i,s,o,n,r,l);if(o=h,1===c){const s=1<y)throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${c} (ptr=${d}, need ${r}, size=${y}) at block ${l}`);for(let s=0;st.length-1)throw new Error(`FastPFOR decode: invalid whereMeta=${a} at pageStart=${o} (expected > 0 and pageStart+whereMeta < encoded.length=${t.length})`);const l=o+1|0,u=o+a|0,c=t[u]>>>0,h=c+3>>>2,p=u+1,f=p+h;if(f>=t.length)throw new Error(`FastPFOR decode: invalid byteSize=${c} (metaInts=${h}, pageStart=${o}, packedEnd=${u}, byteContainerStart=${p}) causes bitmapPos=${f} out of bounds (encoded.length=${t.length})`);const d=function(t,e,n,r){r.byteContainer.length>>2;if(3&i.byteOffset)for(let n=0;n>>8&255,i[s+2|0]=r>>>16&255,i[s+3|0]=r>>>24&255;}else {let n=r.byteContainerI32;(!n||n.buffer!==i.buffer||n.byteOffset!==i.byteOffset||n.length>>2)),n.set(t.subarray(e,e+s));}const o=3&n;if(o>0){const n=0|t[e+s|0],r=s<<2;for(let t=0;t>>(t<<3)&255;}return i}(t,p,c,s),y=c,m=function(t,e,n){const r=0|t[e++],i=n.dataToBePacked;for(let s=2;s<=32;s=s+1|0){if(!(r>>>s-1&1))continue;if(e>=t.length)throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${s}, streamWordIndex=${e}, needWords=1, availableWords=${t.length-e}, encodedWords=${t.length})`);const o=t[e++]>>>0,a=df(o+31,32),l=o*s+31>>>5;if(e+l>t.length)throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${s}, size=${o}, streamWordIndex=${e}, needWords=${l}, availableWords=${t.length-e}, encodedWords=${t.length})`);let u=i[s];(!u||u.length>>5)|0,n.exceptionSizes[s]=o;}return e}(t,f,s);return s.dataPointers.fill(0),function(t,e,n,r,i,s,o,a,l,u){let c=0|n,h=0;for(let e=0;e0&&(h=wf(i,p,r,o,a,l,h,u,e));}if(c!==r)throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${e}, packedStart=${n}, consumedPackedEnd=${c}, expectedPackedEnd=${r}, packedWords=${r-n}, encoded.length=${t.length})`)}(t,o,l,u,e,0|r,i/ff|0,d,y,s),m}function Sf(t,e,n,r,i){switch(i){case 2:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0;n[i++]=s>>>0&3,n[i++]=s>>>2&3,n[i++]=s>>>4&3,n[i++]=s>>>6&3,n[i++]=s>>>8&3,n[i++]=s>>>10&3,n[i++]=s>>>12&3,n[i++]=s>>>14&3,n[i++]=s>>>16&3,n[i++]=s>>>18&3,n[i++]=s>>>20&3,n[i++]=s>>>22&3,n[i++]=s>>>24&3,n[i++]=s>>>26&3,n[i++]=s>>>28&3,n[i++]=s>>>30&3,n[i++]=o>>>0&3,n[i++]=o>>>2&3,n[i++]=o>>>4&3,n[i++]=o>>>6&3,n[i++]=o>>>8&3,n[i++]=o>>>10&3,n[i++]=o>>>12&3,n[i++]=o>>>14&3,n[i++]=o>>>16&3,n[i++]=o>>>18&3,n[i++]=o>>>20&3,n[i++]=o>>>22&3,n[i++]=o>>>24&3,n[i++]=o>>>26&3,n[i++]=o>>>28&3,n[i]=o>>>30&3;}(t,e,n,r);case 3:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0;n[i++]=s>>>0&7,n[i++]=s>>>3&7,n[i++]=s>>>6&7,n[i++]=s>>>9&7,n[i++]=s>>>12&7,n[i++]=s>>>15&7,n[i++]=s>>>18&7,n[i++]=s>>>21&7,n[i++]=s>>>24&7,n[i++]=s>>>27&7,n[i++]=7&(s>>>30|(1&o)<<2),n[i++]=o>>>1&7,n[i++]=o>>>4&7,n[i++]=o>>>7&7,n[i++]=o>>>10&7,n[i++]=o>>>13&7,n[i++]=o>>>16&7,n[i++]=o>>>19&7,n[i++]=o>>>22&7,n[i++]=o>>>25&7,n[i++]=o>>>28&7,n[i++]=7&(o>>>31|(3&a)<<1),n[i++]=a>>>2&7,n[i++]=a>>>5&7,n[i++]=a>>>8&7,n[i++]=a>>>11&7,n[i++]=a>>>14&7,n[i++]=a>>>17&7,n[i++]=a>>>20&7,n[i++]=a>>>23&7,n[i++]=a>>>26&7,n[i]=a>>>29&7;}(t,e,n,r);case 4:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0;n[i++]=s>>>0&15,n[i++]=s>>>4&15,n[i++]=s>>>8&15,n[i++]=s>>>12&15,n[i++]=s>>>16&15,n[i++]=s>>>20&15,n[i++]=s>>>24&15,n[i++]=s>>>28&15,n[i++]=o>>>0&15,n[i++]=o>>>4&15,n[i++]=o>>>8&15,n[i++]=o>>>12&15,n[i++]=o>>>16&15,n[i++]=o>>>20&15,n[i++]=o>>>24&15,n[i++]=o>>>28&15,n[i++]=a>>>0&15,n[i++]=a>>>4&15,n[i++]=a>>>8&15,n[i++]=a>>>12&15,n[i++]=a>>>16&15,n[i++]=a>>>20&15,n[i++]=a>>>24&15,n[i++]=a>>>28&15,n[i++]=l>>>0&15,n[i++]=l>>>4&15,n[i++]=l>>>8&15,n[i++]=l>>>12&15,n[i++]=l>>>16&15,n[i++]=l>>>20&15,n[i++]=l>>>24&15,n[i]=l>>>28&15;}(t,e,n,r);case 5:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0;n[i++]=s>>>0&31,n[i++]=s>>>5&31,n[i++]=s>>>10&31,n[i++]=s>>>15&31,n[i++]=s>>>20&31,n[i++]=s>>>25&31,n[i++]=31&(s>>>30|(7&o)<<2),n[i++]=o>>>3&31,n[i++]=o>>>8&31,n[i++]=o>>>13&31,n[i++]=o>>>18&31,n[i++]=o>>>23&31,n[i++]=31&(o>>>28|(1&a)<<4),n[i++]=a>>>1&31,n[i++]=a>>>6&31,n[i++]=a>>>11&31,n[i++]=a>>>16&31,n[i++]=a>>>21&31,n[i++]=a>>>26&31,n[i++]=31&(a>>>31|(15&l)<<1),n[i++]=l>>>4&31,n[i++]=l>>>9&31,n[i++]=l>>>14&31,n[i++]=l>>>19&31,n[i++]=l>>>24&31,n[i++]=31&(l>>>29|(3&u)<<3),n[i++]=u>>>2&31,n[i++]=u>>>7&31,n[i++]=u>>>12&31,n[i++]=u>>>17&31,n[i++]=u>>>22&31,n[i]=u>>>27&31;}(t,e,n,r);case 6:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0;n[i++]=s>>>0&63,n[i++]=s>>>6&63,n[i++]=s>>>12&63,n[i++]=s>>>18&63,n[i++]=s>>>24&63,n[i++]=63&(s>>>30|(15&o)<<2),n[i++]=o>>>4&63,n[i++]=o>>>10&63,n[i++]=o>>>16&63,n[i++]=o>>>22&63,n[i++]=63&(o>>>28|(3&a)<<4),n[i++]=a>>>2&63,n[i++]=a>>>8&63,n[i++]=a>>>14&63,n[i++]=a>>>20&63,n[i++]=a>>>26&63,n[i++]=l>>>0&63,n[i++]=l>>>6&63,n[i++]=l>>>12&63,n[i++]=l>>>18&63,n[i++]=l>>>24&63,n[i++]=63&(l>>>30|(15&u)<<2),n[i++]=u>>>4&63,n[i++]=u>>>10&63,n[i++]=u>>>16&63,n[i++]=u>>>22&63,n[i++]=63&(u>>>28|(3&c)<<4),n[i++]=c>>>2&63,n[i++]=c>>>8&63,n[i++]=c>>>14&63,n[i++]=c>>>20&63,n[i]=c>>>26&63;}(t,e,n,r);case 7:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0;n[i++]=s>>>0&127,n[i++]=s>>>7&127,n[i++]=s>>>14&127,n[i++]=s>>>21&127,n[i++]=127&(s>>>28|(7&o)<<4),n[i++]=o>>>3&127,n[i++]=o>>>10&127,n[i++]=o>>>17&127,n[i++]=o>>>24&127,n[i++]=127&(o>>>31|(63&a)<<1),n[i++]=a>>>6&127,n[i++]=a>>>13&127,n[i++]=a>>>20&127,n[i++]=127&(a>>>27|(3&l)<<5),n[i++]=l>>>2&127,n[i++]=l>>>9&127,n[i++]=l>>>16&127,n[i++]=l>>>23&127,n[i++]=127&(l>>>30|(31&u)<<2),n[i++]=u>>>5&127,n[i++]=u>>>12&127,n[i++]=u>>>19&127,n[i++]=127&(u>>>26|(1&c)<<6),n[i++]=c>>>1&127,n[i++]=c>>>8&127,n[i++]=c>>>15&127,n[i++]=c>>>22&127,n[i++]=127&(c>>>29|(15&h)<<3),n[i++]=h>>>4&127,n[i++]=h>>>11&127,n[i++]=h>>>18&127,n[i]=h>>>25&127;}(t,e,n,r);case 8:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0;n[i++]=s>>>0&255,n[i++]=s>>>8&255,n[i++]=s>>>16&255,n[i++]=s>>>24&255,n[i++]=o>>>0&255,n[i++]=o>>>8&255,n[i++]=o>>>16&255,n[i++]=o>>>24&255,n[i++]=a>>>0&255,n[i++]=a>>>8&255,n[i++]=a>>>16&255,n[i++]=a>>>24&255,n[i++]=l>>>0&255,n[i++]=l>>>8&255,n[i++]=l>>>16&255,n[i++]=l>>>24&255,n[i++]=u>>>0&255,n[i++]=u>>>8&255,n[i++]=u>>>16&255,n[i++]=u>>>24&255,n[i++]=c>>>0&255,n[i++]=c>>>8&255,n[i++]=c>>>16&255,n[i++]=c>>>24&255,n[i++]=h>>>0&255,n[i++]=h>>>8&255,n[i++]=h>>>16&255,n[i++]=h>>>24&255,n[i++]=p>>>0&255,n[i++]=p>>>8&255,n[i++]=p>>>16&255,n[i]=p>>>24&255;}(t,e,n,r);case 9:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0,f=t[e+8]>>>0;n[i++]=s>>>0&511,n[i++]=s>>>9&511,n[i++]=s>>>18&511,n[i++]=511&(s>>>27|(15&o)<<5),n[i++]=o>>>4&511,n[i++]=o>>>13&511,n[i++]=o>>>22&511,n[i++]=511&(o>>>31|(255&a)<<1),n[i++]=a>>>8&511,n[i++]=a>>>17&511,n[i++]=511&(a>>>26|(7&l)<<6),n[i++]=l>>>3&511,n[i++]=l>>>12&511,n[i++]=l>>>21&511,n[i++]=511&(l>>>30|(127&u)<<2),n[i++]=u>>>7&511,n[i++]=u>>>16&511,n[i++]=511&(u>>>25|(3&c)<<7),n[i++]=c>>>2&511,n[i++]=c>>>11&511,n[i++]=c>>>20&511,n[i++]=511&(c>>>29|(63&h)<<3),n[i++]=h>>>6&511,n[i++]=h>>>15&511,n[i++]=511&(h>>>24|(1&p)<<8),n[i++]=p>>>1&511,n[i++]=p>>>10&511,n[i++]=p>>>19&511,n[i++]=511&(p>>>28|(31&f)<<4),n[i++]=f>>>5&511,n[i++]=f>>>14&511,n[i]=f>>>23&511;}(t,e,n,r);case 10:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0,f=t[e+8]>>>0,d=t[e+9]>>>0;n[i++]=s>>>0&1023,n[i++]=s>>>10&1023,n[i++]=s>>>20&1023,n[i++]=1023&(s>>>30|(255&o)<<2),n[i++]=o>>>8&1023,n[i++]=o>>>18&1023,n[i++]=1023&(o>>>28|(63&a)<<4),n[i++]=a>>>6&1023,n[i++]=a>>>16&1023,n[i++]=1023&(a>>>26|(15&l)<<6),n[i++]=l>>>4&1023,n[i++]=l>>>14&1023,n[i++]=1023&(l>>>24|(3&u)<<8),n[i++]=u>>>2&1023,n[i++]=u>>>12&1023,n[i++]=u>>>22&1023,n[i++]=c>>>0&1023,n[i++]=c>>>10&1023,n[i++]=c>>>20&1023,n[i++]=1023&(c>>>30|(255&h)<<2),n[i++]=h>>>8&1023,n[i++]=h>>>18&1023,n[i++]=1023&(h>>>28|(63&p)<<4),n[i++]=p>>>6&1023,n[i++]=p>>>16&1023,n[i++]=1023&(p>>>26|(15&f)<<6),n[i++]=f>>>4&1023,n[i++]=f>>>14&1023,n[i++]=1023&(f>>>24|(3&d)<<8),n[i++]=d>>>2&1023,n[i++]=d>>>12&1023,n[i]=d>>>22&1023;}(t,e,n,r);case 11:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0,f=t[e+8]>>>0,d=t[e+9]>>>0,y=t[e+10]>>>0;n[i++]=s>>>0&2047,n[i++]=s>>>11&2047,n[i++]=2047&(s>>>22|(1&o)<<10),n[i++]=o>>>1&2047,n[i++]=o>>>12&2047,n[i++]=2047&(o>>>23|(3&a)<<9),n[i++]=a>>>2&2047,n[i++]=a>>>13&2047,n[i++]=2047&(a>>>24|(7&l)<<8),n[i++]=l>>>3&2047,n[i++]=l>>>14&2047,n[i++]=2047&(l>>>25|(15&u)<<7),n[i++]=u>>>4&2047,n[i++]=u>>>15&2047,n[i++]=2047&(u>>>26|(31&c)<<6),n[i++]=c>>>5&2047,n[i++]=c>>>16&2047,n[i++]=2047&(c>>>27|(63&h)<<5),n[i++]=h>>>6&2047,n[i++]=h>>>17&2047,n[i++]=2047&(h>>>28|(127&p)<<4),n[i++]=p>>>7&2047,n[i++]=p>>>18&2047,n[i++]=2047&(p>>>29|(255&f)<<3),n[i++]=f>>>8&2047,n[i++]=f>>>19&2047,n[i++]=2047&(f>>>30|(511&d)<<2),n[i++]=d>>>9&2047,n[i++]=d>>>20&2047,n[i++]=2047&(d>>>31|(1023&y)<<1),n[i++]=y>>>10&2047,n[i]=y>>>21&2047;}(t,e,n,r);case 12:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0,f=t[e+8]>>>0,d=t[e+9]>>>0,y=t[e+10]>>>0,m=t[e+11]>>>0;n[i++]=s>>>0&4095,n[i++]=s>>>12&4095,n[i++]=4095&(s>>>24|(15&o)<<8),n[i++]=o>>>4&4095,n[i++]=o>>>16&4095,n[i++]=4095&(o>>>28|(255&a)<<4),n[i++]=a>>>8&4095,n[i++]=a>>>20&4095,n[i++]=l>>>0&4095,n[i++]=l>>>12&4095,n[i++]=4095&(l>>>24|(15&u)<<8),n[i++]=u>>>4&4095,n[i++]=u>>>16&4095,n[i++]=4095&(u>>>28|(255&c)<<4),n[i++]=c>>>8&4095,n[i++]=c>>>20&4095,n[i++]=h>>>0&4095,n[i++]=h>>>12&4095,n[i++]=4095&(h>>>24|(15&p)<<8),n[i++]=p>>>4&4095,n[i++]=p>>>16&4095,n[i++]=4095&(p>>>28|(255&f)<<4),n[i++]=f>>>8&4095,n[i++]=f>>>20&4095,n[i++]=d>>>0&4095,n[i++]=d>>>12&4095,n[i++]=4095&(d>>>24|(15&y)<<8),n[i++]=y>>>4&4095,n[i++]=y>>>16&4095,n[i++]=4095&(y>>>28|(255&m)<<4),n[i++]=m>>>8&4095,n[i]=m>>>20&4095;}(t,e,n,r);case 16:return void function(t,e,n,r){let i=r;const s=t[e]>>>0,o=t[e+1]>>>0,a=t[e+2]>>>0,l=t[e+3]>>>0,u=t[e+4]>>>0,c=t[e+5]>>>0,h=t[e+6]>>>0,p=t[e+7]>>>0,f=t[e+8]>>>0,d=t[e+9]>>>0,y=t[e+10]>>>0,m=t[e+11]>>>0,g=t[e+12]>>>0,x=t[e+13]>>>0,v=t[e+14]>>>0,b=t[e+15]>>>0;n[i++]=s>>>0&65535,n[i++]=s>>>16&65535,n[i++]=o>>>0&65535,n[i++]=o>>>16&65535,n[i++]=a>>>0&65535,n[i++]=a>>>16&65535,n[i++]=l>>>0&65535,n[i++]=l>>>16&65535,n[i++]=u>>>0&65535,n[i++]=u>>>16&65535,n[i++]=c>>>0&65535,n[i++]=c>>>16&65535,n[i++]=h>>>0&65535,n[i++]=h>>>16&65535,n[i++]=p>>>0&65535,n[i++]=p>>>16&65535,n[i++]=f>>>0&65535,n[i++]=f>>>16&65535,n[i++]=d>>>0&65535,n[i++]=d>>>16&65535,n[i++]=y>>>0&65535,n[i++]=y>>>16&65535,n[i++]=m>>>0&65535,n[i++]=m>>>16&65535,n[i++]=g>>>0&65535,n[i++]=g>>>16&65535,n[i++]=x>>>0&65535,n[i++]=x>>>16&65535,n[i++]=v>>>0&65535,n[i++]=v>>>16&65535,n[i++]=b>>>0&65535,n[i]=b>>>16&65535;}(t,e,n,r);case 32:for(let i=0;i<32;i=i+1|0)n[r+i|0]=0|t[e+i|0];return}const s=pf[i]>>>0;let o=e,a=0,l=t[o]>>>0;for(let e=0;e<32;e++)if(a+i<=32)n[r+e]=l>>>a&s,a+=i,32===a&&(a=0,o++,31!==e&&(l=t[o]>>>0));else {const u=32-a,c=l>>>a;o++,l=t[o]>>>0,n[r+e]=(c|(l&pf[i-u]>>>0)<=64)throw new Error("Varint too long")}return e.set(i),n}function If(t,e){let n,r;return r=t[e.get()],e.increment(),n=127&r,r<128?n:(r=t[e.get()],e.increment(),n|=(127&r)<<7,r<128?n:(r=t[e.get()],e.increment(),n|=(127&r)<<14,r<128?n:(r=t[e.get()],e.increment(),n|=(127&r)<<21,r<128?n:(r=t[e.get()],n|=(15&r)<<28,function(t,e,n){let r,i;if(i=e[n.get()],n.increment(),r=(112&i)>>4,i<128)return 4294967296*r+(t>>>0);if(i=e[n.get()],n.increment(),r|=(127&i)<<3,i<128)return 4294967296*r+(t>>>0);if(i=e[n.get()],n.increment(),r|=(127&i)<<10,i<128)return 4294967296*r+(t>>>0);if(i=e[n.get()],n.increment(),r|=(127&i)<<17,i<128)return 4294967296*r+(t>>>0);if(i=e[n.get()],n.increment(),r|=(127&i)<<24,i<128)return 4294967296*r+(t>>>0);if(i=e[n.get()],n.increment(),r|=(1&i)<<31,i<128)return 4294967296*r+(t>>>0);throw new Error("Expected varint not more than 10 bytes")}(n,t,e)))))}function Ef(t){return t>>>1^-(1&t)}function Tf(t){return t>>1n^-(1n&t)}function Ff(t){return t%2==1?(t+1)/-2:t/2}function Pf(t,e,n){if(void 0===n){n=0;for(let r=0;r=4)for(;r=4)for(;r=4)for(let r=t[0];n>4];let i=null;switch(r){case Lf.DATA:i={dictionaryType:Object.values(Of)[15&n]};break;case Lf.OFFSET:i={offsetType:Object.values($f)[15&n]};break;case Lf.LENGTH:i={lengthType:Object.values(Rf)[15&n]};}e.increment();const s=t[e.get()],o=Object.values(uf)[s>>5],a=Object.values(uf)[s>>2&7],l=Object.values(cf)[3&s];e.increment();const u=Af(t,e,2),c=u[0];return {physicalStreamType:r,logicalStreamType:i,logicalLevelTechnique1:o,logicalLevelTechnique2:a,physicalLevelTechnique:l,numValues:c,byteLength:u[1],decompressedCount:c}}(t,e);return n.logicalLevelTechnique1===uf.MORTON?function(t,e,n){const r=Af(e,n,2);return {physicalStreamType:t.physicalStreamType,logicalStreamType:t.logicalStreamType,logicalLevelTechnique1:t.logicalLevelTechnique1,logicalLevelTechnique2:t.logicalLevelTechnique2,physicalLevelTechnique:t.physicalLevelTechnique,numValues:t.numValues,byteLength:t.byteLength,decompressedCount:t.decompressedCount,numBits:r[0],coordinateShift:r[1]}}(n,t,e):uf.RLE!==n.logicalLevelTechnique1&&uf.RLE!==n.logicalLevelTechnique2||cf.NONE===n.physicalLevelTechnique?n:function(t,e,n){const r=Af(e,n,2);return {physicalStreamType:t.physicalStreamType,logicalStreamType:t.logicalStreamType,logicalLevelTechnique1:t.logicalLevelTechnique1,logicalLevelTechnique2:t.logicalLevelTechnique2,physicalLevelTechnique:t.physicalLevelTechnique,numValues:t.numValues,byteLength:t.byteLength,decompressedCount:r[1],runs:r[0],numRleValues:r[1]}}(n,t,e)}!function(t){t.PRESENT="PRESENT",t.DATA="DATA",t.OFFSET="OFFSET",t.LENGTH="LENGTH";}(Lf||(Lf={})),function(t){t.NONE="NONE",t.SINGLE="SINGLE",t.SHARED="SHARED",t.VERTEX="VERTEX",t.MORTON="MORTON",t.FSST="FSST";}(Of||(Of={})),function(t){t.VERTEX="VERTEX",t.INDEX="INDEX",t.STRING="STRING",t.KEY="KEY";}($f||($f={})),function(t){t.VAR_BINARY="VAR_BINARY",t.GEOMETRIES="GEOMETRIES",t.PARTS="PARTS",t.RINGS="RINGS",t.TRIANGLES="TRIANGLES",t.SYMBOL="SYMBOL",t.DICTIONARY="DICTIONARY";}(Rf||(Rf={})),function(t){t[t.FLAT=0]="FLAT",t[t.CONST=1]="CONST",t[t.SEQUENCE=2]="SEQUENCE",t[t.DICTIONARY=3]="DICTIONARY",t[t.FSST_DICTIONARY=4]="FSST_DICTIONARY";}(Nf||(Nf={}));class Xf{constructor(t,e){this.values=t,this._size=e;}get(t){const e=Math.floor(t/8);return 1==(this.values[e]>>t%8&1)}set(t,e){const n=Math.floor(t/8);this.values[n]=this.values[n]|(e?1:0)<>t%8&1}size(){return this._size}getBuffer(){return this.values}}function Yf(t,e,n){if(!e)return t;const r=e.size(),i=new(0,t.constructor)(r);let s=0;for(let o=0;o=4)for(;r>>0;for(let n=1;n>>0;return e}(e.logicalLevelTechnique2===uf.RLE?Pf(t,e.runs,e.numRleValues):t);break;case uf.RLE:i=Pf(t,e.runs,e.numRleValues);break;case uf.MORTON:Vf(t),i=t;break;case uf.COMPONENTWISE_DELTA:i=function(t){if(t.length<2)return new Uint32Array(t);const e=new Uint32Array(t.length);e[0]=Ef(t[0])>>>0,e[1]=Ef(t[1])>>>0;for(let n=2;n>>0,e[n+1]=e[n-1]+Ef(t[n+1])>>>0;return e}(t);break;case uf.NONE:i=t;break;default:throw new Error(`The specified Logical level technique is not supported: ${e.logicalLevelTechnique1}`)}return r?Yf(i,r,0):i}(Kf(t,e,n),n,0,i)}function Wf(t,e,n){return function(t,e){if(e.logicalLevelTechnique1===uf.DELTA&&e.logicalLevelTechnique2===uf.NONE)return function(t){const e=new Int32Array(t.length+1);e[0]=0,e[1]=Ef(t[0]);let n=e[1];for(let r=2;r!==e.length;++r)n+=Ef(t[r-1]),e[r]=e[r-1]+n;return new Uint32Array(e)}(t);if(e.logicalLevelTechnique1===uf.RLE&&e.logicalLevelTechnique2===uf.NONE)return function(t,e,n){const r=new Uint32Array(n+1);r[0]=0;let i=1,s=r[0];for(let n=0;n>>2,a=function(t,e){if(e<=t.encodedWords.length)return t.encodedWords;const n=new Uint32Array(Math.max(16,2*e));return t.encodedWords=n,n}(i,o);!function(t,e,n,r){if(e<0||n<0||e+n>t.length)throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${e}, byteLength=${n}, bytes.length=${t.length})`);const i=Math.floor(n/4),s=n%4!=0,o=s?i+1:i;if(r.length0){const n=t.byteOffset+e;if(3&n)for(let n=0;n0){const e=0|t[r];if(r=r+1|0,255&e)throw new Error(`FastPFOR decode: invalid alignedLength=${e} (expected multiple of 256)`);if(i+e>s.length)throw new Error(`FastPFOR decode: output buffer too small (outPos=${i}, alignedLength=${e}, out.length=${s.length})`);r=function(t,e,n,r,i,s){const o=r+df(i,ff);let a=r,l=n;for(;a!==o;){const n=Math.min(mf,o-a);l=_f(t,e,l,a,n,s),a=a+n|0;}return l}(t,s,r,i,e,o),i=i+e|0;}return function(t,e,n,r,i,s){if(0===s)return e;let o=0,a=e;const l=e+n,u=i;let c=i;const h=i+s;let p=0,f=0;for(;a>>o&255;if(o+=8,a+=o>>>5,o&=31,p|=(127&e)<28)throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${f}, partial=${p}, decoded=${c-u}/${s}, inPos=${a}, inEnd=${l})`)}if(c!==h)throw new Error(`FastPFOR VByte: truncated stream (decoded=${c-u}, expected=${s}, consumedWords=${a-e}/${n}, vbyteStart=${e}, vbyteEnd=${l})`)}(t,r,t.length-r|0,s,i,e-i|0),s}(a.subarray(0,o),e,i.decoderWorkspace);return r.add(n),l}(t,e,n,r,function(t=16){if(t<0)throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${t}`);const e=Math.max(16,0|t);return {encodedWords:new Uint32Array(e),decoderWorkspace:xf()}}(n>>>2))}(t,n.numValues,n.byteLength,e);case cf.VARINT:return Af(t,e,n.numValues);case cf.NONE:{const r=e.get();e.add(n.byteLength);const i=t.subarray(r,e.get());return new Uint32Array(i)}default:throw new Error(`Specified physicalLevelTechnique ${r} is not supported (yet).`)}}function Jf(t,e,n){const r=Kf(t,e,n);return 1===r.length?r[0]:function(t){return t[1]}(r)}function Qf(t,e,n){return function(t){if(2===t.length){const e=Ef(t[1]);return [e,e]}return [Ef(t[2]),Ef(t[3])]}(Kf(t,e,n))}function td(t,e,n){return function(t){if(2===t.length){const e=Tf(t[1]);return [e,e]}return [Tf(t[2]),Tf(t[3])]}(Mf(t,e,n.numValues))}function ed(t,e,n,r){return function(t,e,n){let r;switch(e.logicalLevelTechnique1){case uf.DELTA:r=function(t){const e=new BigUint64Array(t.length);e[0]=BigInt.asUintN(64,Tf(t[0]));for(let n=1;n>1,e)-n}}function ad(t,e){let n=0;for(let r=0;r>r;return n}function ld(t,e,r,i,s,o,a){return t===qf.MORTON?function(t,e,r,i,s,o){const a=new Array(s?i+1:i);for(let s=0;s[t])),r+=t,i+=t;}break;case Uf.LINESTRING:{let n,c;m?(n=f[i]-f[i-1],i++):n=p[r]-p[r-1],r++,y?(c=ud(g,a,n,!1),a+=2*n):(c=ld(t.vertexBufferType,g,d,l,n,!1,u),l+=n),e[o++]=[c],h&&s++;}break;case Uf.POLYGON:{const n=p[r]-p[r-1];r++;const c=new Array(n-1);let m,x=f[i]-f[i-1];if(i++,y){m=ud(g,a,x,!0),a+=2*x;for(let t=0;t0&&e.push(e[0]),h.push(e);}t[e]=h,s&&u++;}break;case Uf.MULTIPOLYGON:{const c=s[u]-s[u-1];u++;const h=[];for(let t=0;t0&&e.push(e[0]),h.push(e);}}t[e]=h;}}return t}[Symbol.iterator](){return null}}function dd(t,e,n,r,i,s){return new yd(t,e,n,r,i,s)}class yd extends fd{constructor(t,e,n,r,i,s){super(n,r,i,s),this._numGeometries=t,this._geometryType=e;}geometryType(t){return this._geometryType}get numGeometries(){return this._numGeometries}containsSingleGeometryType(){return !0}}function md(t,e,n,r,i){return new gd(t,e,n,r,i)}class gd extends fd{constructor(t,e,n,r,i){super(e,n,r,i),this._geometryTypes=t;}geometryType(t){return this._geometryTypes[t]}get numGeometries(){return this._geometryTypes.length}containsSingleGeometryType(){return !1}}function xd(t,e,n,r,i){const s=Gf(t,n);let o,a,l,u;if(rd(s,r,t,n)===Nf.CONST){const i=Jf(t,n,s);let c,h,p,f;for(let r=0;rn?e[s++]:1);return r}function bd(t,e,n,r){const i=new Uint32Array(e[e.length-1]+1);let s=0;i[0]=s;let o=1,a=0;for(let l=0;l=o);){const n=t[r.increment()];if(n<=127){const o=n+3,a=t[r.increment()],l=Math.min(s+o,e);i.fill(a,s,l),s=l;}else {const o=256-n;for(let n=0;n=12?Md.decode(t.subarray(e,n)):function(t,e,n){let r="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>n)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],o=t[i+2],128==(192&s)&&128==(192&o)&&(l=(15&e)<<12|(63&s)<<6|63&o,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],o=t[i+2],a=t[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(l=(15&e)<<18|(63&s)<<12|(63&o)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,r+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),r+=String.fromCharCode(l),i+=u;}return r}(t,e,n)}class Id extends Qp{constructor(t,e,n,r){super(t,n,r),this.offsetBuffer=e;}}class Ed extends Id{constructor(t,e,n,r){super(t,e,n,r??e.length-1);}getValueFromBuffer(t){return kd(this.dataBuffer,this.offsetBuffer[t],this.offsetBuffer[t+1])}}class Td extends Id{constructor(t,e,n,r,i){super(t,n,r,i??e.length),this.indexBuffer=e,this.indexBuffer=e;}getValueFromBuffer(t){const e=this.indexBuffer[t];return kd(this.dataBuffer,this.offsetBuffer[e],this.offsetBuffer[e+1])}}class Fd extends Id{constructor(t,e,n,r,i,s,o){super(t,n,r,o),this.indexBuffer=e,this.symbolOffsetBuffer=i,this.symbolTableBuffer=s;}getValueFromBuffer(t){null==this.decodedDictionary&&(null==this.symbolLengthBuffer&&(this.symbolLengthBuffer=this.offsetToLengthBuffer(this.symbolOffsetBuffer)),this.decodedDictionary=function(t,e,n){const r=[],i=new Array(e.length).fill(0);for(let t=1;t=10}function Cd(t){return 30===t}function Vd(t){if("scalarType"===t.type){const e=t.scalarType;if("physicalType"===e.type)switch(e.physicalType){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:default:return !1;case 9:return !0}if("logicalType"===e.type)return !1}else if("complexType"===t.type){const e=t.complexType;if("physicalType"===e.type)switch(e.physicalType){case 0:case 1:return !0;default:return !1}}return console.warn("Unexpected column type in hasStreamCount",t),!1}function Ld(t){return "complexType"===t.type&&"physicalType"===t.complexType?.type&&0===t.complexType.physicalType}const Od=new TextDecoder;function $d(t,e){const n=Af(t,e,1)[0];if(0===n)return "";const r=e.get(),i=t.subarray(r,r+n);return e.add(n),Od.decode(i)}function Rd(t,e){const n=Af(t,e,1)[0]>>>0;if(n<10||n>30)throw new Error(`Unsupported field type code ${n}. Supported: 10-29(scalars), 30(STRUCT)`);const r=zd(n);if(Bd(n)&&(r.name=$d(t,e)),Cd(n)){const n=Af(t,e,1)[0]>>>0;r.complexType.children=new Array(n);for(let i=0;i>>0,r=zd(n);if(!r)throw new Error(`Unsupported column type code ${n}. Supported: 0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT)`);if(Bd(n)?r.name=$d(t,e):n>=0&&n<=3?r.name="id":4===n&&(r.name="geometry"),Cd(n)){const n=Af(t,e,1)[0]>>>0,i=r.complexType;i.children=new Array(n);for(let r=0;r>>0,s=Af(t,e,1)[0]>>>0;r.columns=new Array(s);for(let n=0;n=4)for(;n>>0,o=r.get()+e;if(o>t.length)throw new Error(`Block overruns tile: ${o} > ${t.length}`);if(1!=Af(t,r,1)[0]>>>0){r.set(o);continue}const[a,l]=Ud(t,r),u=a.featureTables[0];let c=null,h=null;const p=[];let f=0;for(const e of u.columns){const i=e.name;if("scalarType"===(s=e).type&&"logicalType"===s.scalarType?.type&&0===s.scalarType.logicalType){let s=null;if(e.nullable){const e=Gf(t,r),n=r.get(),i=Ad(t,e.numValues,e.byteLength,r);r.set(n+e.byteLength),s=new Xf(i,e.numValues);}const o=Gf(t,r);f=s?s.size():o.decompressedCount,c=jd(t,e,r,i,o,s??f,n);}else if(Ld(e)){const e=Af(t,r,1)[0];if(0===f){const e=r.get();f=Gf(t,r).decompressedCount,r.set(e);}h=xd(t,e,r,f);}else {const n=Vd(e)?Af(t,r,1)[0]:1;if(0===n)continue;const i=Pd(t,r,e,n,f);if(i)if(Array.isArray(i))for(const t of i)p.push(t);else p.push(i);}}const d=new af(u.name,h,c,p,l);i.push(d),r.set(o);}var s;return i}(new Uint8Array(t));this.layers=e.reduce(((t,e)=>Object.assign(Object.assign({},t),{[e.name]:new Gd(e)})),{});}}class Yd{constructor(t,e){this.feature=t,this.type=t.type,this.properties=t.tags?t.tags:{},this.extent=e,"id"in t&&("string"==typeof t.id?this.id=parseInt(t.id,10):"number"!=typeof t.id||isNaN(t.id)||(this.id=t.id));}loadGeometry(){const t=[],e=1===this.feature.type?[this.feature.geometry]:this.feature.geometry;for(const r of e){const e=[];for(const t of r)e.push(new n(t[0],t[1]));t.push(e);}return t}}const Zd="_geojsonTileLayer";function Hd(t,e,n=""){e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);const r={jsonPrefix:n,keys:[],values:[],keycache:{},valuecache:{}};for(let n=0;n>31}function ty(t,e){const n=t.loadGeometry(),r=t.type;let i=0,s=0;for(const o of n){let n=1;1===r&&(n=o.length),e.writeVarint(Jd(1,n));const a=3===r?o.length-1:o.length;for(let t=0;t=0&&r[3]>=0&&a.insert(o,r[0],r[1],r[2],r[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers="mlt"!==this.encoding?new Ru(new Vh(this.rawTileData)).layers:new Xd(this.rawTileData).layers,this.sourceLayerCoder=new Kp(this.vtLayers?Object.keys(this.vtLayers).sort():[Zd])),this.vtLayers}query(t,e,r,i){this.loadVTLayers();const s=t.params,o=T/t.tileSize/t.scale,a=di(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*o,c=Wp.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Wp.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,r,i,s)=>function(t,e,r,i,s){for(const n of t)if(e<=n.x&&r<=n.y&&i>=n.x&&s>=n.y)return !0;const o=[new n(e,r),new n(e,s),new n(i,s),new n(i,r)];if(t.length>2)for(const e of o)if(rl(t,e))return !0;for(let e=0;e(p||(p=ja(e)),n.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:r,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:o,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,n,r,i,s,o,a,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(n),f=this.vtLayers[p].feature(r);if(i.needGeometry){const t=qa(f,!0);if(!i.filter(new Bs(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Bs(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const o=e instanceof qs?e.get(s):null;return o&&o.evaluate?o.evaluate(n,r,i):o}))}function iy(t,e){return e-t}function sy(t,e,r,i,s){const o=[];for(let a=0;a=i&&c.x>=i||(a.x>=i?a=new n(i,a.y+(i-a.x)/(c.x-a.x)*(c.y-a.y))._round():c.x>=i&&(c=new n(i,a.y+(i-a.x)/(c.x-a.x)*(c.y-a.y))._round()),a.y>=s&&c.y>=s||(a.y>=s?a=new n(a.x+(s-a.y)/(c.y-a.y)*(c.x-a.x),s)._round():c.y>=s&&(c=new n(a.x+(s-a.y)/(c.y-a.y)*(c.x-a.x),s)._round()),u&&a.equals(u[u.length-1])||(u=[a],o.push(u)),u.push(c)))));}}return o}function oy(t,e,n,r,i){switch(e){case 1:return function(t,e,n,r){const i=[];for(const s of t)for(const t of s){const s=0===r?t.x:t.y;s>=e&&s<=n&&i.push([t]);}return i}(t,n,r,i);case 2:return ly(t,n,r,i,!1);case 3:return ly(t,n,r,i,!0)}return []}function ay(t,e,r,i,s){const o=0===i?uy:cy;let a=[];const l=[];for(let n=0;ne&&a.push(o(u,c,e)):h>r?p=e&&(a.push(o(u,c,e)),f=!0),p>r&&h<=r&&(a.push(o(u,c,r)),f=!0),!s&&f&&(l.push(a),a=[]);}const u=t.length-1,c=0===i?t[u].x:t[u].y;return c>=e&&c<=r&&a.push(t[u]),s&&a.length>0&&!a[0].equals(a[a.length-1])&&a.push(new n(a[0].x,a[0].y)),a.length>0&&l.push(a),l}function ly(t,e,n,r,i){const s=[];for(const o of t){const t=ay(o,e,n,r,i);t.length>0&&s.push(...t);}return s}function uy(t,e,r){return new n(r,t.y+(r-t.x)/(e.x-t.x)*(e.y-t.y))}function cy(t,e,r){return new n(t.x+(r-t.y)/(e.y-t.y)*(e.x-t.x),r)}fs("FeatureIndex",ny,{omit:["rawTileData","sourceLayerCoder"]});class hy extends n{constructor(t,e,n,r){super(t,e),this.angle=n,void 0!==r&&(this.segment=r);}clone(){return new hy(this.x,this.y,this.angle,this.segment)}}function py(t,e,n,r,i){if(void 0===e.segment||0===n)return !0;let s=e,o=e.segment+1,a=0;for(;a>-n/2;){if(o--,o<0)return !1;a-=t[o].dist(s),s=t[o];}a+=t[o].dist(t[o+1]),o++;const l=[];let u=0;for(;ar;)u-=l.shift().angleDelta;if(u>i)return !1;o++,a+=e.dist(n);}return !0}function fy(t){let e=0;for(let n=0;nu){const c=(u-l)/s,h=gn.number(r.x,i.x,c),p=gn.number(r.y,i.y,c),f=new hy(h,p,i.angleTo(r),n);return f._round(),!o||py(t,f,a,o,e)?f:void 0}l+=s;}}function gy(t,e,n,r,i,s,o,a,l){const u=dy(r,s,o),c=yy(r,i),h=c*o,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const n=new hy(g,x,y,e);n._round(),r&&!py(t,n,s,r,i)||f.push(n);}}h+=d;}return a||f.length||o||(f=xy(t,h/2,n,r,i,s,o,!0,l)),f}function vy(t,e,r,i){const s=[],o=t.image,a=o.pixelRatio,l=o.paddedRect.w-2,u=o.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=o.stretchX||[[0,l]],p=o.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,M=g;if(o.content&&i){const e=o.content,n=e[2]-e[0],r=e[3]-e[1];(o.textFitWidth||o.textFitHeight)&&(c=cp(t)),x=by(h,0,e[0]),b=by(p,0,e[1]),v=by(h,e[0],e[2]),w=by(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=n-v,M=r-w;}const k=c.x1,I=c.y1,E=c.x2-k,T=c.y2-I,F=(t,i,s,l)=>{const u=_y(t.stretch-x,v,E,k),c=Sy(t.fixed-_,S,t.stretch,d),h=_y(i.stretch-b,w,T,I),p=Sy(i.fixed-A,M,i.stretch,y),f=_y(s.stretch-x,v,E,k),m=Sy(s.fixed-_,S,s.stretch,d),g=_y(l.stretch-b,w,T,I),F=Sy(l.fixed-A,M,l.stretch,y),P=new n(u,h),D=new n(f,h),z=new n(f,g),B=new n(u,g),C=new n(c/a,p/a),V=new n(m/a,F/a),L=e*Math.PI/180;if(L){const t=Math.sin(L),e=Math.cos(L),n=[e,-t,t,e];P._matMult(n),D._matMult(n),B._matMult(n),z._matMult(n);}const O=t.stretch+t.fixed,$=i.stretch+i.fixed;return {tl:P,tr:D,bl:B,br:z,tex:{x:o.paddedRect.x+1+O,y:o.paddedRect.y+1+$,w:s.stretch+s.fixed-O,h:l.stretch+l.fixed-$},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:C,pixelOffsetBR:V,minFontScaleX:S/a/E,minFontScaleY:M/a/T,isSDF:r}};if(i&&(o.stretchX||o.stretchY)){const t=wy(h,m,d),e=wy(p,g,y);for(let n=0;n0&&(r=Math.max(10,r),this.circleDiameter=r);}else {const u=(null===(h=o.image)||void 0===h?void 0:h.content)&&(o.image.textFitWidth||o.image.textFitHeight)?cp(o):{x1:o.left,y1:o.top,x2:o.right,y2:o.bottom};u.y1=u.y1*a-l[0],u.y2=u.y2*a+l[2],u.x1=u.x1*a-l[3],u.x2=u.x2*a+l[1];const p=o.collisionPadding;if(p&&(u.x1-=p[0]*a,u.y1-=p[1]*a,u.x2+=p[2]*a,u.y2+=p[3]*a),c){const t=new n(u.x1,u.y1),e=new n(u.x2,u.y1),r=new n(u.x1,u.y2),i=new n(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),r._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,r.x,i.x),u.x2=Math.max(t.x,e.x,r.x,i.x),u.y1=Math.min(t.y,e.y,r.y,i.y),u.y2=Math.max(t.y,e.y,r.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,i,s);}this.boxEndIndex=t.length;}}class My{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:n}=this,r=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(n(r,s)>=0)break;e[t]=s,t=i;}e[t]=r;}_down(t){const{data:e,compare:n}=this,r=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[r],t=r;}e[t]=i;}}function ky(t,e=1,r=!1){const i=Wp.fromPoints(t[0]),s=Math.min(i.width(),i.height());let o=s/2;const a=new My([],Iy),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new n(l,u);for(let e=l;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(o=n.h/2,a.push(new Ey(n.p.x-o,n.p.y-o,o,t)),a.push(new Ey(n.p.x+o,n.p.y-o,o,t)),a.push(new Ey(n.p.x-o,n.p.y+o,o,t)),a.push(new Ey(n.p.x+o,n.p.y+o,o,t)),f+=4);}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function Iy(t,e){return e.max-t.max}function Ey(t,e,r,i){this.p=new n(t,e),this.h=r,this.d=function(t,e){let n=!1,r=1/0;for(let i=0;it.y!=a.y>t.y&&t.x<(a.x-i.x)*(t.y-i.y)/(a.y-i.y)+i.x&&(n=!n),r=Math.min(r,el(t,i,a));}}return (n?1:-1)*Math.sqrt(r)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var Ty;t.aM=void 0,(Ty=t.aM||(t.aM={}))[Ty.center=1]="center",Ty[Ty.left=2]="left",Ty[Ty.right=3]="right",Ty[Ty.top=4]="top",Ty[Ty.bottom=5]="bottom",Ty[Ty["top-left"]=6]="top-left",Ty[Ty["top-right"]=7]="top-right",Ty[Ty["bottom-left"]=8]="bottom-left",Ty[Ty["bottom-right"]=9]="bottom-right";const Fy=Number.POSITIVE_INFINITY;function Py(t,e){return e[1]!==Fy?function(t,e,n){let r=0,i=0;switch(e=Math.abs(e),n=Math.abs(n),t){case "top-right":case "top-left":case "top":i=n-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-n;}switch(t){case "top-right":case "bottom-right":case "right":r=-e;break;case "top-left":case "bottom-left":case "left":r=e;}return [r,i]}(t,e[0],e[1]):function(t,e){let n=0,r=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":r=i-7;break;case "bottom-right":case "bottom-left":r=7-i;break;case "bottom":r=7-e;break;case "top":r=e-7;}switch(t){case "top-right":case "bottom-right":n=-i;break;case "top-left":case "bottom-left":n=i;break;case "left":n=e;break;case "right":n=-e;}return [n,r]}(t,e[0])}function Dy(t,e,n){var r;const i=t.layout,s=null===(r=i.get("text-variable-anchor-offset"))||void 0===r?void 0:r.evaluate(e,{},n);if(s){const t=s.values,e=[];for(let n=0;nt*Sh));r.startsWith("top")?i[1]-=7:r.startsWith("bottom")&&(i[1]+=7),e[n+1]=i;}return new Oe(e)}const o=i.get("text-variable-anchor");if(o){let r;r=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},n)*Sh,Fy]:i.get("text-offset").evaluate(e,{},n).map((t=>t*Sh));const s=[];for(const t of o)s.push(t,Py(t,r));return new Oe(s)}return null}function zy(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function By(e,n,r,i,s,o,a,l,u,c,h,p){let f=o.textMaxSize.evaluate(n,{});void 0===f&&(f=a);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(n,{},h),m=Vy(r.horizontal),g=a/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,n,r=1){const i=t.get("icon-padding").evaluate(e,{},n),s=i&&i.values;return [s[0]*r,s[1]*r,s[2]*r,s[3]*r]}(d,n,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,M="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),k="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),E=w/2,F=d.get("icon-text-fit");let P;i&&"none"!==F&&(e.allowVerticalPlacement&&r.vertical&&(P=hp(i,r.vertical,F,d.get("icon-text-fit-padding"),y,g)),m&&(i=hp(i,m,F,d.get("icon-text-fit-padding"),y,g)));const D=h?p.line.getGranularityForZoomLevel(h.z):1,z=(l,p)=>{p.x<0||p.x>=T||p.y<0||p.y>=T||function(e,n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,M){const k=e.addToLineVertexArray(n,r);let I,E,T,F,P=0,D=0,z=0,B=0,C=-1,V=-1;const L={};let O=va("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;T=new Ay(u,n,c,h,p,i.vertical,f,d,y,t),a&&(F=new Ay(u,n,c,h,p,a,g,x,y,t));}if(s){const r=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),o=vy(s,r,S,i),f=a?vy(a,r,S,i):void 0;E=new Ay(u,n,c,h,p,s,g,x,!1,r),P=4*o.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[pp*l.layout.get("icon-size").evaluate(w,{})],y[0]>fp&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[pp*_.compositeIconSizes[0].evaluate(w,{},A),pp*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>fp||y[1]>fp)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,o,y,b,v,w,t.aw.none,n,k.lineStartIndex,k.lineLength,-1,A),C=e.icon.placedSymbolArray.length-1,f&&(D=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.aw.vertical,n,k.lineStartIndex,k.lineLength,-1,A),V=e.icon.placedSymbolArray.length-1);}const $=Object.keys(i.horizontal);for(const r of $){const s=i.horizontal[r];if(!I){O=va(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Ay(u,n,c,h,p,s,f,d,y,t);}const a=1===s.positionedLines.length;if(z+=Cy(e,n,s,o,l,y,w,m,k,i.vertical?t.aw.horizontal:t.aw.horizontalOnly,a?$:[r],L,C,_,A),a)break}i.vertical&&(B+=Cy(e,n,i.vertical,o,l,y,w,m,k,t.aw.vertical,["vertical"],L,V,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,N=I?I.boxEndIndex:e.collisionBoxArray.length,U=T?T.boxStartIndex:e.collisionBoxArray.length,j=T?T.boxEndIndex:e.collisionBoxArray.length,G=E?E.boxStartIndex:e.collisionBoxArray.length,X=E?E.boxEndIndex:e.collisionBoxArray.length,Y=F?F.boxStartIndex:e.collisionBoxArray.length,Z=F?F.boxEndIndex:e.collisionBoxArray.length;let H=-1;const W=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=W(I,H),H=W(T,H),H=W(E,H),H=W(F,H);const K=H>-1?1:0;K&&(H*=M/Sh),e.glyphOffsetArray.length>=_p.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const J=Dy(l,w,A),[Q,tt]=function(e,n){const r=e.length,i=null==n?void 0:n.values;if((null==i?void 0:i.length)>0)for(let n=0;n=0?L.right:-1,L.center>=0?L.center:-1,L.left>=0?L.left:-1,L.vertical||-1,C,V,O,R,N,U,j,G,X,Y,Z,c,z,B,P,D,K,0,f,H,Q,tt);}(e,p,l,r,i,s,P,e.layers[0],e.collisionBoxArray,n.index,n.sourceLayerIndex,e.index,x,[_,_,_,_],M,u,b,S,k,y,n,o,c,h,a);};if("line"===I)for(const t of sy(n.geometry,0,0,T,T)){const n=_u(t,D),s=gy(n,w,A,r.vertical||m,i,24,v,e.overscaling,T);for(const t of s)m&&Ly(e,m.text,E,t)||z(n,t);}else if("line-center"===I){for(const t of n.geometry)if(t.length>1){const e=_u(t,D),n=my(e,A,r.vertical||m,i,24,v);n&&z(e,n);}}else if("Polygon"===n.type)for(const t of nr(n.geometry,0)){const e=ky(t,16);z(_u(t[0],D,!0),new hy(e.x,e.y,0));}else if("LineString"===n.type)for(const t of n.geometry){const e=_u(t,D);z(e,new hy(e[0].x,e[0].y,0));}else if("Point"===n.type)for(const t of n.geometry)for(const e of t)z([e],new hy(e.x,e.y,0));}function Cy(t,e,r,i,s,o,a,l,u,c,h,p,f,d,y){const m=function(t,e,r,i,s,o,a,l){const u=i.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const o=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Sh-i.metrics.width*i.scale)/2:(i.scale-1)*Sh)),i.imageName){const t=a[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+r[0],i.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+o.w/b*i.scale/f,A=_+o.h/b*i.scale/f,M=new n(w,_),k=new n(S,_),I=new n(w,A),E=new n(S,A);if(y){const t=new n(-m,m- -17),e=-Math.PI/2,r=12-m,s=new n(22-r,-(i.imageName?r:0)),o=new n(...v);M._rotateAround(e,t)._add(s)._add(o),k._rotateAround(e,t)._add(s)._add(o),I._rotateAround(e,t)._add(s)._add(o),E._rotateAround(e,t)._add(s)._add(o);}if(u){const t=Math.sin(u),e=Math.cos(u),n=[e,-t,t,e];M._matMult(n),k._matMult(n),I._matMult(n),E._matMult(n);}const T=new n(0,0),F=new n(0,0);c.push({tl:M,tr:k,bl:I,br:E,tex:o,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:T,pixelOffsetBR:F,minFontScaleX:0,minFontScaleY:0});}return c}(0,r,l,s,o,a,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[pp*s.layout.get("text-size").evaluate(a,{})],x[0]>fp&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[pp*d.compositeTextSizes[0].evaluate(a,{},y),pp*d.compositeTextSizes[1].evaluate(a,{},y)],(x[0]>fp||x[1]>fp)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,o,a,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function Vy(t){for(const e in t)return t[e];return null}function Ly(t,e,n,r){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(r.dist(t[e])this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}unregisterMessageHandler(t){delete this.messageHandlers[t];}sendAsync(t,e){return new Promise(((n,r)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),zp):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),n(t);},reject:t=>{null==s||s.unsubscribe(),r(t);}};const o=[],a=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:gs(t.data,o)});this.target.postMessage(a,{transfer:o});}))}receive(t){const e=t.data,n=e.id,r=["file://","resource://android","null"],i=[e.origin,location.origin],s=e.origin===location.origin,o=i.some((t=>r.includes(t)));if((s||o)&&(!e.targetMapId||this.mapId===e.targetMapId)){if(""===e.type){delete this.tasks[n];const t=this.abortControllers[n];return delete this.abortControllers[n],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[n]=e,this.taskQueue.push(n),void this.invoker.trigger();this.processTask(n,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,n){return e(this,void 0,void 0,(function*(){if(""===n.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(n.error?e.reject(xs(n.error)):e.resolve(xs(n.data)))}if(!this.messageHandlers[n.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${n.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=xs(n.data),r=new AbortController;this.abortControllers[t]=r;try{const i=yield this.messageHandlers[n.type](n.sourceMapId,e,r);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,n){const r=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?gs(e):null,data:gs(n,r)};this.target.postMessage(i,{transfer:r});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.M=ct,t.N=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.O=function(t,e,n){var r,i,s,o,a,l,u,c,h,p,f,d,y=n[0],m=n[1],g=n[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],o=e[3],a=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=r=e[0],t[1]=i,t[2]=s,t[3]=o,t[4]=a,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=r*y+a*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=o*y+c*m+d*g+e[15]),t},t.P=n,t.Q=function(t,e,n){var r=n[0],i=n[1],s=n[2];return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.R=kl,t.S=function(t,e,n){var r=e[0],i=e[1],s=e[2],o=e[3],a=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=n[0],b=n[1],w=n[2],_=n[3];return t[0]=v*r+b*a+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*o+b*c+w*d+_*x,t[4]=(v=n[4])*r+(b=n[5])*a+(w=n[6])*h+(_=n[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*o+b*c+w*d+_*x,t[8]=(v=n[8])*r+(b=n[9])*a+(w=n[10])*h+(_=n[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*o+b*c+w*d+_*x,t[12]=(v=n[12])*r+(b=n[13])*a+(w=n[14])*h+(_=n[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*o+b*c+w*d+_*x,t},t.T=Ll,t.U=function(t,e){const n={};for(let r=0;r"symbol"===t.type,t.aR=tc,t.aS=oo,t.aT=gu,t.aU=Go,t.aV=la,t.aW=ia,t.aX=et,t.aY=jp,t.aZ=b,t.a_=v,t.aa=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((n=>{e.onloadstart=()=>{n(e);};for(const n of t){const t=window.document.createElement("source");dt(n)||(e.crossOrigin="Anonymous"),t.src=n,e.appendChild(t);}}))},t.ab=Dt,t.ac=function(){return $++},t.ad=Bo,t.ae=_p,t.af=Zd,t.ag=di,t.ah=qa,t.ai=Jp,t.aj=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,n,r,i)=>{const s=r||i;return e[n]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ak=V,t.al=85.051129,t.am=tt,t.an=function(t){return Math.pow(2,t)},t.ao=y,t.ap=Rp,t.aq=function(t){return Math.log(t)/Math.LN2},t.ar=function(t){var e=t[0],n=t[1];return e*e+n*n},t.as=function(t){if(!t.length)return new Set;const e=Math.max(...t.map((t=>t.canonical.z)));let n=1/0,r=-1/0,i=1/0,s=-1/0;const o=[];for(const a of t){const{x:t,y:l,z:u}=a.canonical,c=Math.pow(2,e-u),h=t*c,p=l*c;o.push({id:a,x:h,y:p}),hr&&(r=h),ps&&(s=p);}const a=new Set;for(const t of o)t.x!==n&&t.x!==r&&t.y!==i&&t.y!==s||a.add(t.id);return a},t.at=function(t,e){const n=Math.abs(2*t.wrap)-+(t.wrap<0),r=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||r-n||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x},t.au=class{constructor(t,e){this.max=t,this.onRemove=e,this.reset();}reset(){for(const t in this.data)for(const e of this.data[t])e.timeout&&clearTimeout(e.timeout),this.onRemove(e.value);return this.data={},this.order=[],this}add(t,e,n){const r=t.wrapped().key;void 0===this.data[r]&&(this.data[r]=[]);const i={value:e,timeout:void 0};if(void 0!==n&&(i.timeout=setTimeout((()=>{this.remove(t,i);}),n)),this.data[r].push(i),this.order.push(r),this.order.length>this.max){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}has(t){return t.wrapped().key in this.data}getAndRemove(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null}_getAndRemoveByKey(t){const e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value}getByKey(t){const e=this.data[t];return e?e[0].value:null}get(t){return this.has(t)?this.data[t.wrapped().key][0].value:null}remove(t,e){if(!this.has(t))return this;const n=t.wrapped().key,r=void 0===e?0:this.data[n].indexOf(e),i=this.data[n][r];return this.data[n].splice(r,1),i.timeout&&clearTimeout(i.timeout),0===this.data[n].length&&delete this.data[n],this.onRemove(i.value),this.order.splice(this.order.indexOf(n),1),this}setMaxSize(t){for(this.max=t;this.order.length>this.max;){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}filter(t){const e=[];for(const n in this.data)for(const r of this.data[n])t(r.value)||e.push(r);for(const t of e)this.remove(t.value.tileID,t);}},t.av=function(t,e){let n=0,r=0;if("constant"===t.kind)r=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:o}=t,a=i?V(yn.interpolationFactor(i,e,s,o),0,1):0;"camera"===t.kind?r=gn.number(t.minSize,t.maxSize,a):n=a;}return {uSizeT:n,uSize:r}},t.ax=function(t,{uSize:e,uSizeT:n},{lowerSize:r,upperSize:i}){return "source"===t.kind?r/pp:"composite"===t.kind?gn.number(r/pp,i/pp,n):e},t.ay=function(t,e){var n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=n*a-r*o,v=n*l-i*o,b=n*u-s*o,w=r*l-i*a,_=r*u-s*a,S=i*u-s*l,A=c*y-h*d,M=c*m-p*d,k=c*g-f*d,I=h*m-p*y,E=h*g-f*y,T=p*g-f*m,F=x*T-v*E+b*I+w*k-_*M+S*A;return F?(t[0]=(a*T-l*E+u*I)*(F=1/F),t[1]=(i*E-r*T-s*I)*F,t[2]=(y*S-m*_+g*w)*F,t[3]=(p*_-h*S-f*w)*F,t[4]=(l*k-o*T-u*M)*F,t[5]=(n*T-i*k+s*M)*F,t[6]=(m*b-d*S-g*v)*F,t[7]=(c*S-p*b+f*v)*F,t[8]=(o*E-a*k+u*A)*F,t[9]=(r*k-n*E-s*A)*F,t[10]=(d*_-y*b+g*x)*F,t[11]=(h*b-c*_-f*x)*F,t[12]=(a*M-o*I-l*A)*F,t[13]=(n*I-r*M+i*A)*F,t[14]=(y*v-d*w-m*x)*F,t[15]=(c*w-h*v+p*x)*F,t):null},t.az=I,t.b=Z,t.b$=class extends Aa{constructor(t,e){super(t,e),this.current=Ea;}set(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,!1,t);for(let e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,!1,t);break}}},t.b0=function(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t[2]=e[2]-n[2],t},t.b1=function(t,e){var n=e[0],r=e[1],i=e[2],s=n*n+r*r+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.b2=w,t.b3=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.b4=function(t,e,n){return t[0]=e[0]*n[0],t[1]=e[1]*n[1],t[2]=e[2]*n[2],t[3]=e[3]*n[3],t},t.b5=g,t.b6=function(t,e,n){const r=e[0]*n[0]+e[1]*n[1]+e[2]*n[2];return 0===r?null:(-(t[0]*n[0]+t[1]*n[1]+t[2]*n[2])-n[3])/r},t.b7=S,t.b8=function(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t},t.b9=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.bA=function(t,e,n){var r=n[0],i=n[1],s=n[2],o=n[3],a=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*a-r*u,p=r*l-i*a;return t[0]=a+o*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+o*h+s*c-r*p,t[2]=u+o*p+r*h-i*c,t},t.bB=function(t,e,n){const r=(i=[t[0],t[1],t[2],e[0],e[1],e[2],n[0],n[1],n[2]])[0]*((c=i[8])*(o=i[4])-(a=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+a*(l=i[6]))+i[2]*(u*s-o*l);var i,s,o,a,l,u,c;if(0===r)return null;const h=w([],[e[0],e[1],e[2]],[n[0],n[1],n[2]]),p=w([],[n[0],n[1],n[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-n[3])),b(d,d,1/r),d},t.bC=Bp,t.bD=function(){return new Float64Array(4)},t.bE=function(t,e,n,r){var i=[],s=[];return i[0]=e[0]-n[0],i[1]=e[1]-n[1],i[2]=e[2]-n[2],s[0]=i[0]*Math.cos(r)-i[1]*Math.sin(r),s[1]=i[0]*Math.sin(r)+i[1]*Math.cos(r),s[2]=i[2],t[0]=s[0]+n[0],t[1]=s[1]+n[1],t[2]=s[2]+n[2],t},t.bF=function(t,e,n,r){var i=[],s=[];return i[0]=e[0]-n[0],i[1]=e[1]-n[1],i[2]=e[2]-n[2],s[0]=i[0],s[1]=i[1]*Math.cos(r)-i[2]*Math.sin(r),s[2]=i[1]*Math.sin(r)+i[2]*Math.cos(r),t[0]=s[0]+n[0],t[1]=s[1]+n[1],t[2]=s[2]+n[2],t},t.bG=function(t,e,n,r){var i=[],s=[];return i[0]=e[0]-n[0],i[1]=e[1]-n[1],i[2]=e[2]-n[2],s[0]=i[2]*Math.sin(r)+i[0]*Math.cos(r),s[1]=i[1],s[2]=i[2]*Math.cos(r)-i[0]*Math.sin(r),t[0]=s[0]+n[0],t[1]=s[1]+n[1],t[2]=s[2]+n[2],t},t.bH=function(t,e,n){var r=Math.sin(n),i=Math.cos(n),s=e[0],o=e[1],a=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*r,t[1]=o*i-c*r,t[2]=a*i-h*r,t[3]=l*i-p*r,t[8]=s*r+u*i,t[9]=o*r+c*i,t[10]=a*r+h*i,t[11]=l*r+p*i,t},t.bI=function(t,e){const n=P(t,360),r=P(e,360),i=r-n,s=r>n?i-360:i+360;return Math.abs(i)0?o:-o},t.bL=function(t,e){const n=P(t,2*Math.PI),r=P(e,2*Math.PI);return Math.min(Math.abs(n-r),Math.abs(n-r+2*Math.PI),Math.abs(n-r-2*Math.PI))},t.bM=function(){const t={},e=bt.$version;for(const n in bt.$root){const r=bt.$root[n];if(r.required){let i=null;i="version"===n?e:"array"===r.type?[]:{},null!=i&&(t[n]=i);}}return t},t.bN=pt,t.bO=vs,t.bP=function t(e,n){if(Array.isArray(e)){if(!Array.isArray(n)||e.length!==n.length)return !1;for(let r=0;r"raster"===t.type,t.bU=U,t.bV=function(t,e){if(!t)return [{command:"setStyle",args:[e]}];let n=[];try{if(!St(t.version,e.version))return [{command:"setStyle",args:[e]}];St(t.center,e.center)||n.push({command:"setCenter",args:[e.center]}),St(t.state,e.state)||n.push({command:"setGlobalState",args:[e.state]}),St(t.centerAltitude,e.centerAltitude)||n.push({command:"setCenterAltitude",args:[e.centerAltitude]}),St(t.zoom,e.zoom)||n.push({command:"setZoom",args:[e.zoom]}),St(t.bearing,e.bearing)||n.push({command:"setBearing",args:[e.bearing]}),St(t.pitch,e.pitch)||n.push({command:"setPitch",args:[e.pitch]}),St(t.roll,e.roll)||n.push({command:"setRoll",args:[e.roll]}),St(t.sprite,e.sprite)||n.push({command:"setSprite",args:[e.sprite]}),St(t.glyphs,e.glyphs)||n.push({command:"setGlyphs",args:[e.glyphs]}),St(t.transition,e.transition)||n.push({command:"setTransition",args:[e.transition]}),St(t.light,e.light)||n.push({command:"setLight",args:[e.light]}),St(t.terrain,e.terrain)||n.push({command:"setTerrain",args:[e.terrain]}),St(t.sky,e.sky)||n.push({command:"setSky",args:[e.sky]}),St(t.projection,e.projection)||n.push({command:"setProjection",args:[e.projection]});const r={},i=[];!function(t,e,n,r){let i;for(i in e=e||{},t=t||{})Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)||kt(i,n,r));for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&(Object.prototype.hasOwnProperty.call(t,i)?St(t[i],e[i])||("geojson"===t[i].type&&"geojson"===e[i].type&&Et(t,e,i)?At(n,{command:"setGeoJSONSourceData",args:[i,e[i].data]}):It(i,e,n,r)):Mt(i,e,n));}(t.sources,e.sources,i,r);const s=[];t.layers&&t.layers.forEach((t=>{"source"in t&&r[t.source]?n.push({command:"removeLayer",args:[t.id]}):s.push(t);})),n=n.concat(i),function(t,e,n){e=e||[];const r=(t=t||[]).map(Ft),i=e.map(Ft),s=t.reduce(Pt,{}),o=e.reduce(Pt,{}),a=r.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),o=Math.sin(i),a=Math.sin((1-r)*i)/o,l=Math.sin(r*i)/o):(a=1-r,l=r),t[0]=a*u+l*d,t[1]=a*c+l*y,t[2]=a*h+l*m,t[3]=a*f+l*g,t},t.bl=function(t){const e=new Float64Array(9);var n,r,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(r=t)[0])*(l=i+i),p=(s=r[1])*l,d=(o=r[2])*l,y=o*(u=s+s),g=(a=r[3])*l,x=a*u,v=a*(c=o+o),(n=e)[0]=1-(f=s*u)-(m=o*c),n[3]=p-v,n[6]=d+x,n[1]=p+v,n[4]=1-h-m,n[7]=y-g,n[2]=d-x,n[5]=y+g,n[8]=1-h-f;const b=et(-Math.asin(V(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.bm=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bn=Ee,t.bo=Ma,t.bp=xu,t.bq=vu,t.br=mu,t.bs=D,t.bt=z,t.bu=Re,t.bv=function(t,e,n,r,i){return D(r,i,V((t-e)/(n-e),0,1))},t.bw=function(t,e,n,r){return t[0]=e[0]+n[0]*r,t[1]=e[1]+n[1]*r,t[2]=e[2]+n[2]*r,t},t.bx=P,t.by=function(){return new Float64Array(3)},t.bz=k,t.c=lt,t.c$=class{get tiles(){return this.tileIndex?.tiles??{}}get stats(){return this.tileIndex.stats}get total(){return this.tileIndex.total}constructor(t,e){const n=(e=this.options=Object.assign({},nh,e)).debug;if(n&&console.time("preprocess data"),e.maxZoom<0||e.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");let r=cc(t,e);n&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",e.indexMaxZoom,e.indexMaxPoints),console.time("generate tiles")),r=Cc(r,e),e.updateable&&(this.source=r),this.initializeIndex(r,e);}initializeIndex(t,e){this.tileIndex=e.cluster?new Nc(e.clusterOptions):new th(e),t.length&&this.tileIndex.initialize(t);}getTile(t,e,n){return e=+e,n=+n,(t=+t)<0||t>24?null:this.tileIndex.getTile(t,e,n)}updateData(t,e){const n=this.options;if(!n.updateable)throw new Error("to update tile geojson `updateable` option must be set to true");let{affected:r,source:i}=function(t,e,n){const r=function(t){return t?{removeAll:t.removeAll,remove:new Set(t.remove||[]),add:new Map(t.add?.map((t=>[t.id,t]))),update:new Map(t.update?.map((t=>[t.id,t])))}:{remove:new Set,add:new Map,update:new Map}}(e);let i=[];if(r.removeAll&&(i=t,t=[]),r.remove.size||r.add.size){const e=[];for(const n of t)(r.remove.has(n.id)||r.add.has(n.id))&&e.push(n);if(e.length){i.push(...e);const n=new Set(e.map((t=>t.id)));t=t.filter((t=>!n.has(t.id)));}if(r.add.size){let e=cc({type:"FeatureCollection",features:Array.from(r.add.values())},n);e=Cc(e,n),i.push(...e),t.push(...e);}}if(r.update.size)for(const[e,s]of r.update){const r=[],o=[];for(const n of t)n.id===e?r.push(n):o.push(n);if(!r.length)continue;const a=Oc(r,s,n);a.length&&(i.push(...r,...a),o.push(...a),t=o);}return {affected:i,source:t}}(this.source,t,n);e&&({affected:r,source:i}=this.filterUpdate(i,r,e)),r.length&&(this.source=i,this.tileIndex.updateIndex(i,r,n));}filterUpdate(t,e,n){const r=new Set;for(const i of t)null!=i.id&&(n(mc(i))||(e.push(i),r.add(i.id)));return {affected:e,source:t=t.filter((t=>!r.has(t.id)))}}getData(){if(!this.options.updateable)throw new Error("to retrieve data the `updateable` option must be set to true");return {type:"FeatureCollection",features:this.source.map((t=>mc(t)))}}updateClusterOptions(t,e){const n=this.options.cluster;this.options.cluster=t,this.options.clusterOptions=e,n!=t?this.initializeIndex(this.source,this.options):this.tileIndex.updateIndex(this.source,[],this.options);}getClusterExpansionZoom(t){return this.tileIndex.getClusterExpansionZoom(t)}getClusterChildren(t){return this.tileIndex.getChildren(t)}getClusterLeaves(t,e,n){return this.tileIndex.getLeaves(t,e,n)}},t.c0=ka,t.c1=class extends Aa{constructor(t,e){super(t,e),this.current=[0,0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));}},t.c2=class extends Aa{constructor(t,e){super(t,e),this.current=[0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));}},t.c3=d,t.c4=function(t,e){var n=Math.sin(e),r=Math.cos(e);return t[0]=r,t[1]=n,t[2]=0,t[3]=-n,t[4]=r,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.c5=function(t,e,n){var r=e[0],i=e[1],s=e[2];return t[0]=r*n[0]+i*n[3]+s*n[6],t[1]=r*n[1]+i*n[4]+s*n[7],t[2]=r*n[2]+i*n[5]+s*n[8],t},t.c6=function(t,e,n,r,i,s,o){var a=1/(e-n),l=1/(r-i),u=1/(s-o);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*u,t[11]=0,t[12]=(e+n)*a,t[13]=(i+r)*l,t[14]=(o+s)*u,t[15]=1,t},t.c7=class extends Aa{constructor(t,e){super(t,e),this.current=new Array;}set(t){if(t!=this.current){this.current=t;const e=new Float32Array(4*t.length);for(let n=0;n25||r<0||r>=1||n<0||n>=1)},t.cD=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cE=class extends uo{},t.cF=ht,t.cG=function(t,e){lt.REGISTERED_PROTOCOLS[t]=e;},t.cH=function(t){delete lt.REGISTERED_PROTOCOLS[t];},t.cI=function(t,e){const n={};for(let r=0;rt*Sh));}let v=l?"center":i.get("text-justify").evaluate(s,{},e.canonical);const b="point"===i.get("symbol-placement")?i.get("text-max-width").evaluate(s,{},e.canonical)*Sh:1/0,w=()=>{e.bucket.allowVerticalPlacement&&Ss(n)&&(y.vertical=ep(m,e.glyphMap,e.glyphPositions,e.imagePositions,h,b,a,d,"left",c,x,t.aw.vertical,!0,f,p));};if(!l&&g){const n=new Set;if("auto"===v)for(let t=0;tHd(t,e,n)),t.layers[r]);}(t,n,e),n.finish()},t.cS=function(t,e,n,r,i,s){let o=oy(t,e,n,i,0);return o=oy(o,e,r,s,1),o},t.cT=class{constructor(t){this.maxEntries=t,this.map=new Map;}get(t){const e=this.map.get(t);return void 0!==e&&(this.map.delete(t),this.map.set(t,e)),e}set(t,e){if(this.map.has(t))this.map.delete(t);else if(this.map.size>=this.maxEntries){const t=this.map.keys().next().value;this.map.delete(t);}this.map.set(t,e);}clear(){this.map.clear();}},t.cU=Ru,t.cV=Vh,t.cW=Xd,t.cX=function(t,n,r,i,s){return e(this,void 0,void 0,(function*(){if(h())try{return yield W(t,n,r,i,s)}catch(t){}return function(t,e,n,r,i){const s=t.width,o=t.height;K&&J||(K=new OffscreenCanvas(s,o),J=K.getContext("2d",{willReadFrequently:!0})),K.width=s,K.height=o,J.drawImage(t,0,0,s,o);const a=J.getImageData(e,n,r,i);return J.clearRect(0,0,s,o),a.data}(t,n,r,i,s)}))},t.cY=Ol,t.cZ=class{constructor(t,e){this.layers={[Zd]:this},this.name=Zd,this.version=e?e.version:1,this.extent=e?e.extent:4096,this.length=t.length,this.features=t;}feature(t){return new Yd(this.features[t],this.extent)}},t.c_=ii,t.ca=wh,t.cb=class extends Ao{},t.cc=Tl,t.cd=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.ce=El,t.cf=function(t,e,n){var r=e[0],i=e[1],s=e[2],o=n[3]*r+n[7]*i+n[11]*s+n[15];return t[0]=(n[0]*r+n[4]*i+n[8]*s+n[12])/(o=o||1),t[1]=(n[1]*r+n[5]*i+n[9]*s+n[13])/o,t[2]=(n[2]*r+n[6]*i+n[10]*s+n[14])/o,t},t.cg=class extends co{},t.ch=class extends Po{},t.ci=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.cj=function(t,e){var n=t[0],r=t[1],i=t[2],s=t[3],o=t[4],a=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],M=e[6],k=e[7],I=e[8],E=e[9],T=e[10],F=e[11],P=e[12],D=e[13],z=e[14],B=e[15];return Math.abs(n-v)<=p*Math.max(1,Math.abs(n),Math.abs(v))&&Math.abs(r-b)<=p*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(o-S)<=p*Math.max(1,Math.abs(o),Math.abs(S))&&Math.abs(a-A)<=p*Math.max(1,Math.abs(a),Math.abs(A))&&Math.abs(l-M)<=p*Math.max(1,Math.abs(l),Math.abs(M))&&Math.abs(u-k)<=p*Math.max(1,Math.abs(u),Math.abs(k))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-E)<=p*Math.max(1,Math.abs(h),Math.abs(E))&&Math.abs(f-T)<=p*Math.max(1,Math.abs(f),Math.abs(T))&&Math.abs(d-F)<=p*Math.max(1,Math.abs(d),Math.abs(F))&&Math.abs(y-P)<=p*Math.max(1,Math.abs(y),Math.abs(P))&&Math.abs(m-D)<=p*Math.max(1,Math.abs(m),Math.abs(D))&&Math.abs(g-z)<=p*Math.max(1,Math.abs(g),Math.abs(z))&&Math.abs(x-B)<=p*Math.max(1,Math.abs(x),Math.abs(B))},t.ck=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cl=t=>"circle"===t.type,t.cm=t=>"heatmap"===t.type,t.cn=t=>"line"===t.type,t.co=t=>"fill"===t.type,t.cp=t=>"fill-extrusion"===t.type,t.cq=t=>"hillshade"===t.type,t.cr=t=>"color-relief"===t.type,t.cs=t=>"background"===t.type,t.ct=t=>"custom"===t.type,t.cu=B,t.cv=function(t,e,n){if(e<=0)return t;const r=1/e;return void 0===n||Math.abs(n)<1e-10?Math.round(t*r)/r:(n>0?Math.ceil(t*r-1e-9):Math.floor(t*r+1e-10))/r},t.cw=function(t,e,n){const r=E(e.x-n.x,e.y-n.y),i=E(t.x-n.x,t.y-n.y);var s,o;return et(Math.atan2(r[0]*i[1]-r[1]*i[0],(s=r)[0]*(o=i)[0]+s[1]*o[1]))},t.cx=C,t.cy=function(t,e){var n;if(!rt[e])return !1;const r=null==t?void 0:t.target,i=(null===(n=null==r?void 0:r.ownerDocument)||void 0===n?void 0:n.defaultView)||window;return t instanceof i.MouseEvent||t instanceof i.WheelEvent},t.cz=function(t,e){return nt[e]&&"touches"in t},t.d=dt,t.d0=zs,t.e=O,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ut,t.h=t=>new Promise(((e,n)=>{const r=new Image;r.onload=()=>{e(r),URL.revokeObjectURL(r.src),r.onload=null,window.requestAnimationFrame((()=>{r.src=H;}));},r.onerror=()=>n(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});r.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ft(O(t,{type:"json"}),e),t.k=xt,t.l=gt,t.m=ft,t.n=(t,e)=>ft(O(t,{type:"arrayBuffer"}),e),t.o=function(t){return new Vh(t).readFields(Zh,[])},t.p=Kh,t.q=function(t){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(t))},t.r=Ml,t.s=Q,t.t=Ws,t.u=bt,t.v=is,t.w=q,t.x=$s,t.y=os,t.z=Vs;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,s,i){for(const s of t){this._layerConfigs[s.id]=s;const t=this._layers[s.id]=e.bS(s,i);t._featureFilter=e.ag(t.filter,i),this.keyCache[s.id]&&delete this.keyCache[s.id];}for(const e of s)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const r=e.cI(Object.values(this._layerConfigs),this.keyCache);for(const t of r){const s=t.map((e=>this._layers[e.id])),i=s[0];if(i.isHidden())continue;const r=i.source||"";let o=this.familiesBySource[r];o||(o=this.familiesBySource[r]={});const n=i.sourceLayer||e.af;let a=o[n];a||(a=o[n]=[]),a.push(s);}}}class s{constructor(t){const s={},i=[];for(const e in t){const r=t[e],o=s[e]={};for(const e in r){const t=r[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const s={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(s),o[e]={rect:s,metrics:t.metrics};}}const{w:r,h:o}=e.p(i),n=new e.r({width:r||1,height:o||1});for(const i in t){const r=t[i];for(const t in r){const o=r[+t];if(!o||0===o.bitmap.width||0===o.bitmap.height)continue;const a=s[i][t].rect;e.r.copy(o.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},o.bitmap);}}this.image=n,this.positions=s;}}e.cJ("GlyphAtlas",s);class i{constructor(t){this.tileID=new e.a2(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,i,o,n,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.ad;const l=new e.cK(Object.keys(t.layers).sort()),c=new e.cL(this.tileID,this.promoteId);c.bucketLayerIDs=[];const h={},d={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},dashDependencies:{},availableImages:o,subdivisionGranularity:a},u=i.familiesBySource[this.source];for(const s in u){const i=t.layers[s];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${s}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=l.encode(s),a=[];for(let e=0;ee.id))));}}const g=e.bX(d.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let p=Promise.resolve({});if(Object.keys(g).length){const e=new AbortController;this.inFlightDependencies.push(e),p=n.sendAsync({type:"GG",data:{stacks:g,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const f=Object.keys(d.iconDependencies);let y=Promise.resolve({});if(f.length){const e=new AbortController;this.inFlightDependencies.push(e),y=n.sendAsync({type:"GI",data:{icons:f,source:this.source,tileID:this.tileID,type:"icons"}},e);}const m=Object.keys(d.patternDependencies);let v=Promise.resolve({});if(m.length){const e=new AbortController;this.inFlightDependencies.push(e),v=n.sendAsync({type:"GI",data:{icons:m,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const S=d.dashDependencies;let _=Promise.resolve({});if(Object.keys(S).length){const e=new AbortController;this.inFlightDependencies.push(e),_=n.sendAsync({type:"GDA",data:{dashes:S}},e);}const[w,b,I,k]=yield Promise.all([p,y,v,_]),T=new s(w),x=new e.cM(b,I);for(const t in h){const s=h[t];s instanceof e.ae?(r(s.layers,this.zoom,o),e.cN({bucket:s,glyphMap:w,glyphPositions:T.positions,imageMap:b,imagePositions:x.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:d.subdivisionGranularity})):s.hasDependencies&&(s instanceof e.cO||s instanceof e.cP||s instanceof e.cQ)&&(r(s.layers,this.zoom,o),s.addFeatures(d,this.tileID.canonical,x.patternPositions,k));}return this.status="done",{buckets:Object.values(h).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:T.image,imageAtlas:x,dashPositions:k,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?b:null,glyphPositions:this.returnDependencies?T.positions:null}}))}}function r(t,s,i){const r=new e.H(s);for(const e of t)e.recalculate(r,i);}class o{constructor(){this.loading={},this.loaded={},this.parsing={};}startLoading(e,t){this.loading[e]=t;}finishLoading(e){delete this.loading[e];}abort(e){const t=this.loading[e];(null==t?void 0:t.abort)&&(t.abort.abort(),delete this.loading[e]);}setParsing(e,t){this.parsing[e]=t;}consumeParsing(e){const t=this.parsing[e];if(t)return delete this.parsing[e],t}clearParsing(e){delete this.parsing[e];}markLoaded(e,t){this.loaded[e]=t;}getLoaded(e){const t=this.loaded[e];if(t)return t}removeLoaded(e){delete this.loaded[e];}clearLoaded(){this.loaded={};}}class n{constructor(e){this.start=`${e}#start`,this.end=`${e}#end`,this.measure=e,performance.mark(this.start);}finish(){performance.mark(this.end);let e=performance.getEntriesByName(this.measure);return 0===e.length&&(performance.measure(this.measure,this.start,this.end),e=performance.getEntriesByName(this.measure),performance.clearMarks(this.start),performance.clearMarks(this.end),performance.clearMeasures(this.measure)),e}}class a{constructor(e,t,s,i,r){this.type=e,this.properties=s||{},this.extent=r,this.pointsArray=t,this.id=i;}loadGeometry(){return this.pointsArray.map((t=>t.map((t=>new e.P(t.x,t.y)))))}}class l{constructor(e,t,s){this.version=2,this._myFeatures=e,this.name=t,this.length=e.length,this.extent=s;}feature(e){return this._myFeatures[e]}}class c{constructor(){this.layers={};}addLayer(e){this.layers[e.name]=e;}}function h(t){let s=e.cR(t);return 0===s.byteOffset&&s.byteLength===s.buffer.byteLength||(s=new Uint8Array(s)),{vectorTile:t,rawData:s.buffer}}function d(t,s,i){const{extent:r}=t,o=Math.pow(2,i.z-s.z),n=(i.x-s.x*o)*r,c=(i.y-s.y*o)*r,h=[];for(let s=0;s0&&l.addLayer(r);}const g=h(l);return this.overzoomedTileResultCache.set(n,g),g}reloadTile(t){return e._(this,void 0,void 0,(function*(){const e=t.uid,s=this.tileState.getLoaded(e);if(!s)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(s.showCollisionBoxes=t.showCollisionBoxes,"parsing"===s.status){const i=this.tileState.consumeParsing(e);return yield this._parseWorkerTile(s,t,i)}if("done"===s.status&&s.vectorTile)return yield this._parseWorkerTile(s,t)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){this.tileState.abort(t.uid);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(t.uid);}))}}class g{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:s,encoding:i,rawImageData:r,redFactor:o,greenFactor:n,blueFactor:a,baseShift:l}=t,c=r.width+2,h=r.height+2,d=e.b(r)?new e.R({width:c,height:h},yield e.cX(r,-1,-1,c,h)):r,u=new e.cY(s,d,i,o,n,a,l);return this.loaded=this.loaded||{},this.loaded[s]=u,u}))}removeTile(e){const t=this.loaded,s=e.uid;t&&t[s]&&delete t[s];}}class p{constructor(e,t,s,i=f){this.actor=e,this.layerIndex=t,this.availableImages=s,this.tileState=new o,this._createGeoJSONIndex=i;}loadVectorTile(t){if(!this._geoJSONIndex)throw new Error("Unable to parse the data into a cluster or geojson");const{z:s,x:i,y:r}=t.tileID.canonical,o=this._geoJSONIndex.getTile(s,i,r);return o?h(new e.cZ(o.features,{version:2,extent:e.a5})):null}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:e}=t,s=new i(t);s.abort=new AbortController;try{const i=this.loadVectorTile(t);if(!i)return null;const{vectorTile:r,rawData:o}=i;s.vectorTile=r,this.tileState.markLoaded(e,s);const n={rawData:o};this.tileState.setParsing(e,n);try{return yield this._parseWorkerTile(s,t,n)}finally{this.tileState.clearParsing(e);}}catch(t){throw s.status="done",this.tileState.markLoaded(e,s),t}}))}_reloadLoadedTile(t){return e._(this,void 0,void 0,(function*(){const e=t.uid,s=this.tileState.getLoaded(e);if(!s)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(s.showCollisionBoxes=t.showCollisionBoxes,"parsing"===s.status){const i=this.tileState.consumeParsing(e);return yield this._parseWorkerTile(s,t,i)}if("done"===s.status&&s.vectorTile)return yield this._parseWorkerTile(s,t)}))}_parseWorkerTile(t,s,i){return e._(this,void 0,void 0,(function*(){let r=yield t.parse(t.vectorTile,this.layerIndex,this.availableImages,this.actor,s.subdivisionGranularity);if(i){const{rawData:t}=i;r=e.e({rawTileData:t.slice(0),encoding:"mvt"},r);}return r}))}abortTile(t){return e._(this,void 0,void 0,(function*(){this.tileState.abort(t.uid);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(t.uid);}))}loadData(t){return e._(this,void 0,void 0,(function*(){var s;null===(s=this._pendingRequest)||void 0===s||s.abort();const i=this._startRequestTiming(t);this._pendingRequest=new AbortController;try{yield this.loadAndProcessGeoJSON(t,this._pendingRequest),delete this._pendingRequest,this.tileState.clearLoaded();const e={};return t.request&&(e.data=t.data),this._finishRequestTiming(i,t,e),e}catch(t){if(delete this._pendingRequest,!e.Z(t))throw t;return {abandoned:!0}}}))}_startRequestTiming(e){var t;if(null===(t=e.request)||void 0===t?void 0:t.collectResourceTiming)return new n(e.request.url)}_finishRequestTiming(e,t,s){const i=null==e?void 0:e.finish();i&&(s.resourceTiming={[t.source]:JSON.parse(JSON.stringify(i))});}reloadTile(e){return this.tileState.getLoaded(e.uid)?this._reloadLoadedTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,s){return e._(this,void 0,void 0,(function*(){var i;if(t.request&&(t.data=(yield e.j(t.request,s)).data),t.data)return t.data=this._filterGeoJSON(t.data,t.filter),void(this._geoJSONIndex=this._createGeoJSONIndex(t.data,t));if(t.dataDiff)return null!==(i=this._geoJSONIndex)&&void 0!==i||(this._geoJSONIndex=this._createGeoJSONIndex({type:"FeatureCollection",features:[]},t)),void this._geoJSONIndex.updateData(t.dataDiff,this._getFilterPredicate(t.filter));if(t.updateCluster&&this._geoJSONIndex.updateClusterOptions(t.geojsonVtOptions.cluster,y(t)),null==this._geoJSONIndex)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}))}_filterGeoJSON(e,t){if("FeatureCollection"!==e.type)return e;const s=this._getFilterPredicate(t);return s?{type:"FeatureCollection",features:e.features.filter((e=>s(e)))}:e}_getFilterPredicate(t){if("boolean"!=typeof t&&!(null==t?void 0:t.length))return;const s=e.c_(t,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===s.result)throw new Error(s.value.map((e=>`${e.key}: ${e.message}`)).join(", "));return e=>s.value.evaluate({zoom:0},e)}removeSource(t){return e._(this,void 0,void 0,(function*(){var e;null===(e=this._pendingRequest)||void 0===e||e.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getClusterChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getClusterLeaves(e.clusterId,e.limit,e.offset)}}function f(t,s){const i=e.e(s.geojsonVtOptions||{},{updateable:!0,clusterOptions:y(s)});return new e.c$(t,i)}function y({geojsonVtOptions:t,clusterProperties:s}){if(!s||!t.clusterOptions)return t.clusterOptions;const i={},r={},o={accumulated:null,zoom:0},n={properties:null},a=Object.keys(s);for(const t of a){const[o,n]=s[t],a=e.c_(n),l=e.c_("string"==typeof o?[o,["accumulated"],["get",t]]:o);i[t]=a.value,r[t]=l.value;}return t.clusterOptions.map=e=>{n.properties=e;const t={};for(const e of a)t[e]=i[e].evaluate(o,n);return t},t.clusterOptions.reduce=(e,t)=>{n.properties=t;for(const t of a)o.accumulated=e[t],e[t]=r[t].evaluate(o,n);},t.clusterOptions}class m{constructor(t){this.self=t,this.actor=new e.L(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cG,this.self.removeProtocol=e.cH,this.self.registerRTLTextPlugin=t=>{e.d0.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,s)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,s.source).removeTile(s);})))),this.actor.registerMessageHandler("GCEZ",((t,s)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,s.type,s.source).getClusterExpansionZoom(s)})))),this.actor.registerMessageHandler("GCC",((t,s)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,s.type,s.source).getClusterChildren(s)})))),this.actor.registerMessageHandler("GCL",((t,s)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,s.type,s.source).getClusterLeaves(s)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,s)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][s.type]||!this.workerSources[t][s.type][s.source])return;const e=this.workerSources[t][s.type][s.source];delete this.workerSources[t][s.type][s.source],void 0!==e.removeSource&&e.removeSource(s);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,s)=>e._(this,void 0,void 0,(function*(){this.referrer=s;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,s)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(s);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,s)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(s.layers,s.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,s)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in s)e[t]=s[t];})))),this.actor.registerMessageHandler("SL",((t,s)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(s,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,s){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=s;for(const e in this.workerSources[t]){const i=this.workerSources[t][e];for(const e in i)i[e].availableImages=s;}}))}_syncRTLPluginState(t,s){return e._(this,void 0,void 0,(function*(){return yield e.d0.syncState(s,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let s=this.layerIndexes[e];return s||(s=this.layerIndexes[e]=new t),s}_getWorkerSource(e,t,s){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][s]){const i={sendAsync:(t,s)=>(t.targetMapId=e,this.actor.sendAsync(t,s))};switch(t){case "vector":this.workerSources[e][t][s]=new u(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][s]=new p(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][s]=new this.externalWorkerSourceTypes[t](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][s]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new g),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new m(self)),m})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.22.0";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let a,r,s;const n={frame(e,i,o,a){const r=a||window,s=r.requestAnimationFrame((e=>{n(),i(e);})),{unsubscribe:n}=t.s(e.signal,"abort",(()=>{n(),r.cancelAnimationFrame(s),o(new t.a(e.signal.reason));}),!1);},frameAsync(e,t){return new Promise(((i,o)=>{this.frame(e,i,o,t);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(a||(a=document.createElement("a")),a.href=e,a.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return void 0!==s?s:!!matchMedia&&(null==r&&(r=matchMedia("(prefers-reduced-motion: reduce)")),r.matches)},set prefersReducedMotion(e){s=e;}},l=new class{constructor(){this._frozenAt=null;}getCurrentTime(){return null!==this._frozenAt?this._frozenAt:performance.now()}setNow(e){this._frozenAt=e;}restoreNow(){this._frozenAt=null;}isFrozen(){return null!==this._frozenAt}};function c(){return l.getCurrentTime()}class h{static create(e,t,i){const o=window.document.createElement(e);return void 0!==t&&(o.className=t),i&&i.appendChild(o),o}static createNS(e,t){return window.document.createElementNS(e,t)}static disableDrag(){h.docStyle&&h.selectProp&&(h.userSelect=h.docStyle[h.selectProp],h.docStyle[h.selectProp]="none");}static enableDrag(){h.docStyle&&h.selectProp&&(h.docStyle[h.selectProp]=h.userSelect);}static suppressClickInternal(e){e.preventDefault(),e.stopPropagation(),window.removeEventListener("click",h.suppressClickInternal,!0);}static suppressClick(){window.addEventListener("click",h.suppressClickInternal,!0),window.setTimeout((()=>{window.removeEventListener("click",h.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const a=i.boundingClientRect;return new t.P((o.clientX-a.left)/i.x-e.clientLeft,(o.clientY-a.top)/i.y-e.clientTop)}static mousePos(e,t){const i=h.getScale(e);return h.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=h.getScale(e);for(let a=0;a{i=[],o=0,a=0,r={};},e.addThrottleControl=e=>{const t=a++;return r[t]=e,t},e.removeThrottleControl=e=>{delete r[e],n();},e.getImage=(e,o,a=!0)=>new Promise(((r,s)=>{e.headers||(e.headers={}),e.headers.accept="image/webp,*/*",t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:a,state:"queued",onError:e=>{s(e);},onSuccess:e=>{r(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:a,onError:r,onSuccess:s,abortController:c}=e,h=!1===a&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?l(i,c):t.m(i,c);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,r(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(r))if(r[e]())return !0;return !1})()?t.c.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.c.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},l=(e,i)=>new Promise(((o,a)=>{const r=new Image,s=e.url,n=e.credentials;n&&"include"===n?r.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(r.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{r.src="",a(new t.a(i.signal.reason));})),r.fetchPriority="high",r.onload=()=>{r.onerror=r.onload=null,o({data:r});},r.onerror=()=>{r.onerror=r.onload=null,i.signal.aborted||a(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."));},r.src=s;}));}(u||(u={})),u.resetRequestQueue();class d{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function _(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:a}of e){const e=`${o}${a}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:a}));}}return t}function p(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function m(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class f extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}destroy(){this.atlasTexture&&(this.atlasTexture.destroy(),this.atlasTexture=null);for(const e of Object.keys(this.images))this.removeImage(e);this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const a=i.data||i.spriteData;return this._validateStretch(i.stretchX,a&&a.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,a&&a.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},a=new t.I(i,o);this.patterns[e]={bin:i,position:a};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),a=this.atlasImage;a.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,r=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,a,{x:0,y:0},{x:o,y:r},{width:n,height:l}),t.R.copy(s,a,{x:0,y:l-1},{x:o,y:r-1},{width:n,height:1}),t.R.copy(s,a,{x:0,y:0},{x:o,y:r+l},{width:n,height:1}),t.R.copy(s,a,{x:n-1,y:0},{x:o-1,y:r},{width:1,height:l}),t.R.copy(s,a,{x:0,y:0},{x:o+n,y:r},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),m(e)&&this.updateImage(i,e);}}cloneImages(){const e={};for(const t in this.images){const i=this.images[t];e[t]=Object.assign(Object.assign({},i),{data:i.data?i.data.clone():null});}return e}}const g=1e20;function v(e,t,i,o,a,r,s,n,l){for(let c=t;c-1);l++,r[l]=n,s[l]=c,s[l+1]=g;}for(let n=0,l=0;n/[-\w]+/.test(e)?e:`'${CSS.escape(e)}'`)).join(",");return new y.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:i,fontWeight:this._fontWeight(t[0]),fontStyle:this._fontStyle(t[0]),lang:this.lang})}_fontStyle(e){return /italic/i.test(e)?"italic":/oblique/i.test(e)?"oblique":"normal"}_fontWeight(e){const t={thin:100,hairline:100,"extra light":200,"ultra light":200,light:300,normal:400,regular:400,medium:500,semibold:600,demibold:600,bold:700,"extra bold":800,"ultra bold":800,black:900,heavy:900,"extra black":950,"ultra black":950};let i;for(const[o,a]of Object.entries(t))new RegExp(`\\b${o}\\b`,"i").test(e)&&(i=`${a}`);return i}destroy(){for(const e in this.entries){const t=this.entries[e];t.tinySDF&&(t.tinySDF=null),t.ideographTinySDF&&(t.ideographTinySDF=null),t.glyphs={},t.requests={},t.ranges={};}this.entries={};}}y.loadGlyphRange=function(e,i,o,a){return t._(this,void 0,void 0,(function*(){const r=256*i,s=r+255,n=yield a.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${r}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${r}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},y.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:a="sans-serif",fontWeight:r="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${r} ${e}px ${a}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:a,actualBoundingBoxRight:r}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(r-a))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:x}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const b=p.getImageData(m,m,n,l);x.fill(g,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}v(x,0,0,c,h,c,this.f,this.v,this.z),v(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++r]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[a+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let a=0,r=e[a];for(let t=0;t1&&(r=e[++a]);const i=Math.abs(t-r.left),s=Math.abs(t-r.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(r.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,a=2*o+1;if(this.nextRow+a>this.height)return t.w("LineAtlas out of space"),null;let r=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[E]}numActive(){return Object.keys(this.active).length}}const R=Math.floor(n.hardwareConcurrency/2);let z,D;function A(){return z||(z=new S),z}S.workerCount=t.K(globalThis)?Math.max(Math.min(R,3),1):1;class L{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}unregisterMessageHandler(e){for(const t of this.actors)t.unregisterMessageHandler(e);}}function k(){return D||(D=new L(A(),t.M),D.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),D}function F(e,i){const o=t.N();return t.O(o,o,[1,1,0]),t.Q(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.S(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function B(e,t,i,o,a,r,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==a?void 0:a.layers)&&void 0!==n?n:null,t,e.id),c=r.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(O);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e.getState(),o.queryGeometry,o.cameraQueryGeometry,o.scale,a,r,c,F(r,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])j(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,a=o.wrappedTileID,r=i[a]=i[a]||{};for(const i in e){const o=e[i],a=r[i]=r[i]||{},s=t[i]=t[i]||[];for(const e of o)a[e.featureIndex]||(a[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function O(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function j(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o,a){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(yield i.transformRequest(e.url,"Source"),o)).data:yield n.frameAsync(o,a),!r)return null;const s=t.U(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(s.vectorLayerIds=r.vector_layers.map((e=>e.id))),s}))}class N{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.V?new t.V(e.lng,e.lat):t.V.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.V?new t.V(e.lng,e.lat):t.V.convert(e),this}extend(e){const i=this._sw,o=this._ne;let a,r;if(e instanceof t.V)a=e,r=e;else {if(!(e instanceof N))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(N.convert(e)):this.extend(t.V.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.V.convert(e)):this;if(a=e._sw,r=e._ne,!a||!r)return this}return i||o?(i.lng=Math.min(a.lng,i.lng),i.lat=Math.min(a.lat,i.lat),o.lng=Math.max(r.lng,o.lng),o.lat=Math.max(r.lat,o.lat)):(this._sw=new t.V(a.lng,a.lat),this._ne=new t.V(r.lng,r.lat)),this}getCenter(){return new t.V((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.V(this.getWest(),this.getNorth())}getSouthEast(){return new t.V(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.V.convert(e);let a=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(a=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&a}intersects(e){if(!((e=N.convert(e)).getNorth()>=this.getSouth()&&e.getSouth()<=this.getNorth()))return !1;const i=Math.abs(this.getEast()-this.getWest()),o=Math.abs(e.getEast()-e.getWest());if(i>=360||o>=360)return !0;const a=t.W(this.getWest(),-180,180),r=t.W(this.getEast(),-180,180),s=t.W(e.getWest(),-180,180),n=t.W(e.getEast(),-180,180),l=a>r,c=s>n;return !(!l||!c)||(l?n>=a||s<=r:c?r>=s||a<=n:s<=r&&n>=a)}static convert(e){return e instanceof N?e:e?new N(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,a=o/Math.cos(Math.PI/180*e.lat);return new N(new t.V(e.lng-a,e.lat-o),new t.V(e.lng+a,e.lat+o))}adjustAntiMeridian(){const e=new t.V(this._sw.lng,this._sw.lat),i=new t.V(this._ne.lng,this._ne.lat);return new N(e,e.lng>i.lng?new t.V(i.lng+360,i.lat):i)}}class U{constructor(e,t,i){this.bounds=N.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.Y(this.bounds.getWest())*i),a=Math.floor(t.X(this.bounds.getNorth())*i),r=Math.ceil(t.Y(this.bounds.getEast())*i),s=Math.ceil(t.X(this.bounds.getSouth())*i);return e.x>=o&&e.x=a&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:yield this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity,encoding:this.encoding,overzoomParameters:yield this._getOverzoomParameters(e),etag:e.etag};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);const a={};return (null==t?void 0:t.etagUnmodified)&&(a.unmodified=!0),a}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_getOverzoomParameters(e){return t._(this,void 0,void 0,(function*(){if(e.tileID.canonical.z<=this.maxzoom)return;if(void 0===this.map._zoomLevelsToOverscale)return;const t=e.tileID.scaledTo(this.maxzoom).canonical,i=t.url(this.tiles,this.map.getPixelRatio(),this.scheme);return {maxZoomTileID:t,overzoomRequest:yield this.map._requestManager.transformRequest(i,"Tile")}}))}_afterTileLoadWorkerResponse(e,t){if((null==t?void 0:t.resourceTiming)&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.etag=null==t?void 0:t.etag,e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class V extends t.E{constructor(e,i,o,a){super(),this.id=e,this.dispatcher=o,this.setEventedParent(a),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.U(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest,this.map._ownerWindow);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new U(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,t.Z(e)||this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield u.getImage(yield this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,a=i.gl,r=o.data;e.texture=this.map.painter.getTileTexture(r.width),e.texture?e.texture.update(r,{useMipmap:!0}):(e.texture=new t.T(i,r,a.RGBA,{useMipmap:!0}),e.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends V{constructor(e,i,o,a){super(e,i,o,a),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=yield this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield u.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const a=t.b(o)&&t.$()?o:yield this.readImageNow(o),r={type:this.type,uid:e.uid,source:this.id,rawImageData:a,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(e.actor&&"expired"!==e.state&&"reloading"!==e.state)return;e.actor&&"expired"!==e.state||(e.actor=this.dispatcher.getActor());const s=yield e.actor.sendAsync({type:"LDT",data:r});e.dem=s,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.a0()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.a1(e,-1,-1,i,o))}catch(e){}}return n.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),a=(i.x-1+o)%o,r=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.a2(e.overscaledZ,r,i.z,a,i.y).key]={backfilled:!1},l[new t.a2(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.a2(e.overscaledZ,r,i.z,a,i.y-1).key]={backfilled:!1},l[new t.a2(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.a2(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.key===i));t>-1&&e.addOrUpdateProperties.splice(t,1);}return (e.removeAllProperties||t.removeAllProperties)&&(i.removeAllProperties=!0),(e.removeProperties||t.removeProperties)&&(i.removeProperties=[...e.removeProperties||[],...t.removeProperties||[]]),(e.addOrUpdateProperties||t.addOrUpdateProperties)&&(i.addOrUpdateProperties=[...e.addOrUpdateProperties||[],...t.addOrUpdateProperties||[]]),(e.newGeometry||t.newGeometry)&&(i.newGeometry=t.newGeometry||e.newGeometry),i}function H(e){var t,i;if(!e)return {};const o={};return o.removeAll=e.removeAll,o.remove=new Set(e.remove||[]),o.add=new Map(null===(t=e.add)||void 0===t?void 0:t.map((e=>[e.id,e]))),o.update=new Map(null===(i=e.update)||void 0===i?void 0:i.map((e=>[e.id,e]))),o}function X(e){return e&&0!==e.length?"number"==typeof e[0]?[e]:e.flatMap((e=>X(e))):[]}function K(e){return "GeometryCollection"===e.type?e.geometries.flatMap((e=>K(e))):X(e.coordinates)}function Y(e){const t=new N;let i;switch(e.type){case "FeatureCollection":i=e.features.flatMap((e=>K(e.geometry)));break;case "Feature":i=K(e.geometry);break;default:i=K(e);}if(0===i.length)return t;for(let e=0;e0||(null===(a=i.addOrUpdateProperties)||void 0===a?void 0:a.length)>0;if(!s&&!n)continue;r.push(t.geometry);const l=Object.assign({},t);if(e.set(i.id,l),s&&(r.push(i.newGeometry),l.geometry=i.newGeometry),n){if(l.properties=i.removeAllProperties?{}:Object.assign({},l.properties||{}),i.removeProperties)for(const e of i.removeProperties)delete l.properties[e];if(i.addOrUpdateProperties)for(const{key:e,value:t}of i.addOrUpdateProperties)l.properties[e]=t;}}return r}(this._data.updateable,e,t);return e.removeAll||this._options.cluster?void 0:i}_getShouldReloadTileOptions(e){if(e)return {affectedBounds:e.filter(Boolean).map((e=>Y(e)))}}shouldReloadTile(e,{affectedBounds:i}){if("loading"===e.state)return !0;if("unloaded"===e.state)return !1;const{buffer:o,extent:a}=this.workerOptions.geojsonVtOptions,r=function({x:e,y:i,z:o},a=0){const r=t.a3((e-a)/Math.pow(2,o)),s=t.a4((i+1+a)/Math.pow(2,o)),n=t.a3((e+1+a)/Math.pow(2,o)),l=t.a4((i-a)/Math.pow(2,o));return new N([r,s],[n,l])}(e.tileID.canonical,o/a);for(const e of i)if(r.intersects(e))return !0;return !1}loaded(){return !this._isUpdatingWorker&&!this._hasPendingWorkerUpdate()}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data.updateable?{type:"FeatureCollection",features:Array.from(this._data.updateable.values())}:this._data.url||this._data.geojson})}hasTransition(){return !1}}class J extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield u.getImage(yield this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,t.Z(e)||this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a6.fromLngLat);var o;return this.tileID=function(e){const i=t.a7.fromPoints(e),o=i.width(),a=i.height(),r=Math.max(o,a),s=Math.max(0,Math.floor(-Math.log(r)/Math.LN2)),n=Math.pow(2,s);return new t.a9(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:a,maxY:r}=t.a7.fromPoints(e),s={};for(let e=0;e<=t.a8;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(a*t),h=Math.floor(r*t),u=(n%t+t)%t,d=c%t,_=Math.floor(n/t),p=Math.floor(c/t);s[e]={minWrap:_,maxWrap:p,minTileXWrapped:u,maxTileXWrapped:d,minTileY:l,maxTileY:h};}return s}}class ee extends J{constructor(e,t,i,o){super(e,t,i,o),this._onPlayingHandler=()=>{var e;null===(e=this.map)||void 0===e||e.triggerRepaint();},this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push((yield this.map._requestManager.transformRequest(t,"Source")).url);try{const e=yield t.aa(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",this._onPlayingHandler),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.ab(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}onRemove(){super.onRemove(),this.video&&(this.video.removeEventListener("playing",this._onPlayingHandler),this.video.pause());}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class te extends J{constructor(e,i,o,a){super(e,i,o,a),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.ab(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.ab(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.ab(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.ab(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.ab(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):(this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0}),this.texture.bind(o.LINEAR,o.CLAMP_TO_EDGE));let a=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,a=!0);}a&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",animate:this.animate,canvas:this.options.canvas,coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const ie={},oe=e=>{switch(e){case "geojson":return Q;case "image":return J;case "raster":return V;case "raster-dem":return W;case "vector":return G;case "video":return ee;case "canvas":return te}return ie[e]},ae="RTLPluginLoaded";class re extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=k();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=n.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ae));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let se=null;function ne(){return se||(se=new re),se}var le,ce;!function(e){e[e.Base=0]="Base",e[e.Parent=1]="Parent";}(le||(le={})),function(e){e[e.Departing=0]="Departing",e[e.Incoming=1]="Incoming";}(ce||(ce={}));class he{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.fadeOpacity=1,this.tileID=e,this.uid=t.ac(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttFingerprint={},this.expiredRequestCount=0,this.state="loading";}isRenderable(e){return this.hasData()&&(!this.fadeEndTime||this.fadeOpacity>0)&&(e||!this.holdingForSymbolFade())}setCrossFadeLogic({fadingRole:e,fadingDirection:t,fadingParentID:i,fadeEndTime:o}){this.resetFadeLogic(),this.fadingRole=e,this.fadingDirection=t,this.fadingParentID=i,this.fadeEndTime=o;}setSelfFadeLogic(e){this.resetFadeLogic(),this.selfFading=!0,this.fadeEndTime=e;}resetFadeLogic(){this.fadingRole=null,this.fadingDirection=null,this.fadingParentID=null,this.selfFading=!1,this.timeAdded=c(),this.fadeEndTime=0,this.fadeOpacity=1;}wasRequested(){return "errored"===this.state||"loaded"===this.state||"reloading"===this.state}clearTextures(e){this.demTexture&&e.saveTileTexture(this.demTexture),this.demTexture=null;}loadVectorData(e,i,o){if(!0!==(null==e?void 0:e.etagUnmodified))if(this.hasData()&&this.unloadVectorData(),this.state="loaded",e){e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestEncoding=e.encoding,this.latestFeatureIndex.rawTileData=e.rawTileData,this.latestFeatureIndex.encoding=e.encoding):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData,this.latestFeatureIndex.encoding=this.latestEncoding)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=function(e,t){const i={};if(!t)return i;for(const o of e){const e=o.layerIds.map((e=>t.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.ae){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.ae&&i.hasRTLText){this.hasRTLText=!0,ne().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage),this.dashPositions=e.dashPositions;}else this.collisionBoxArray=new t.ad;else this.state="loaded";}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.dashPositions&&(this.dashPositions=null),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,a,r,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:a,scale:r,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const a=o.loadVTLayers(),r=i&&i.sourceLayer?i.sourceLayer:"",s=a[t.af]||a[r];if(!s)return;const n=t.ag(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),b=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)b.push(x(-e)),b.push(x(e));for(b.push(x(0));b.length>0;){const _=b.pop(),f=_.x,x=_.y;let w=_.fullyVisible;const T={x:f,y:x,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=xe(o,P,a);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(r.x,r.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||we)(e.zoom+t.aq(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const Ce=t.a7.fromPoints([new t.P(0,0),new t.P(t.a5,t.a5)]);function Ie(e){return "raster"===e||"image"===e||"video"===e}function Me(e,t,i,o,a,r,s){if(!t.hasData())return !1;const{tileID:n,fadingRole:l,fadingDirection:c,fadingParentID:h}=t;if(l===le.Base&&c===ce.Incoming&&h)return i[h.key]=h,!0;const u=Math.max(n.overscaledZ-a,r);for(let a=n.overscaledZ-1;a>=u;a--){const r=n.scaledTo(a),l=e.getLoadedTile(r);if(l)return t.setCrossFadeLogic({fadingRole:le.Base,fadingDirection:ce.Incoming,fadingParentID:l.tileID,fadeEndTime:o+s}),l.setCrossFadeLogic({fadingRole:le.Parent,fadingDirection:ce.Departing,fadeEndTime:o+s}),i[r.key]=r,!0}return !1}function Ee(e,t,i,o,a,r){if(!t.hasData())return !1;const s=t.tileID.children(a);let n=Se(e,t,s,i,o,a,r);if(n)return !0;for(const l of s)Se(e,t,l.children(a),i,o,a,r)&&(n=!0);return n}function Se(e,t,i,o,a,r,s){if(i[0].overscaledZ>=r)return !1;let n=!1;for(const r of i){const i=e.getLoadedTile(r);if(!i)continue;const{fadingRole:l,fadingDirection:c,fadingParentID:h}=i;l===le.Base&&c===ce.Departing&&h||(i.setCrossFadeLogic({fadingRole:le.Base,fadingDirection:ce.Departing,fadingParentID:t.tileID,fadeEndTime:a+s}),t.setCrossFadeLogic({fadingRole:le.Parent,fadingDirection:ce.Incoming,fadeEndTime:a+s})),o[r.key]=r,n=!0;}return n}function Re(e,t,i,o){const a=e.tileID;return !!e.selfFading||!e.hasData()&&!!t.has(a)&&(e.setSelfFadeLogic(i+o),!0)}function ze(e,t){var i;e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0;let o=t.tileID.canonical.x-e.tileID.canonical.x;const a=t.tileID.canonical.y-e.tileID.canonical.y,r=Math.pow(2,e.tileID.canonical.z),s=t.tileID.key;0===o&&0===a||Math.abs(a)>1||(Math.abs(o)>1&&(1===Math.abs(o+r)?o+=r:1===Math.abs(o-r)&&(o-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,o,a),(null===(i=e.neighboringTiles)||void 0===i?void 0:i[s])&&(e.neighboringTiles[s].backfilled=!0)));}class De{constructor(){this._tiles={};}handleWrapJump(e){const t={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+e),t[o.tileID.key]=o;}this._tiles=t;}setFeatureState(e,t){for(const i in this._tiles)this._tiles[i].setFeatureState(e,t);}getAllTiles(){return Object.values(this._tiles)}getAllIds(e=!1){return e?Object.values(this._tiles).map((e=>e.tileID)).sort(t.at).map((e=>e.key)):Object.keys(this._tiles)}getTileById(e){return this._tiles[e]}setTile(e,t){this._tiles[e]=t;}deleteTileById(e){delete this._tiles[e];}getLoadedTile(e){const t=this.getTileById(e.key);return (null==t?void 0:t.hasData())?t:null}isIdRenderable(e,t=!1){var i;return null===(i=this.getTileById(e))||void 0===i?void 0:i.isRenderable(t)}getRenderableIds(e=0,i){const o=[];for(const e of this.getAllIds())this.isIdRenderable(e,i)&&o.push(this.getTileById(e));return i?o.sort(((i,o)=>{const a=i.tileID,r=o.tileID,s=new t.P(a.canonical.x,a.canonical.y)._rotate(-e),n=new t.P(r.canonical.x,r.canonical.y)._rotate(-e);return a.overscaledZ-r.overscaledZ||n.y-s.y||n.x-s.x})).map((e=>e.tileID.key)):o.map((e=>e.tileID)).sort(t.at).map((e=>e.key))}}class Ae extends t.E{constructor(e,i,o){super(),this.id=e,this.dispatcher=o,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const a=new(oe(t.type))(e,t,i,o);if(a.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${a.id}`);return a})(e,i,o,this),this._inViewTiles=new De,this._outOfViewCache=new t.au(0,(e=>this._unloadTile(e))),this._timers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._rasterFadeDuration=0,this._maxFadingAncestorLevels=5,this._state=new ue,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){for(const e of this._inViewTiles.getAllTiles())e.unloadVectorData();this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e),this._inViewTiles=new De;}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e of this._inViewTiles.getAllTiles())if("loaded"!==e.state&&"errored"!==e.state)return !1;return !0}getSource(){return this._source}getState(){return this._state}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{const t=yield this._source.loadTile(e);this._tileLoaded(e,i,o,t);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._inViewTiles,this.map?this.map.painter:null);for(const t of this._inViewTiles.getAllTiles())t.upload(e),t.prepare(this.map.style.imageManager);}getIds(){return this._inViewTiles.getAllIds(!0)}getRenderableIds(e){var t;return this._inViewTiles.getRenderableIds(null===(t=this.transform)||void 0===t?void 0:t.bearingInRadians,e)}hasRenderableParent(e){const t=e.overscaledZ-1;if(t>=this._source.minzoom){const i=this.getLoadedTile(e.scaledTo(t));if(i)return this._inViewTiles.isIdRenderable(i.tileID.key)}return !1}reload(e,t=void 0){if(this._paused)this._shouldReloadOnResume=!0;else {this._outOfViewCache.reset();for(const i of this._inViewTiles.getAllIds()){const o=this._inViewTiles.getTileById(i);t&&!this._source.shouldReloadTile(o,t)||(e?this._reloadTile(i,"expired"):"errored"!==o.state&&this._reloadTile(i,"reloading"));}}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._inViewTiles.getTileById(e);t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o,a){e.timeAdded=c(),e.selfFading&&(e.fadeEndTime=e.timeAdded+this._rasterFadeDuration),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),(null==a?void 0:a.unmodified)||("raster-dem"===this.getSource().type&&e.dem&&function(e,t){var i,o;const a=t.getRenderableIds();for(const r of a){if(!e.neighboringTiles||!e.neighboringTiles[r])continue;const a=t.getTileById(r);e.neighboringTiles[r].backfilled||ze(e,a),(null===(o=null===(i=a.neighboringTiles)||void 0===i?void 0:i[e.tileID.key])||void 0===o?void 0:o.backfilled)||ze(a,e);}}(e,this._inViewTiles),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID})));}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._inViewTiles.getTileById(e)}_retainLoadedChildren(e,t){const i=this._getLoadedDescendents(t),o=new Set;for(const a of t){const t=i[a.key];if(!(null==t?void 0:t.length)){o.add(a);continue}const r=a.overscaledZ+Ae.maxOverzooming,s=t.filter((e=>e.tileID.overscaledZ<=r));if(!s.length){o.add(a);continue}const n=Math.min(...s.map((e=>e.tileID.overscaledZ))),l=s.filter((e=>e.tileID.overscaledZ===n)).map((e=>e.tileID));for(const t of l)e[t.key]=t;this._areDescendentsComplete(l,n,a.overscaledZ)||o.add(a);}return o}_getLoadedDescendents(e){var t;const i={};for(const o of this._inViewTiles.getAllTiles().filter((e=>e.hasData())))for(const a of e)o.tileID.isChildOf(a)&&(i[t=a.key]||(i[t]=[])).push(o);return i}_areDescendentsComplete(e,t,i){return 1===e.length&&e[0].isOverscaled()?e[0].overscaledZ===t:Math.pow(4,t-i)===e.length}getLoadedTile(e){return this._inViewTiles.getLoadedTile(e)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,a=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.c.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),r="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,a):a;this._outOfViewCache.setMaxSize(r);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);this._prevLng=e,t&&(this._inViewTiles.handleWrapJump(t),this._resetTileReloadTimers());}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.a2(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=Pe(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:"vector"===this._source.type&&void 0!==this.map._zoomLevelsToOverscale?e.maxZoom-this.map._zoomLevelsToOverscale:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[],this.usedForTerrain&&(o=this._addTerrainIdealTiles(o));const a=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,a&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const r=Te(e,this._source),s=this._updateRetainedTiles(o,r),n=Ie(this._source.type);n&&this._rasterFadeDuration>0&&!i&&function(e,i,o,a,r,s,n){const l=c(),h=t.as(i);for(const t of i){const i=e.getTileById(t.key);i.fadingDirection!==ce.Departing&&0!==i.fadeOpacity||i.resetFadeLogic(),Me(e,i,o,l,a,r,n)||Ee(e,i,o,l,s,n)||Re(i,h,l,n)||i.resetFadeLogic();}}(this._inViewTiles,o,s,this._maxFadingAncestorLevels,this._source.minzoom,this._source.maxzoom,this._rasterFadeDuration),n?this._cleanUpRasterTiles(s):this._cleanUpVectorTiles(s);}_cleanUpRasterTiles(e){for(const t of this._inViewTiles.getAllIds())e[t]||this._removeTile(t);}_cleanUpVectorTiles(e){for(const t of this._inViewTiles.getAllIds()){const i=this._inViewTiles.getTileById(t);e[t]?i.clearSymbolFadeHold():i.hasSymbolBuckets?i.holdingForSymbolFade()?i.symbolFadeFinished()&&this._removeTile(t):i.setSymbolHoldDuration(this.map._fadeDuration):this._removeTile(t);}}_addTerrainIdealTiles(e){const t=[];for(const i of e)if(i.canonical.z>this._source.minzoom){const e=i.scaledTo(i.canonical.z-1);t.push(e);const o=i.scaledTo(Math.max(this._source.minzoom,Math.min(i.canonical.z,5)));t.push(o);}return e.concat(t)}releaseSymbolFadeTiles(){for(const e of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(e).holdingForSymbolFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o=new Set;for(const t of e)this._addTile(t).hasData()||o.add(t);const a=e.reduce(((e,t)=>(e[t.key]=t,e)),{}),r=this._retainLoadedChildren(a,o),s={},n=Math.max(t-Ae.maxUnderzooming,this._source.minzoom);for(const e of r){let t=this._inViewTiles.getTileById(e.key),o=null==t?void 0:t.wasRequested();for(let r=e.overscaledZ-1;r>=n;--r){const n=e.scaledTo(r);if(s[n.key])break;if(s[n.key]=!0,t=this.getTile(n),!t&&o&&(t=this._addTile(n)),t){const e=t.hasData();if((e||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||o)&&(a[n.key]=n),o=t.wasRequested(),e)break}}}return a}_addTile(e){let i=this._inViewTiles.getTileById(e.key);if(i)return i;i=this._outOfViewCache.getAndRemove(e),i&&(i.resetFadeLogic(),this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null));const o=i;return i||(i=new he(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._inViewTiles.setTile(e.key,i),o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){this._clearTileReloadTimer(e);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}_clearTileReloadTimer(e){const t=this._timers[e];t&&(clearTimeout(t),delete this._timers[e]);}_resetTileReloadTimers(){for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e of this._inViewTiles.getAllIds()){const t=this._inViewTiles.getTileById(e);this._setTileReloadTimer(e,t);}}refreshTiles(e){for(const t of this._inViewTiles.getAllIds()){const i=this._inViewTiles.getTileById(t);(this._inViewTiles.isIdRenderable(t)||"errored"==i.state)&&e.some((e=>e.equals(i.tileID.canonical)))&&this._reloadTile(t,"expired");}}_removeTile(e){const t=this._inViewTiles.getTileById(e);t&&(t.uses--,this._inViewTiles.deleteTileById(e),this._clearTileReloadTimer(e),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._outOfViewCache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){"source"===e.dataType&&("metadata"!==e.sourceDataType?"content"===e.sourceDataType&&this._sourceLoaded&&!this._paused&&(this.reload(e.sourceDataChanged,e.shouldReloadTileOptions),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0):this._sourceLoaded=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e of this._inViewTiles.getAllIds())this._removeTile(e);this._outOfViewCache.reset();}tilesIn(e,i,o){const a=[],r=this.transform;if(!r)return a;const s=r.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?r.getCameraQueryGeometry(e):e,l=e=>r.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a7.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a6(i.x,i.y))));if(i.expandBy(_),i.intersects(Ce)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));a.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return a}transformBbox(e,i,o){let a=e.map(i);if(o){const o=t.a7.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const r=o.map(i);t.a7.fromPoints(a).covers(r)||(a=a.map((e=>e.x>.5?new t.a6(e.x-1,e.y,e.z):e)));}return a}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._inViewTiles.getTileById(e).tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){return !!this._source.hasTransition()||!(!Ie(this._source.type)||!function(e,t){if(t<=0)return !1;const i=c();for(const t of e.getAllTiles())if(t.fadeEndTime>=i)return !0;return !1}(this._inViewTiles,this._rasterFadeDuration))}setRasterFadeDuration(e){this._rasterFadeDuration=e;}setFeatureState(e,i,o){this._state.updateState(e=e||t.af,i,o);}removeFeatureState(e,i,o){this._state.removeFeatureState(e=e||t.af,i,o);}getFeatureState(e,i){return this._state.getState(e=e||t.af,i)}setDependencies(e,t,i){const o=this._inViewTiles.getTileById(e);o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(i).hasDependency(e,t)&&this._reloadTile(i,"reloading");this._outOfViewCache.filter((i=>!i.hasDependency(e,t)));}areTilesLoaded(){for(const e of this._inViewTiles.getAllTiles())if("loaded"!==e.state&&"errored"!==e.state)return !1;return !0}}Ae.maxUnderzooming=10,Ae.maxOverzooming=3;class Le{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(a-s)/n:0;return this.points[r].mult(1-l).add(this.points[i].mult(l))}}function ke(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Fe{constructor(e,t,i){const o=this.boxCells=[],a=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(a)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,a){const r=e-i,s=e+i,n=t-i,l=t+i;if(s<0||r>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(r,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},a),c.length>0}_queryCell(e,t,i,o,a,r,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[a],d=1e-6;if(null!==u){const a=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,_=this.boxKeys[s];if(e<=a[u+2]+d&&t<=a[u+3]+d&&i>=a[u+0]-d&&o>=a[u+1]-d&&(!n||n(_))&&(!c||!ke(h,_.overlapMode))&&(r.push({key:_,x1:a[u],y1:a[u+1],x2:a[u+2],y2:a[u+3]}),c))return !0}}const _=this.circleCells[a];if(null!==_){const a=this.circles;for(const s of _)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(a[u],a[u+1],a[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!ke(h,d.overlapMode))){const e=a[u],t=a[u+1],i=a[u+2];if(r.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,a,r,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[a];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!ke(h,o.overlapMode))return r.push(!0),!0}}const d=this.circleCells[a];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!ke(h,o.overlapMode))return r.push(!0),!0}}}_forEachCell(e,t,i,o,a,r,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(a.call(this,e,t,i,o,this.xCellCount*l+d,r,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,a,r){const s=o-e,n=a-t,l=i+r;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,a,r,s){const n=(r-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-a)/2,h=Math.abs(t-(a+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Be(e,i,a){const r=t.N();if(!e){const{vecSouth:e,vecEast:t}=je(i),a=o();a[0]=t[0],a[1]=t[1],a[2]=e[0],a[3]=e[1],s=a,(d=(l=(n=a)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),r[0]=a[0],r[1]=a[1],r[4]=a[2],r[5]=a[3];}var s,n,l,c,h,u,d;return t.Q(r,r,[1/a,1/a,1]),r}function Oe(e,i,o,a){if(e){const e=t.N();if(!i){const{vecSouth:t,vecEast:i}=je(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.Q(e,e,[a,a,1]),e}return o.pixelsToClipSpaceMatrix}function je(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),a=Math.cos(e.pitchInRadians),r=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.az();n[0]=-r*a*o-s*i,n[1]=-s*a*o+r*i;const l=t.aA(n);l<1e-9?t.aB(n):t.aC(n,n,1/l);const c=t.az();c[0]=r*a*i-s*o,c[1]=s*a*i+r*o;const h=t.aA(c);return h<1e-9?t.aB(c):t.aC(c,c,1/h),{vecEast:c,vecSouth:n}}function Ze(e,i,o,a){let r;a?(r=[e,i,a(e,i),1],t.aE(r,r,o)):(r=[e,i,0,1],ot(r,r,o));const s=r[3];return {point:new t.P(r[0]/s,r[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Ne(e,t){return .5+e/t*.5}function Ue(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function Ge(e,i,o,a,r,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.av(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,x=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,b=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*a?{useVertical:!0}:(e===t.aw.vertical?i.yo.x)?{needsFlipping:!0}:null}function qe(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:a,fontSize:r,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=r/24,_=a.lineOffsetX*d,p=a.lineOffsetY*d;let m;if(a.numGlyphs>1){const e=a.glyphStartIndex+a.numGlyphs,t=a.lineStartIndex,r=a.lineStartIndex+a.lineLength,c=Ve(d,l,_,p,s,a,u,i);if(!c)return {notEnoughRoom:!0};const f=Ke(c.first.point.x,c.first.point.y,i,o),g=Ke(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=We(a.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=a.glyphStartIndex+1;o0?n.point:$e(i.tileAnchorPoint,s,e,1,i),c=Ke(e.x,e.y,i,o),u=Ke(l.x,l.y,i,o),d=We(a.writingMode,c,u,h);if(d)return d}const e=et(d*l.getoffsetX(a.glyphStartIndex),_,p,s,a.segment,a.lineStartIndex,a.lineStartIndex+a.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.aD(c,e.point,e.angle);return {}}function $e(e,t,i,o,a){const r=e.add(e.sub(t)._unit()),s=Xe(r.x,r.y,a).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function He(e,i,o){const a=i.projectionCache;if(a.projections[e])return a.projections[e];const r=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Xe(r.x,r.y,i);if(s.signedDistanceFromCamera>0)return a.projections[e]=s.point,a.anyProjectionOccluded=a.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return $e(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),r,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Xe(e,t,i){const o=e+i.translation[0],a=t+i.translation[1];let r;return i.pitchWithMap?(r=Ze(o,a,i.pitchedLabelPlaneMatrix,i.getElevation),r.isOccluded=!1):(r=i.transform.projectTileCoordinates(o,a,i.unwrappedTileID,i.getElevation),r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height),r}function Ke(e,i,o,a){if(o.pitchWithMap){const r=[e,i,0,1];return t.aE(r,r,a),o.transform.projectTileCoordinates(r[0]/r[3],r[1]/r[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ye(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Qe(e,t,i){return e._unit()._perp()._mult(t*i)}function Je(e,i,o,a,r,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=r)return l.projectionCache.offsets[e]=h,h;const u=He(e+c.direction,l,c),d=Qe(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.aF(s,h,_,p)||h,l.projectionCache.offsets[e]}function et(e,t,i,o,a,r,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?r+a:r+a+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Xe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,x=0;const b=Math.abs(c),y=[];let w;for(;v+x<=b;){if(_+=h,_=s)return null;v+=x,g=f,m=p;const e={absOffsetX:b,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=He(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Qe(He(_+h,n,e).sub(f),i,h):Qe(o,i,h),m||(m=g.add(t)),p=Je(_,t,f,r,s,m,i,n,e),y.push(m),w=p.sub(m);}x=w.mag();}const T=w._mult((b-v)/x)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const tt=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function it(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=a.x&&e.y>=o.y&&i.y<=a.y?[_]:i.xa.x||i.ya.y?[]:t.aG([_],o.x,o.y,a.x,a.y);}for(const t of f){r.reset(t,.25*i);let o=0;o=r.length<=.5*i?1:Math.ceil(r.paddedLength/p)+1;for(let t=0;t{const t=Ze(e.x,e.y,o,i.getElevation),a=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height,a}))}(e,i);return function(e){let t=0,i=0,o=0,a=0;for(let r=0;ri&&(i=a,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a7;for(const a of e){const e=new t.P(a.x+at,a.y+at);o.extend(e),i.push(e);}const{minX:a,minY:r,maxX:s,maxY:n}=o,l=this.grid.query(a,r,s,n).concat(this.ignoredGrid.query(a,r,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const a=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.aH(i,a)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,a,r){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:a,collisionGroupID:r,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,a,r){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:a,collisionGroupID:r,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,a,c,u)));S=e.some((e=>!e.isOccluded)),E=e.map((e=>new t.P(e.x,e.y)));}else S=!0;return {box:t.aI(E),allPointsOccluded:!S}}}class st{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class nt{constructor(e,t,i,o,a){this.text=new st(e?e.text:null,t,i,a),this.icon=new st(e?e.icon:null,t,o,a);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class lt{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class ct{constructor(e,t,i,o,a){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=a;}}class ht{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function ut(e,i,o,a,r){const{horizontalAlign:s,verticalAlign:n}=t.aP(e);return new t.P(-(s-.5)*i+a[0]*r,-(n-.5)*o+a[1]*r)}class dt{constructor(e,t,i,o,a){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new rt(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new ht(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=a,a&&(a.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,a){const r=o.getBucket(i),s=o.latestFeatureIndex;if(!r||!s||i.id!==r.layerIds[0])return;const n=o.collisionBoxArray,l=r.layers[0].layout,c=r.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.a5,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aK(o,1,this.transform.zoom),m=t.aL(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aL(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Be(_,this.transform,p);this.retainedQueryData[r.bucketInstanceId]=new ct(r.bucketInstanceId,s,r.sourceLayerIndex,r.index,o.tileID);const v={bucket:r,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForSymbolFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.av(r.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(r.sourceID)};if(a)for(const t of r.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:a}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:a,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:r.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,a,r,s,n,l,c,h,u,d,_,p,m,f,g,v,x,b){const y=t.aM[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=ut(y,o,a,w,r),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,x,T,b);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,x,T,b).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:a,anchor:y,textBoxScale:r,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:a,layout:r,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=r.get("text-optional"),f=r.get("icon-optional"),g=t.aN(r,"text-overlap","text-allow-overlap"),v="always"===g,x=t.aN(r,"icon-overlap","icon-allow-overlap"),b="always"===x,y="map"===r.get("text-rotation-alignment"),w="map"===r.get("text-pitch-alignment"),T="none"!==r.get("icon-text-fit"),P="viewport-y"===r.get("symbol-z-order"),C=v&&(b||!a.hasIconData()||f),I=b&&(v||!a.hasTextData()||m);!a.collisionArrays&&d&&a.deserializeCollisionBoxes(d);const M=this.retainedQueryData[a.bucketInstanceId].tileID,E=this._getTerrainElevationFunc(M),S=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,b)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new lt(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,Z=0,N=0,U=0;d.textFeatureIndex?Z=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(Z=e.featureIndex),d.verticalTextFeatureIndex&&(N=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.aw.horizontal;if(a.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(a,o,e));}return o},r=(i,o)=>{if(a.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of a.writingModes)if(e===t.aw.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,E,void 0,S);return o&&o.placeable&&(this.markUsedOrientation(a,i,e),this.placedOrientations[e.crossTileID]=i),o};r((()=>o(G,t.aw.horizontal)),(()=>{const i=d.verticalTextBox;return a.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.aw.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aM[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,r)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===x?i:null;let b=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.aw.horizontal)),(()=>{const i=d.verticalTextBox;return a.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.aw.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(a,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles&&e.centerJustifiedTextSymbolIndex>=0){const i=a.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ax(a.textSizeData,_,i),h=r.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,a.lineVertexArray,a.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,E),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(U=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,x,h,M,l,w,y,n,p.predicate,E,T&&L?L:void 0,S);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,W=f||0===e.numIconVertices;V||W?W?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,r.get("text-ignore-placement"),a.bucketInstanceId,F&&F.placeable&&N?N:Z,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,x,r.get("icon-ignore-placement"),a.bucketInstanceId,U,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,r.get("text-ignore-placement"),a.bucketInstanceId,Z,p.ID),o&&this.storeCollisionData(a.bucketInstanceId,b,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===a.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new lt((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||a.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=a.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(a.symbolInstances.get(i),a.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=r>=0&&t!==r?0:o.crossTileID);}markUsedOrientation(e,i,o){const a=i===t.aw.horizontal||i===t.aw.horizontalOnly?i:0,r=i===t.aw.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=a;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=r);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,a=t?t.opacities:{},r=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],r=a[e];r?(this.opacities[e]=new nt(r,o,t.text,t.icon),i=i||t.text!==r.text.placed||t.icon!==r.icon.placed):(this.opacities[e]=new nt(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in a){const t=a[e];if(!this.opacities[e]){const a=new nt(t,o,!1,!1);a.isHidden()||(this.opacities[e]=a,i=i||t.text.placed||t.icon.placed);}}for(const e in r)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=r[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,a){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const r=e.layers[0],s=r.layout,n=new nt(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=r._unevaluatedLayout.hasValue("text-variable-anchor")||r._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new nt(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&a&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(a);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[a.crossTileID],x=v===t.aw.vertical,b=v===t.aw.horizontal||v===t.aw.horizontalOnly;if(r>0||s>0){const t=yt(c.text);m(e.text,r,x?wt:t),m(e.text,s,b?wt:t);const i=c.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||x?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=i||b?1:0);const o=this.variableOffsets[a.crossTileID];o&&this.markUsedJustification(e,o.anchor,a,v);const n=this.placedOrientations[a.crossTileID];n&&(this.markUsedJustification(e,"left",a,n),this.markUsedOrientation(e,n,a));}if(g){const t=yt(c.icon),i=!(_&&a.verticalPlacedIconSymbolIndex&&x);a.placedIconSymbolIndex>=0&&(m(e.icon,a.numIconVertices,i?t:wt),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=c.icon.isHidden()),a.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,a.numVerticalIconVertices,i?wt:t),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=ut(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let a;o.textBox&&(a=x),o.verticalTextBox&&(a=b),_t(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||a,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!b&&o.verticalIconBox);let a;o.iconBox&&(a=t),o.verticalIconBox&&(a=!t),_t(e.iconCollisionBox.collisionVertexArray,c.icon.placed,a,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function _t(e,t,i,o,a,r){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-at,n=o[1]-at,l=o[2]-at,c=o[3]-at;e.emplaceBack(t?1:0,i?1:0,a||0,r||0,s,n),e.emplaceBack(t?1:0,i?1:0,a||0,r||0,l,n),e.emplaceBack(t?1:0,i?1:0,a||0,r||0,l,c),e.emplaceBack(t?1:0,i?1:0,a||0,r||0,s,c);}const pt=Math.pow(2,25),mt=Math.pow(2,24),ft=Math.pow(2,17),gt=Math.pow(2,16),vt=Math.pow(2,9),xt=Math.pow(2,8),bt=Math.pow(2,1);function yt(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*pt+t*mt+i*ft+t*gt+i*vt+t*xt+i*bt+t}const wt=0;class Tt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,a){const r=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&c()-a>2;for(;this._currentPlacementIndex>=0;){const a=i[e[this._currentPlacementIndex]],s=this.placement.collisionIndex.transform.zoom;if(t.aQ(a)&&a.layout&&(!a.minzoom||a.minzoom<=s)&&(!a.maxzoom||a.maxzoom>s)){if(this._inProgressLayer||(this._inProgressLayer=new Tt(a)),this._inProgressLayer.continuePlacement(o[a.source],this.placement,this._showCollisionBoxes,a,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const Ct=512/t.a5/2;class It{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const a=new Map;for(let e=0;e({x:Math.floor(e.anchorX*Ct),y:Math.floor(e.anchorY*Ct)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aR(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:a,z:r}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=Ct/Math.pow(2,l-r),h=(n*t.a5+e.anchorY)*c,u=a*t.a5*Ct;return {x:Math.floor((s*t.a5+e.anchorX)*c-o*t.a5*Ct),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class Mt{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class Et{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const a=i[e];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+t),o[a.tileID.key]=a;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in a){const r=a[i];r.tileID.isChildOf(e)&&r.findMatches(t.symbolInstances,e,o);}else {const r=a[e.scaledTo(Number(i)).key];r&&r.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var Rt="void main() {fragColor=vec4(1.0);}";const zt={prelude:Dt("#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;","#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 float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}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 float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\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(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*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.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));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;uniform mat4 u_projection_matrix;"),projectionMercator:Dt("","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);}"),projectionGlobe:Dt("","#define GLOBE_RADIUS 6371008.8\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;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 spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (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;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\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) {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) {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);}"),background:Dt("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}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:Dt("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}","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;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(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);}"),circle:Dt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: 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}","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 lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+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);}"),clippingMask:Dt(Rt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:Dt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: 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}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: 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 mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/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=floor(pos_raw/8.0);\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}"),heatmapTexture:Dt("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}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:Dt("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;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;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;}"),collisionCircle:Dt("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;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;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);}"),colorRelief:Dt("#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) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,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}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.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;}}"),debug:Dt("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);}","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));}"),depth:Dt(Rt,"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}"),fill:Dt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:Dt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: 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}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:Dt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;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 mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: 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);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}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;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 mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: 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;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;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:Dt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: 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);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: 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 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);}"),fillExtrusion:Dt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","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;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\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=mod(normal.x,2.0);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.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(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;}"),fillExtrusionPattern:Dt("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 mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: 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}","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;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin 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 mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: 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=a_normal_ed.xyz;float edgedistance=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;\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=mod(normal.x,2.0);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=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\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.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(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;}"),hillshadePrepare:Dt("#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;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);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+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;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;}"),hillshade:Dt("uniform sampler2D u_image;in 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() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.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}","uniform mat4 u_matrix;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;}}"),line:Dt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat 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#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_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 mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;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 float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);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);}"),lineGradient:Dt("uniform lowp float u_device_pixel_ratio;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 mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat 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#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;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 mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;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=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;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 float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);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);}"),linePattern:Dt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform 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 mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\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 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#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_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 mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;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 float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);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;}"),lineSDF:Dt("uniform lowp float u_device_pixel_ratio;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 mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\nfloat 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#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;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 mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;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 float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);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);}"),lineGradientSDF:Dt("uniform lowp float u_device_pixel_ratio;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 mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\nfloat 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#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;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 mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*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=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;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 float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);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);}"),raster:Dt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 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);vec4 color1=texture(u_image1,v_pos1);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}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:Dt("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}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;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 highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;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;out vec2 v_tex;out float v_total_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);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=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;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);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;}"),symbolSDF:Dt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: 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;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*total_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;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 highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy/16.0;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);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=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;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);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);}"),symbolTextAndIcon:Dt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat total_opacity=v_data1[2];if (v_data1.w==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;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*total_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;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 highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);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=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;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);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=vec4(gamma_scale,size,total_opacity,is_sdf);}"),terrain:Dt("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 && 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;}}","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,get_elevation(a_pos3d.xy)-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;}"),terrainDepth:Dt("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);}","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;}"),terrainCoords:Dt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;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);}"),projectionErrorMeasurement:Dt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:Dt("#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;}","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);}"),sky:Dt("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;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;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(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function Dt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),a=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),r=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=r?r.concat(a):a,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,a)=>(n[a]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${a}\nin ${i} ${o} ${a};\n#else\nuniform ${i} ${o} u_${a};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${a}\n ${i} ${o} ${a} = u_${a};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,a)=>{const r="float"===o?"vec2":"vec4",s=a.match(/color/)?"color":r;return n[a]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${a}\nuniform lowp float u_${a}_t;\nin ${i} ${r} a_${a};\nout ${i} ${o} ${a};\n#else\nuniform ${i} ${o} u_${a};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${a}\n ${a} = a_${a};\n#else\n ${i} ${o} ${a} = u_${a};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${a}\n ${a} = unpack_mix_${s}(a_${a}, u_${a}_t);\n#else\n ${i} ${o} ${a} = u_${a};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${a}\nuniform lowp float u_${a}_t;\nin ${i} ${r} a_${a};\n#else\nuniform ${i} ${o} u_${a};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${a}\n ${i} ${o} ${a} = a_${a};\n#else\n ${i} ${o} ${a} = u_${a};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${a}\n ${i} ${o} ${a} = unpack_mix_${s}(a_${a}, u_${a}_t);\n#else\n ${i} ${o} ${a} = u_${a};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class At{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Lt=t.aS([{name:"a_pos",type:"Int16",components:2}]);const kt="#define PROJECTION_MERCATOR",Ft="mercator";class Bt{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ft}get shaderDefine(){return kt}get shaderPreludeCode(){return zt.projectionMercator}get vertexShaderPreludeCode(){return zt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aT.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,a,r){if(this._cachedMesh)return this._cachedMesh;const s=new t.aU;s.emplaceBack(0,0),s.emplaceBack(t.a5,0),s.emplaceBack(0,t.a5),s.emplaceBack(t.a5,t.a5);const n=e.createVertexBuffer(s,Lt.members),l=t.aV.simpleSegment(0,0,4,2),c=new t.aW;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new At(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Ot{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.G.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.G.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.G.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.G.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ak((this.left+e-this.right)/2,0,e),a=t.ak((this.top+i-this.bottom)/2,0,i);return new t.P(o,a)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Ot(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function jt(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Zt(e){return Math.max(0,Math.floor(e))}class Nt{constructor(e,i){var o;this.applyConstrain=(e,t)=>null!==this._constrainOverride?this._constrainOverride(e,t):this._callbacks.defaultConstrain(e,t),this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===(null==i?void 0:i.renderWorldCopies)||!!(null==i?void 0:i.renderWorldCopies),this._minZoom=(null==i?void 0:i.minZoom)||0,this._maxZoom=(null==i?void 0:i.maxZoom)||22,this._minPitch=null==(null==i?void 0:i.minPitch)?0:null==i?void 0:i.minPitch,this._maxPitch=null==(null==i?void 0:i.maxPitch)?60:null==i?void 0:i.maxPitch,this._constrainOverride=null!==(o=null==i?void 0:i.constrainOverride)&&void 0!==o?o:null,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.V(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Zt(this._zoom),this._scale=t.an(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Ot,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._constrainOverride=e.constrainOverride,this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Zt(this._zoom),this._scale=t.an(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Ot(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this.constrainInternal(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.applyConstrain(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.applyConstrain(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get constrainOverride(){return this._constrainOverride}setConstrainOverride(e){void 0===e&&(e=null),this._constrainOverride!==e&&(this._constrainOverride=e,this.constrainInternal(),this._calcMatrices());}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.W(e,-180,180)*Math.PI/180;var a,r,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),a=this._rotationMatrix,s=-this._bearingInRadians,n=(r=this._rotationMatrix)[0],l=r[1],c=r[2],h=r[3],u=Math.sin(s),d=Math.cos(s),a[0]=n*d+c*u,a[1]=l*d+h*u,a[2]=n*-u+c*d,a[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ak(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aX(this._fovInRadians)}setFov(e){e=t.ak(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.am(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.applyConstrain(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.an(i),this.constrainInternal(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this.constrainInternal(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this.constrainInternal(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this.constrainInternal(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this.constrainInternal(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new N([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this.constrainInternal()):(this._lngRange=null,this._latRange=[-t.al,t.al]);}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:a,maxX:r,maxY:s}=t.a7.fromPoints(i).extend(e);return [new t.P(o,a),new t.P(r,a),new t.P(r,s),new t.P(o,s),new t.P(o,a)]}}constrainInternal(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.applyConstrain(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ao(new Float64Array(16));t.Q(e,e,[this._width/2,-this._height/2,1]),t.O(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ao(new Float64Array(16)),t.Q(e,e,[1,-1,1]),t.O(e,e,[-1,-1,0]),t.Q(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,a){const r=void 0!==o?o:this.bearing,s=a=void 0!==a?a:this.pitch,{distanceToCenter:n,clampedElevation:l}=this._distanceToCenterFromAltElevationPitch(i,this.elevation,s),{x:c,y:h}=ve(s,r),u=t.a6.fromLngLat(e,i);let d,_,p=t.aY(1,u.y),m=0;do{if(m+=1,m>10)break;_=n/p,d=new t.a6(u.x+c*_,u.y+h*_),p=1/d.meterInMercatorCoordinateUnits();}while(Math.abs(n-_*p)>1e-12);return {center:d.toLngLat(),elevation:l,zoom:t.aq(this.height/2/Math.tan(this.fovInRadians/2)/_/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=1/this.worldSize,o=t.ap(1,this.center.lat)*this.worldSize,a=t.a6.fromLngLat(this.center,this.elevation),r=a.x/i,s=a.y/i,n=a.z/i,l=this.pitch,c=this.bearing,{x:h,y:u,z:d}=ve(l,c),_=this.cameraToCenterDistance,p=r+_*-h,m=s+_*-u,f=n+_*d,{distanceToCenter:g,clampedElevation:v}=this._distanceToCenterFromAltElevationPitch(f/o,e,l),x=g*o,b=new t.a6((p+h*x)*i,(m+u*x)*i,0).toLngLat(),y=t.ap(1,b.lat),w=t.aq(this.height/2/Math.tan(this.fovInRadians/2)/g/y/this.tileSize);this._elevation=v,this._center=b,this.setZoom(w);}_distanceToCenterFromAltElevationPitch(e,i,o){const a=-Math.cos(t.am(o)),r=e-i;let s,n=i;return a*r>=0||Math.abs(a)<.1?(s=1e4,n=e+s*a):s=-r/a,{distanceToCenter:s,clampedElevation:n}}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.ap(1,this.center.lat)*this.worldSize;return ge(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Gt{distanceToTile2d(e,t,i,o){const a=o.distanceX([e,t]),r=o.distanceY([e,t]);return Math.hypot(a,r)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,a){var r,s;let n=0,l=0;if(null==a?void 0:a.terrain){const c=new t.a2(e.z,i,e.z,e.x,e.y),h=a.terrain.getMinMaxElevation(c);n=null!==(r=h.minElevation)&&void 0!==r?r:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<a}allowWorldCopies(){return !0}prepareNextFrame(){}}class Vt{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,a,r){const s=r?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,a){const r=t.aE([],e,i),s=1/r[3]/o*a;return t.b4(r,r,[s,s,1/r[3],s])}(o,e,i,n)));a&&function(e,i,o,a){const r=a?4:0,s=a?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.b0([],e[i+s],e[i+r]),a=t.b5(o);t.aZ(o,o,1/a),l.push(a),c.push(o);}for(let i=0;i<4;i++){const a=t.b6(e[i+r],c[i],o);n=null!==a&&a>=0?Math.max(n,a):Math.max(n,l[i]);}const h=function(e,i){const o=t.b0([],e[i[0]],e[i[1]]),a=t.b0([],e[i[2]],e[i[1]]),r=[0,0,0,0];return t.b1(r,t.b2([],o,a)),r[3]=-t.b3(r,e[i[0]]),r}(e,i),u=function(e,i){const o=t.b7(e),a=t.b8([],e,1/o),r=t.b0([],i,t.aZ([],a,t.b3(i,a))),s=t.b7(r);if(s>0){const e=Math.sqrt(1-a[3]*a[3]),o=t.aZ([],a,-a[3]),n=t.a_([],o,t.aZ([],r,e/s));return t.b9(i,n)}return null}(o,h);if(null!==u){const e=u/t.b3(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+r][0]+c[t][0]*i,e[t+r][1]+c[t][1]*i,e[t+r][2]+c[t][2]*i,1];}}(l,s[0],a,r);const c=s.map((e=>{const i=t.b0([],l[e[0]],l[e[1]]),o=t.b0([],l[e[2]],l[e[1]]),a=t.b1([],t.b2([],i,o)),r=-t.b3(a,l[e[1]]);return a.concat(r)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new Vt(l,c,new Ut(h,u))}}class Wt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}setConstrainOverride(e){this._helper.setConstrainOverride(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this.defaultConstrain=(e,i)=>{i=t.ak(+i,this.minZoom,this.maxZoom);const o={center:new t.V(e.lng,e.lat),zoom:i};let a=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===a){const e=180-1e-10;a=[-e,e];}const r=this.tileSize*t.an(o.zoom);let s=0,n=r,l=0,c=r,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.X(e[1])*r,n=t.X(e[0])*r,n-s<_&&(h=_/(n-s));}a&&(l=t.W(t.Y(a[0])*r,0,r),c=t.W(t.Y(a[1])*r,0,r),cn&&(g=n-e);}if(a){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.W(p,e-r/2,e+r/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=pe(r,e).wrap();}return o},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new Nt({calcMatrices:()=>{this._calcMatrices();},defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new Gt;}clone(){const e=new Wt;return e.apply(this,!1),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.ba(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,a.x,r.x,s.x)),l=Math.floor(Math.max(o.x,a.x,r.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.ba(o,e));}return i}getCameraFrustum(){return Vt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.ap(this.elevation,this.center.lat),a=this.screenPointToMercatorCoordinateAtZ(i,o),r=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a6.fromLngLat(e),n=new t.a6(s.x-(a.x-r.x),s.y-(a.y-r.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a6.fromLngLat(e),i.getElevationForLngLat(e,this),this._pixelMatrix3D):this.coordinatePoint(t.a6.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,a=[e.x,e.y,0,1],r=[e.x,e.y,1,1];t.aE(a,a,this._pixelMatrixInverse),t.aE(r,r,this._pixelMatrixInverse);const s=a[3],n=r[3],l=a[1]/s,c=r[1]/n,h=a[2]/s,u=r[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a6(t.G.number(a[0]/s,r[0]/n,d)/this.worldSize,t.G.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const a=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aE(a,a,o),new t.P(a[0]/a[3],a[1]/a[3])}getBounds(){const e=Math.max(0,this._helper._height/2-me(this));return (new N).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-me(this)}calculatePosMatrix(e,i=!1,o){var a;const r=null!==(a=e.key)&&void 0!==a?a:t.bb(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(r)){const e=s.get(r);return o?e.f32:e.f64}const n=fe(e,this.worldSize);t.S(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(r,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const a=fe(e,this.worldSize);return t.S(a,this._fogMatrix,a),o.set(i,new Float32Array(a)),o.get(i)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const a=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),r=e-a*this._helper._pixelPerMeter/Math.cos(i),s=a<0?r:e,n=Math.PI/2+this.pitchInRadians,l=t.am(this.fov)*(Math.abs(Math.cos(t.am(this.roll)))*this.height+Math.abs(Math.sin(t.am(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ak(Math.PI-n-l,.01,Math.PI-.01)),h=me(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.am(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ak(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=_e(this.worldSize,this.center),o=i.x,a=i.y;this._helper._pixelPerMeter=t.ap(1,this.center.lat)*this.worldSize;const r=t.am(Math.min(this.pitch,de)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(r));let n;this._calculateNearFarZIfNeeded(s,r,e),n=new Float64Array(16),t.bc(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.ay(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.bd(n),t.Q(n,n,[1,-1,1]),t.O(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.be(n,n,-this.rollInRadians),t.bf(n,n,this.pitchInRadians),t.be(n,n,-this.bearingInRadians),t.O(n,n,[-o,-a,0]),this._mercatorMatrix=t.Q([],n,[this.worldSize,this.worldSize,this.worldSize]),t.Q(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.S(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.O(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.ay([],n);const l=[0,0,-1,1];t.aE(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.bc(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.Q(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.O(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.be(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.bf(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.be(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.O(this._fogMatrix,this._fogMatrix,[-o,-a,0]),t.Q(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.O(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.S(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=a-Math.round(a)+u*h+d*c,m=new Float64Array(n);if(t.O(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.ay(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aE(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.ap(1,this.center.lat)*this.worldSize;return ge(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a6.fromLngLat(e),a=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aE(a,a,this._viewProjMatrix),a[2]/a[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:a}=e,r=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&a?i.terrainRttPosMatrix32f:s||t.bg(),{mainMatrix:n,tileMercatorCoords:r,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.a$(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,a){const r=this.calculatePosMatrix(o);let s;a?(s=[e,i,a(e,i),1],t.aE(s,s,r)):(s=[e,i,0,1],ot(s,s,r));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a6.fromLngLat(e,i),a=o.meterInMercatorCoordinateUnits(),r=t.bh();return t.O(r,r,[o.x,o.y,o.z]),t.be(r,r,Math.PI),t.bf(r,r,Math.PI/2),t.Q(r,r,[-a,a,a]),r}getProjectionDataForCustomLayer(e=!0){const i=new t.a2(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),a=fe(i,this.worldSize);t.S(a,this._viewProjMatrix,a),o.tileMercatorCoords=[0,0,1,1];const r=[t.a5,t.a5,this.worldSize/this._helper.pixelsPerMeter],s=t.bi();return t.Q(s,a,r),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function qt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function $t(e){if(e.useSlerp)if(e.k<1){const i=t.bj(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bj(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),a=new Float64Array(4);t.bk(a,i,o,e.k);const r=t.bl(a);e.tr.setRoll(r.roll),e.tr.setPitch(r.pitch),e.tr.setBearing(r.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.G.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.G.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.G.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Ht(e,i,o,a,r){const s=r.padding,n=_e(r.worldSize,o.getNorthWest()),l=_e(r.worldSize,o.getNorthEast()),c=_e(r.worldSize,o.getSouthEast()),h=_e(r.worldSize,o.getSouthWest()),u=t.am(-a),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),x=(r.width-(s.left+s.right+i.left+i.right))/v.x,b=(r.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(b<0||x<0)return void qt();const y=Math.min(t.aq(r.scale*Math.min(x,b)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.am(a)),P=w.add(T).mult(r.scale/t.an(y));return {center:pe(r.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:a}}class Xt{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(me(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,a){return Ht(e,t,i,o,a)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.V.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,a=e.padding,r={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.applyConstrain(t.V.convert(i.center||d),null!=h?h:o);jt(e,_);const m=_e(e.worldSize,d),f=_e(e.worldSize,_).sub(m),g=t.an(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.G.number(o,p,n)),t.bm(r,s)||$t({startEulerAngles:r,endEulerAngles:s,tr:e,k:n,useSlerp:r.roll!=s.roll}),l&&(e.interpolatePadding(a,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.an(e.zoom-o),a=p>o?Math.min(2,g):Math.max(.5,g),r=Math.pow(a,1-n),s=pe(e.worldSize,m.add(f.mult(n*r)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,a=e.zoom,r=e.applyConstrain(t.V.convert(i.center||i.locationAtOffset),o?+i.zoom:a),s=r.center,n=r.zoom;jt(e,s);const l=_e(e.worldSize,i.locationAtOffset),c=_e(e.worldSize,s).sub(l),h=c.mag(),u=t.an(n-a);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,a,n),r=e.applyConstrain(s,o).zoom;d=t.an(r-a);}return {easeFunc:(i,o,r,h)=>{e.setZoom(1===i?n:a+t.aq(o));const u=1===i?s:pe(e.worldSize,l.add(c.mult(r)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class Kt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}Kt.Replace=[1,0],Kt.disabled=new Kt(Kt.Replace,t.bn.transparent,[!1,!1,!1,!1]),Kt.unblended=new Kt(Kt.Replace,t.bn.transparent,[!0,!0,!0,!0]),Kt.alphaBlended=new Kt([1,771],t.bn.transparent,[!0,!0,!0,!0]);const Yt=2305;class Qt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Qt.disabled=new Qt(!1,1029,Yt),Qt.backCCW=new Qt(!0,1029,Yt),Qt.frontCCW=new Qt(!0,1028,Yt);class Jt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Jt.ReadOnly=!1,Jt.ReadWrite=!0,Jt.disabled=new Jt(519,Jt.ReadOnly,[0,1]);const ei=7680;class ti{constructor(e,t,i,o,a,r){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=a,this.pass=r;}}ti.disabled=new ti({func:519,mask:0},0,0,ei,ei,ei);const ii=new WeakMap;function oi(e){var t;if(ii.has(e))return ii.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return ii.set(e,i),i}}class ai{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const a=new t.aU;a.emplaceBack(-1,-1),a.emplaceBack(2,-1),a.emplaceBack(-1,2);const r=new t.aW;r.emplaceBack(0,1,2),this._fullscreenTriangle=new At(i.createVertexBuffer(a,Lt.members),i.createIndexBuffer(r),t.aV.simpleSegment(0,0,a.length,r.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),oi(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,a=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bn.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,a.TRIANGLES,Jt.disabled,ti.disabled,Kt.unblended,Qt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&oi(a)){a.bindBuffer(a.PIXEL_PACK_BUFFER,this._pbo),a.readBuffer(a.COLOR_ATTACHMENT0),a.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const e=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);a.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&oi(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=ai._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const ri=t.a5/128;function si(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,a=o+(e.generateBorders?2:0),r=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=a+1,n=r+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=a*r*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let a=l;a<=h;a++){let r=a/o*t.a5;-1===a&&(r=-ri),a===o+1&&(r=t.a5+ri);let s=i/o*t.a5;-1===i&&(s=e.extendToNorthPole?t.bp:-ri),i===o+1&&(s=e.extendToSouthPole?t.bq:t.a5+ri),f[g++]=r,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let x=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,a){return this.currentProjection.getMeshFromTileID(e,t,i,o,a)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ui(e){const t=pi(e.worldSize,e.center.lat);return 2*Math.PI*t}function di(e,i,o,a,r){const s=1/(1<1e-6){const a=e[0]/o,r=Math.acos(e[2]/o),s=(a>0?r:-r)/Math.PI*180;return new t.V(t.W(s,-180,180),i)}return new t.V(0,i)}function fi(e){return Math.cos(e*Math.PI/180)}function gi(e,i){const o=fi(e),a=fi(i);return t.aq(a/o)}function vi(e,i){const o=e.rotate(i.bearingInRadians),a=i.zoom+gi(i.center.lat,0),r=t.bs(1/fi(i.center.lat),1/fi(Math.min(Math.abs(i.center.lat),60)),t.bv(a,7,3,0,1)),s=360/ui({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.V(i.center.lng-o.x*s*r,t.ak(i.center.lat+o.y*s,-t.al,t.al))}function xi(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function bi(e,i,o,a){const r=e.lat+o*a;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=xi(s+a*(n-s)),c=xi(s),h=xi(n);return new t.V(e.lng+i*((l-c)/(h-c)),r)}return new t.V(e.lng+i*a,r)}class yi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const a=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,r=this._cache.get(a);if(r)return r;const s=this._cachePrevious.get(a);if(s)return this._cache.set(a,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(a,n),this._hadAnyChanges=!0,n}}class wi{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new wi(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const a=t.bz([],o[0],o[1],o[2]),r=t.bA([],[i[0],0,0],a),s=t.bA([],[0,i[1],0],a),n=t.bA([],[0,0,i[2]],a),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+r[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.a_(o,o,t.aZ([],r,1&~i?-1:1)),t.a_(o,o,t.aZ([],s,1==(i>>1&1)?1:-1)),t.a_(o,o,t.aZ([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new wi(h,[[...r,-t.b3(r,h[0])],[...s,-t.b3(s,h[0])],[...n,-t.b3(n,h[0])],[-r[0],-r[1],-r[2],-t.b3(r,h[7])],[-s[0],-s[1],-s[2],-t.b3(s,h[7])],[-n[0],-n[1],-n[2],-t.b3(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,a=e.planes.length,r=e.points.length;for(let o=0;o=0&&r++;}if(0===r)return 0;r=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function Ti(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function Pi(e,t,i,o,a){const r=e-i;let s;return s=r<0?Math.min(-r,1+r-a):r>a?Math.min(Math.max(r-a,0),1-r):0,Math.max(s,Ti(t,o,a))}class Ci{constructor(){this._boundingVolumeCache=new yi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const a=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,a){var r,s;let n=0,l=0;if(null==a?void 0:a.terrain){const c=new t.a2(e.z,i,e.z,e.x,e.y),h=a.terrain.getMinMaxElevation(c);n=null!==(r=h.minElevation)&&void 0!==r?r:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bC,l/=t.bC,n+=1,l+=1,e.z<=0)return wi.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return wi.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[di(0,0,e.x,e.y,e.z),di(t.a5,0,e.x,e.y,e.z),di(t.a5,t.a5,e.x,e.y,e.z),di(0,t.a5,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aZ([],e,l));if(l!==n)for(const e of i)o.push(t.aZ([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{const o=t.ak(e.lat,-t.al,t.al),a=t.ak(+i,this.minZoom+gi(0,o),this.maxZoom);return {center:new t.V(e.lng,o),zoom:a}},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new Nt({calcMatrices:()=>{this._calcMatrices();},defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new Ci;}clone(){const e=new Mi;return e.apply(this,!1),e}apply(e,t,i){this._globeLatitudeErrorCorrectionRadians=i||0,this._helper.apply(e,t);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.by();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,a=Math.sin(i)*o,r=Math.cos(i)*o+1,s=1/Math.sqrt(a*a+r*r)*1;let n=-a,l=r;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bE(h,h,[0,0,0],-this.bearingInRadians),t.bF(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.bG(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.b5(h);return t.aZ(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(_i(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,a=Math.cos(o),r=[Math.sin(i)*a,Math.sin(o),Math.cos(i)*a],s=[r[2],0,-r[0]],n=[0,0,0];t.b2(n,s,r),t.b1(s,s),t.b1(n,n);const l=[0,0,0];return t.b1(l,[s[0]*e[0]+n[0]*e[1]+r[0]*e[2],s[1]*e[0]+n[1]*e[1]+r[1]*e[2],s[2]*e[0]+n[2]*e[1]+r[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const a=function(e,i,o){const a=1/(1<r&&(r=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+r,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new N(h)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=_i(this.unprojectScreenPoint(i)),a=_i(e),r=t.by();t.bJ(r);const s=t.by();t.bG(s,o,r,-this.center.lng*Math.PI/180),t.bF(s,s,r,this.center.lat*Math.PI/180);const n=a[0]*a[0]+a[2]*a[2],l=s[0]*s[0];if(n=-g&&p<=g,x=f>=-g&&f<=g;let b,y;if(v&&x){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bL(u,e)+t.bL(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bD();return t.aE(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.b3(e,i),a=t.by(),r=t.by();t.aZ(r,i,o),t.b0(a,e,r);const s=1-t.b3(a,a);if(s<0)return null;const n=t.b3(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),a=this.rayPlanetIntersection(i,o);if(a){const e=t.by();t.a_(e,i,[o[0]*a.tMin,o[1]*a.tMin,o[2]*a.tMin]);const r=t.by();return t.b1(r,e),mi(r)}const r=this._cachedClippingPlane,s=r[0]*o[0]+r[1]*o[1]+r[2]*o[2],n=-t.b9(r,i)/s,l=t.by();if(n>0)t.a_(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.by();t.a_(e,i,[2*o[0],2*o[1],2*o[2]]);const a=t.b9(this._cachedClippingPlane,e);t.b0(l,e,[this._cachedClippingPlane[0]*a,this._cachedClippingPlane[1]*a,this._cachedClippingPlane[2]*a]);}const c=function(e){const i=t.by();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(r);return mi(function(e,i,o){const a=t.by();t.b0(a,o,e);const r=t.by();return t.bw(r,e,a,i/t.b7(a)),r}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.V.convert(e),a=1/t.bC,r=t.bh();return t.bH(r,r,o.lng/180*Math.PI),t.bf(r,r,-o.lat/180*Math.PI),t.O(r,r,[0,0,1+i/t.bC]),t.bf(r,r,.5*Math.PI),t.Q(r,r,[a,a,a]),r}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.a2(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class Ei{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}setConstrainOverride(e){this._helper.setConstrainOverride(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(e){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this.defaultConstrain=(e,t)=>this.currentTransform.defaultConstrain(e,t),this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new Nt({calcMatrices:()=>{this._calcMatrices();},defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._globeness=1,this._mercatorTransform=new Wt,this._verticalPerspectiveTransform=new Mi;}clone(){const e=new Ei;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this,!1),e}apply(e,t){this._helper.apply(e,t),this._mercatorTransform.apply(this,!1),this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bs(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bs(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const a=this._mercatorTransform.getPitchedTextCorrection(e,i,o),r=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bs(a,r,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform,!1);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform,!1);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class Si{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=vi(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,a=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const r=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-r;if(0===s)return;const n=t.bI(i.center.lng,a.lng),l=n/(Math.abs(n/180)+1),c=t.bI(i.center.lat,a.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.b3(u,h),_=t.by();t.a_(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.b5(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=pi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bv(f,.9,.5,1,.25),v=(1-t.an(-s))*Math.min(m,g),x=i.center.lat,b=i.zoom,y=new t.V(i.center.lng+l*v,t.ak(i.center.lat+c*v,-t.al,t.al));i.setLocationAtPoint(a,o);const w=i.center,T=t.bv(Math.abs(n),45,85,0,1),P=t.bv(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bI(w.lng,y.lng),M=t.bI(w.lat,y.lat);i.setCenter(new t.V(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(b+gi(x,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,a=t.zoom;t.setCenter(vi(e.panDelta,t).wrap()),t.setZoom(a+gi(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,a,r){const s=Ht(e,i,o,a,r),n=i.left/r.width*2-1,l=(r.width-i.right)/r.width*2-1,c=i.top/r.height*-2+1,h=(r.height-i.bottom)/r.height*-2+1,u=t.bI(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bI(d,_),g=p+.5*t.bI(p,m),v=r.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const x=v.modelViewProjectionMatrix,b=[_i(o.getNorthWest()),_i(o.getNorthEast()),_i(o.getSouthWest()),_i(o.getSouthEast()),_i(new t.V(_,g)),_i(new t.V(d,g)),_i(new t.V(f,p)),_i(new t.V(f,m))],y=_i(s.center);let w=Number.POSITIVE_INFINITY;for(const e of b)n<0&&(w=Si.getLesserNonNegativeNonNull(w,Si.solveVectorScale(e,y,x,"x",n))),l>0&&(w=Si.getLesserNonNegativeNonNull(w,Si.solveVectorScale(e,y,x,"x",l))),c>0&&(w=Si.getLesserNonNegativeNonNull(w,Si.solveVectorScale(e,y,x,"y",c))),h<0&&(w=Si.getLesserNonNegativeNonNull(w,Si.solveVectorScale(e,y,x,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=Math.min(v.zoom+t.aq(w),e.maxZoom),s;qt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,a=e.applyConstrain(i.center?t.V.convert(i.center):e.center,e.zoom).center;e.setCenter(a.wrap());const r=void 0!==i.zoom?+i.zoom:e.zoom+gi(o,a.lat);e.zoom!==r&&e.setZoom(r);}handleEaseTo(e,i){const o=e.zoom,a=e.center,r=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.V.convert(i.center):a,d=e.applyConstrain(u,o).center;jt(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+gi(a.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ak(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ak(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+gi(a.lat,m.lat),g=o+gi(a.lat,0),v=f+gi(m.lat,0),x=t.bI(a.lng,m.lng),b=t.bI(a.lat,m.lat),y=t.an(v-g);return h=f!==o,{easeFunc:o=>{if(t.bm(s,n)||$t({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(r,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),r=bi(a,x,b,o*i);e.setCenter(r.wrap());}if(h){const i=t.G.number(g,v,o)+gi(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,a=e.center,r=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.applyConstrain(t.V.convert(i.center||i.locationAtOffset),r).center,c=o?+i.zoom:e.zoom+gi(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ak(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ak(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;jt(e,d);const _=function(e,i,o){const a=_i(i),r=_i(o),s=t.b3(a,r),n=Math.acos(s),l=ui(e);return n/(2*Math.PI)*l}(e,a,d),p=r+gi(a.lat,0),m=c+gi(d.lat,0),f=t.an(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+gi(d.lat,0),a=Math.min(o,p,m)+gi(0,d.lat),r=e.applyConstrain(d,a).zoom+gi(d.lat,0);g=t.an(r-p);}const v=t.bI(a.lng,d.lng),x=t.bI(a.lat,d.lat);return {easeFunc:(o,r,l,h)=>{const u=bi(a,v,x,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.aq(r);e.setZoom(1===o?c:m+gi(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,a){const r="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*r[0]+t[1]*r[1]+t[2]*r[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+a*l===n+a*h||s[3]*(n-c)+r[3]*(h-l)+n*h==c*l?null:(c+r[3]-a*h-a*s[3])/(c-n-a*h+a*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.B(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),Di=t.bM();class Ai extends t.E{constructor(e,i={}){var o,a;super(),this._rtlPluginLoaded=()=>{for(const e in this.tileManagers){const t=this.tileManagers[e].getSource().type;"vector"!==t&&"geojson"!==t||this.tileManagers[e].reload();}},this.map=e,this.dispatcher=new L(A(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.dispatcher.registerMessageHandler("GDA",((e,t)=>this.getDashes(e,t))),this.imageManager=new f,this.imageManager.setEventedParent(this);const r=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(a=document.documentElement)||void 0===a?void 0:a.lang)||void 0;this.glyphManager=new y(e._requestManager,i.localIdeographFontFamily,r),this.lineAtlas=new M(256,512),this.crossTileSymbolIndex=new St,this._setInitialValues(),this._resetUpdates(),this.dispatcher.broadcast("SR",t.bN()),ne().on(ae,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.tileManagers[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}_setInitialValues(){var e;this._spritesImagesIds={},this._layers={},this._order=[],this.tileManagers={},this.zoomHistory=new t.bO,this._availableImages=[],this._globalState={},this._serializedLayers={},this.stylesheet=null,this.light=null,this.sky=null,this.projection&&(this.projection.destroy(),delete this.projection),this._loaded=!1,this._changed=!1,this._updatedLayers={},this._updatedSources={},this._changedImages={},this._glyphsDidChange=!1,this._updatedPaintProps={},this._layerOrderChanged=!1,this.crossTileSymbolIndex=new((null===(e=this.crossTileSymbolIndex)||void 0===e?void 0:e.constructor)||Object),this.pauseablePlacement=void 0,this.placement=void 0,this.z=0;}setGlobalStateProperty(e,i){var o,a,r;this._checkLoaded();const s=null===i?null!==(r=null===(a=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===a?void 0:a.default)&&void 0!==r?r:null:i;if(t.bP(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bP(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],a=i.getLayoutAffectingGlobalStateRefs(),r=i.getPaintAffectingGlobalStateRefs(),s=i.getVisibilityAffectingGlobalStateRefs();if(a.has(o)&&t.add(i.source),r.has(o))for(const{name:e,value:t}of r.get(o))this._updatePaintProperty(i,e,t);(null==s?void 0:s.has(o))&&(i.recalculateVisibility(),this._updateLayer(i));}}this.dispatcher.broadcast("UGS",i);for(const e in this.tileManagers)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e){return t._(this,arguments,void 0,(function*(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate,this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;try{const r=yield this.map._requestManager.transformRequest(e,"Style");t.bQ(a.signal);const s=yield t.j(r,a);this._loadStyleRequest===a&&(this._loadStyleRequest=null),this._load(s.data,i,o);}catch(e){this._loadStyleRequest===a&&(this._loadStyleRequest=null),e&&!a.signal.aborted&&this.fire(new t.k(e));}}))}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,n.frameAsync(this._frameRequest,this.map._ownerWindow).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(Di,{validate:!1});}_load(e,i,o){var a,r;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!zi(this,t.C(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new P(this.stylesheet.light),this._setProjectionInternal((null===(a=this.stylesheet.projection)||void 0===a?void 0:a.type)||"mercator"),this.sky=new I(this.stylesheet.sky),this.map.setTerrain(null!==(r=this.stylesheet.terrain)&&void 0!==r?r:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e,i,o;const a=t.bR(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",a),this._order=a.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of a){const a=t.bS(e,this._globalState);if(a.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=a,t.bT(a)&&this.tileManagers[a.source]){const t=null!==(o=null===(i=e.paint)||void 0===i?void 0:i["raster-fade-duration"])&&void 0!==o?o:a.paint.get("raster-fade-duration");this.tileManagers[a.source].setRasterFadeDuration(t);}}}_loadSprite(e,i=!1,o=void 0){this.imageManager.setLoaded(!1);const a=new AbortController;let r;this._spriteRequest=a,function(e,i,o,a){return t._(this,void 0,void 0,(function*(){const r=_(e),s=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of r){const r=yield i.transformRequest(p(o,s,".json"),"SpriteJSON");l[e]=t.j(r,a);const n=yield i.transformRequest(p(o,s,".png"),"SpriteImage");c[e]=u.getImage(n,a);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const a=n.getImageCanvasContext((yield i[o]).data),r=(yield e[o]).data;for(const e in r){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=r[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:a}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const a="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(a),a in this.imageManager.images?this.imageManager.updateImage(a,e[t][o],!1):this.imageManager.addImage(a,e[t][o]),i&&(this._changedImages[a]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,a.signal.aborted||this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.tileManagers[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const a=i.getSource();("geojson"===a.type||a.vectorLayerIds&&-1===a.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${a.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.tileManagers)if(!this.tileManagers[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bU(o):o);const a=[];for(const r of e)if(o[r]){const e=i?t.bU(o[r]):o[r];a.push(e);}return a}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.tileManagers)if(this.tileManagers[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.tileManagers){const t=this.tileManagers[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.tileManagers[i.source].used=!0);}for(const e in o){const i=this.tileManagers[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.tileManagers)this.tileManagers[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.tileManagers)this.tileManagers[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const a=this.serialize();if(e=i.transformStyle?i.transformStyle(a,e):e,(null===(o=i.validate)||void 0===o||o)&&zi(this,t.C(e)))return !1;(e=t.bU(e)).layers=t.bR(e.layers);const r=t.bV(a,e),s=this._getOperationsToPerform(r);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,this.fire(new t.l("style.load",{style:this})),!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.tileManagers[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.C.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const a=this.tileManagers[e]=new Ae(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(()=>({isSourceLoaded:a.loaded(),source:a.serialize(),sourceId:e}))),a.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.tileManagers[e])throw new Error(`There is no source with this ID=${e}`);for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.tileManagers[e];delete this.tileManagers[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.tileManagers[e])throw new Error(`There is no source with this ID=${e}`);const i=this.tileManagers[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.tileManagers[e]&&this.tileManagers[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const a=e.id;if(this.getLayer(a))return void this.fire(new t.k(new Error(`Layer "${a}" already exists on this map.`)));let r;if("custom"===e.type){if(zi(this,t.bW(e)))return;r=t.bS(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(a,e.source),e=t.bU(e),e=t.e(e,{source:a})),this._validate(t.C.layer,`layers.${a}`,e,{arrayIndex:-1},o))return;r=t.bS(e,this._globalState),this._validateLayer(r),r.setEventedParent(this,{layer:{id:a}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${a}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,a),this._layerOrderChanged=!0,this._layers[a]=r,this._removedLayers[a]&&r.source&&"custom"!==r.type){const e=this._removedLayers[a];delete this._removedLayers[a],e.type!==r.type?this._updatedSources[r.source]="clear":(this._updatedSources[r.source]="reload",this.tileManagers[r.source].pause());}this._updateLayer(r),r.onAdd&&r.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const a=i?this._order.indexOf(i):this._order.length;i&&-1===a?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(a,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const a=this.getLayer(e);a?a.minzoom===i&&a.maxzoom===o||(null!=i&&(a.minzoom=i),null!=o&&(a.maxzoom=o),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const a=this.getLayer(e);if(a){if(!t.bP(a.filter,i))return null==i?(a.setFilter(void 0),void this._updateLayer(a)):void(this._validate(t.C.filter,`layers.${a.id}.filter`,i,null,o)||(a.setFilter(t.bU(i)),this._updateLayer(a)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bU(this.getLayer(e).filter)}setLayoutProperty(e,i,o,a={}){this._checkLoaded();const r=this.getLayer(e);r?t.bP(r.getLayoutProperty(i),o)||(r.setLayoutProperty(i,o,a),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,a={}){this._checkLoaded();const r=this.getLayer(e);r?t.bP(r.getPaintProperty(i),o)||this._updatePaintProperty(r,i,o,a):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,i,o,a={}){e.setPaintProperty(i,o,a)&&this._updateLayer(e),t.bT(e)&&"raster-fade-duration"===i&&this.tileManagers[e.source].setRasterFadeDuration(o),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,a=e.sourceLayer,r=this.tileManagers[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=r.getSource().type;"geojson"===s&&a?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||a?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.setFeatureState(a,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,a=this.tileManagers[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const r=a.getSource().type,s="vector"===r?e.sourceLayer:void 0;"vector"!==r||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):a.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,a=this.tileManagers[i];if(void 0!==a)return "vector"!==a.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bX(this.tileManagers,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,a=this.stylesheet;return t.bY({version:a.version,name:a.name,metadata:a.metadata,light:a.light,sky:a.sky,center:a.center,zoom:a.zoom,bearing:a.bearing,pitch:a.pitch,sprite:a.sprite,glyphs:a.glyphs,transition:a.transition,projection:a.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.tileManagers[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.tileManagers[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let a=this._order.length-1;a>=0;a--){const r=this._order[a];if(t(r)){i[r]=a;for(const t of e){const e=t[r];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const a=[];for(let r=this._order.length-1;r>=0;r--){const s=this._order[r];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&r.push(function(e,t,i,o,a,r,s){const n={},l=r.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(O);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:a.filter,globalState:a.globalState},a.layers,a.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],a=o[e];a.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of a)t.push(e);}}return function(e,t,i){for(const o in e)for(const a of e[o])j(a,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.tileManagers,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(r)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.C.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.tileManagers[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],a={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,n[i.source],e.center.lng);r=r||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((a=a||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(c(),e.zoom))&&(this.pauseablePlacement=new Pt(e,this.map.terrain,this._order,a,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,n),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(c()),s=!0),r&&this.pauseablePlacement.placement.setStale()),s||r)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,n[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(c())}_releaseSymbolFadeTiles(){for(const e in this.tileManagers)this.tileManagers[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.tileManagers[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.tileManagers[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.C.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}getDashes(e,i){return t._(this,void 0,void 0,(function*(){const e={};for(const[t,o]of Object.entries(i.dashes))e[t]=this.lineAtlas.getDash(o.dasharray,o.round);return e}))}addSprite(e,i,o={},a){this._checkLoaded();const r=[{id:e,url:i}],s=[..._(this.stylesheet.sprite),...r];this._validate(t.C.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(r,!0,a));}removeSprite(e){this._checkLoaded();const i=_(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return _(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.C.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}destroy(){this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._loadStyleRequest&&(this._loadStyleRequest.abort(),this._loadStyleRequest=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null);for(const e in this.tileManagers){const t=this.tileManagers[e];t.setEventedParent(null),t.onRemove(this.map);}this.tileManagers={},this.imageManager&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this._availableImages=[],this._spritesImagesIds={}),this.glyphManager&&this.glyphManager.destroy();for(const e in this._layers){const t=this._layers[e];t.setEventedParent(null),t.onRemove&&t.onRemove(this.map);}this._setInitialValues(),this.setEventedParent(null),this.dispatcher.unregisterMessageHandler("GG"),this.dispatcher.unregisterMessageHandler("GI"),this.dispatcher.unregisterMessageHandler("GDA"),this.dispatcher.remove(!0),this._listeners={},this._oneTimeListeners={};}}var Li=t.aS([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class ki{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,a,r,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bn.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:r?0:o?o.calculateFogBlendOpacity(a):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bn.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:r?1:0}),Bi={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Oi(e){const t=[];for(let i=0;i({u_depth:new t.bZ(e,i.u_depth),u_terrain:new t.bZ(e,i.u_terrain),u_terrain_dim:new t.bo(e,i.u_terrain_dim),u_terrain_matrix:new t.b$(e,i.u_terrain_matrix),u_terrain_unpack:new t.c0(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bo(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.b$(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.c0(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.c0(e,i.u_projection_clipping_plane),u_projection_transition:new t.bo(e,i.u_projection_transition),u_projection_fallback_matrix:new t.b$(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,a,r,s,n,l,c,h,u,d,_,p,m,f,g,v){const x=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(a),e.setCullFace(r),n){e.activeTexture.set(x.TEXTURE2),x.bindTexture(x.TEXTURE_2D,n.depthTexture),e.activeTexture.set(x.TEXTURE3),x.bindTexture(x.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Bi[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let b=0;switch(t){case x.LINES:b=2;break;case x.TRIANGLES:b=3;break;case x.LINE_STRIP:b=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new ki)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),x.drawElements(t,i.primitiveLength*b,x.UNSIGNED_SHORT,i.primitiveOffset*b*2);}}}function Zi(e,i,o){const a=1/t.aK(o,1,i.transform.tileZoom),r=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/r,n=s*(o.tileID.canonical.x+o.tileID.wrap*r),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[a,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ni=(e,i,o,a)=>{const r=e.style.light,s=r.properties.get("position"),n=[s.x,s.y,s.z],l=t.c3();"viewport"===r.properties.get("anchor")&&t.c4(l,e.transform.bearingInRadians),t.c5(n,n,l);const c=e.transform.transformLightDirection(n),h=r.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:r.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:a}},Ui=(e,i,o,a,r,s,n)=>t.e(Ni(e,i,o,a),Zi(s,e,n),{u_height_factor:-Math.pow(2,r.overscaledZ)/n.tileSize/8}),Gi=(e,i,o,a)=>t.e(Zi(i,e,o),{u_fill_translate:a}),Vi=(e,t)=>({u_world:e,u_fill_translate:t}),Wi=(e,i,o,a,r)=>t.e(Gi(e,i,o,r),{u_world:a}),qi=(e,i,o,a,r)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aK(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.a5*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*r;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:a}},$i=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Hi=e=>({u_viewport_size:[e.width,e.height]}),Xi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),Ki=(e,i,o,a)=>{const r=t.aK(e,1,i)/(t.a5*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*a;return {u_extrude_scale:t.aK(e,1,i),u_intensity:o,u_globe_extrude_scale:r}},Yi=(e,i,o,a)=>{const r=t.N();t.c6(r,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:r,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:a,u_opacity:i.paint.get("heatmap-opacity")}},Qi=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let a;switch(i.paint.get("hillshade-method")){case "basic":a=4;break;case "combined":a=1;break;case "igor":a=2;break;case "multidirectional":a=3;break;default:a=0;}const r=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,a=t.N();return t.c6(a,0,t.a5,-t.a5,0,0,1),t.O(a,a,[0,-t.a5,0]),{u_matrix:a,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function eo(e,i){const o=Math.pow(2,i.canonical.z),a=i.canonical.y;return [new t.a6(0,a/o).toLngLat().lat,new t.a6(0,(a+1)/o).toLngLat().lat]}const to=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),io=(e,i,o,a)=>{const r=e.transform;return {u_translation:lo(e,i,o),u_ratio:a/t.aK(i,1,r.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/r.pixelsToGLUnits[0],1/r.pixelsToGLUnits[1]]}},oo=(e,i,o,a,r)=>t.e(io(e,i,o,a),{u_image:0,u_image_height:r}),ao=(e,i,o,a,r)=>{const s=e.transform,n=no(i,s);return {u_translation:lo(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:a/t.aK(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,r.fromScale,r.toScale],u_fade:r.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},ro=(e,i,o,a,r)=>{const s=no(i,e.transform);return t.e(io(e,i,o,a),{u_tileratio:s,u_crossfade_from:r.fromScale,u_crossfade_to:r.toScale,u_image:0,u_mix:r.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})},so=(e,i,o,a,r,s)=>{const n=no(i,e.transform);return t.e(io(e,i,o,a),{u_image:0,u_image_height:s,u_tileratio:n,u_crossfade_from:r.fromScale,u_crossfade_to:r.toScale,u_image_dash:1,u_mix:r.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})};function no(e,i){return 1/t.aK(e,1,i.tileZoom)}function lo(e,i,o){return t.aL(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const co=(e,t,i,o,a)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(r=o.paint.get("raster-contrast"),r>0?1/(1-r):1+r),u_spin_weights:ho(o.paint.get("raster-hue-rotate")),u_coords_top:[a[0].x,a[0].y,a[1].x,a[1].y],u_coords_bottom:[a[3].x,a[3].y,a[2].x,a[2].y]};var r,s;};function ho(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const uo=(e,t,i,o,a,r,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:a,u_is_variable_anchor:r,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},_o=(e,i,o,a,r,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(uo(e,i,o,a,r,s,n,l,c,h,u,d,p),{u_gamma_scale:a?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},po=(e,i,o,a,r,s,n,l,c,h,u,d,_)=>t.e(_o(e,i,o,a,r,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),mo=(e,t)=>({u_opacity:e,u_color:t}),fo=(e,i,o,a,r)=>t.e(function(e,i,o,a){const r=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,a.tileID.overscaledZ),h=a.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(a.tileID.canonical.x+a.tileID.wrap*c),d=h*a.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aK(a,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,r,i,a),{u_opacity:e}),go=(e,t)=>{},vo={fillExtrusion:(e,i)=>({u_lightpos:new t.c1(e,i.u_lightpos),u_lightpos_globe:new t.c1(e,i.u_lightpos_globe),u_lightintensity:new t.bo(e,i.u_lightintensity),u_lightcolor:new t.c1(e,i.u_lightcolor),u_vertical_gradient:new t.bo(e,i.u_vertical_gradient),u_opacity:new t.bo(e,i.u_opacity),u_fill_translate:new t.c2(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.c1(e,i.u_lightpos),u_lightpos_globe:new t.c1(e,i.u_lightpos_globe),u_lightintensity:new t.bo(e,i.u_lightintensity),u_lightcolor:new t.c1(e,i.u_lightcolor),u_vertical_gradient:new t.bo(e,i.u_vertical_gradient),u_height_factor:new t.bo(e,i.u_height_factor),u_opacity:new t.bo(e,i.u_opacity),u_fill_translate:new t.c2(e,i.u_fill_translate),u_image:new t.bZ(e,i.u_image),u_texsize:new t.c2(e,i.u_texsize),u_pixel_coord_upper:new t.c2(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.c2(e,i.u_pixel_coord_lower),u_scale:new t.c1(e,i.u_scale),u_fade:new t.bo(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.c2(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bZ(e,i.u_image),u_texsize:new t.c2(e,i.u_texsize),u_pixel_coord_upper:new t.c2(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.c2(e,i.u_pixel_coord_lower),u_scale:new t.c1(e,i.u_scale),u_fade:new t.bo(e,i.u_fade),u_fill_translate:new t.c2(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.c2(e,i.u_world),u_fill_translate:new t.c2(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.c2(e,i.u_world),u_image:new t.bZ(e,i.u_image),u_texsize:new t.c2(e,i.u_texsize),u_pixel_coord_upper:new t.c2(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.c2(e,i.u_pixel_coord_lower),u_scale:new t.c1(e,i.u_scale),u_fade:new t.bo(e,i.u_fade),u_fill_translate:new t.c2(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bo(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bZ(e,i.u_scale_with_map),u_pitch_with_map:new t.bZ(e,i.u_pitch_with_map),u_extrude_scale:new t.c2(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bo(e,i.u_globe_extrude_scale),u_translate:new t.c2(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.c2(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.c2(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.b_(e,i.u_color),u_overlay:new t.bZ(e,i.u_overlay),u_overlay_scale:new t.bo(e,i.u_overlay_scale)}),depth:go,clippingMask:go,heatmap:(e,i)=>({u_extrude_scale:new t.bo(e,i.u_extrude_scale),u_intensity:new t.bo(e,i.u_intensity),u_globe_extrude_scale:new t.bo(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.b$(e,i.u_matrix),u_world:new t.c2(e,i.u_world),u_image:new t.bZ(e,i.u_image),u_color_ramp:new t.bZ(e,i.u_color_ramp),u_opacity:new t.bo(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bZ(e,i.u_image),u_latrange:new t.c2(e,i.u_latrange),u_exaggeration:new t.bo(e,i.u_exaggeration),u_altitudes:new t.c8(e,i.u_altitudes),u_azimuths:new t.c8(e,i.u_azimuths),u_accent:new t.b_(e,i.u_accent),u_method:new t.bZ(e,i.u_method),u_shadows:new t.c7(e,i.u_shadows),u_highlights:new t.c7(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.b$(e,i.u_matrix),u_image:new t.bZ(e,i.u_image),u_dimension:new t.c2(e,i.u_dimension),u_zoom:new t.bo(e,i.u_zoom),u_unpack:new t.c0(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bZ(e,i.u_image),u_unpack:new t.c0(e,i.u_unpack),u_dimension:new t.c2(e,i.u_dimension),u_elevation_stops:new t.bZ(e,i.u_elevation_stops),u_color_stops:new t.bZ(e,i.u_color_stops),u_color_ramp_size:new t.bZ(e,i.u_color_ramp_size),u_opacity:new t.bo(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.c2(e,i.u_translation),u_ratio:new t.bo(e,i.u_ratio),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.c2(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.c2(e,i.u_translation),u_ratio:new t.bo(e,i.u_ratio),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.c2(e,i.u_units_to_pixels),u_image:new t.bZ(e,i.u_image),u_image_height:new t.bo(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.c2(e,i.u_translation),u_texsize:new t.c2(e,i.u_texsize),u_ratio:new t.bo(e,i.u_ratio),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_image:new t.bZ(e,i.u_image),u_units_to_pixels:new t.c2(e,i.u_units_to_pixels),u_scale:new t.c1(e,i.u_scale),u_fade:new t.bo(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.c2(e,i.u_translation),u_ratio:new t.bo(e,i.u_ratio),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.c2(e,i.u_units_to_pixels),u_image:new t.bZ(e,i.u_image),u_mix:new t.bo(e,i.u_mix),u_tileratio:new t.bo(e,i.u_tileratio),u_crossfade_from:new t.bo(e,i.u_crossfade_from),u_crossfade_to:new t.bo(e,i.u_crossfade_to),u_lineatlas_width:new t.bo(e,i.u_lineatlas_width),u_lineatlas_height:new t.bo(e,i.u_lineatlas_height)}),lineGradientSDF:(e,i)=>({u_translation:new t.c2(e,i.u_translation),u_ratio:new t.bo(e,i.u_ratio),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.c2(e,i.u_units_to_pixels),u_image:new t.bZ(e,i.u_image),u_image_height:new t.bo(e,i.u_image_height),u_tileratio:new t.bo(e,i.u_tileratio),u_crossfade_from:new t.bo(e,i.u_crossfade_from),u_crossfade_to:new t.bo(e,i.u_crossfade_to),u_image_dash:new t.bZ(e,i.u_image_dash),u_mix:new t.bo(e,i.u_mix),u_lineatlas_width:new t.bo(e,i.u_lineatlas_width),u_lineatlas_height:new t.bo(e,i.u_lineatlas_height)}),raster:(e,i)=>({u_tl_parent:new t.c2(e,i.u_tl_parent),u_scale_parent:new t.bo(e,i.u_scale_parent),u_buffer_scale:new t.bo(e,i.u_buffer_scale),u_fade_t:new t.bo(e,i.u_fade_t),u_opacity:new t.bo(e,i.u_opacity),u_image0:new t.bZ(e,i.u_image0),u_image1:new t.bZ(e,i.u_image1),u_brightness_low:new t.bo(e,i.u_brightness_low),u_brightness_high:new t.bo(e,i.u_brightness_high),u_saturation_factor:new t.bo(e,i.u_saturation_factor),u_contrast_factor:new t.bo(e,i.u_contrast_factor),u_spin_weights:new t.c1(e,i.u_spin_weights),u_coords_top:new t.c0(e,i.u_coords_top),u_coords_bottom:new t.c0(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bZ(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bZ(e,i.u_is_size_feature_constant),u_size_t:new t.bo(e,i.u_size_t),u_size:new t.bo(e,i.u_size),u_camera_to_center_distance:new t.bo(e,i.u_camera_to_center_distance),u_pitch:new t.bo(e,i.u_pitch),u_rotate_symbol:new t.bZ(e,i.u_rotate_symbol),u_aspect_ratio:new t.bo(e,i.u_aspect_ratio),u_fade_change:new t.bo(e,i.u_fade_change),u_label_plane_matrix:new t.b$(e,i.u_label_plane_matrix),u_coord_matrix:new t.b$(e,i.u_coord_matrix),u_is_text:new t.bZ(e,i.u_is_text),u_pitch_with_map:new t.bZ(e,i.u_pitch_with_map),u_is_along_line:new t.bZ(e,i.u_is_along_line),u_is_variable_anchor:new t.bZ(e,i.u_is_variable_anchor),u_texsize:new t.c2(e,i.u_texsize),u_texture:new t.bZ(e,i.u_texture),u_translation:new t.c2(e,i.u_translation),u_pitched_scale:new t.bo(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bZ(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bZ(e,i.u_is_size_feature_constant),u_size_t:new t.bo(e,i.u_size_t),u_size:new t.bo(e,i.u_size),u_camera_to_center_distance:new t.bo(e,i.u_camera_to_center_distance),u_pitch:new t.bo(e,i.u_pitch),u_rotate_symbol:new t.bZ(e,i.u_rotate_symbol),u_aspect_ratio:new t.bo(e,i.u_aspect_ratio),u_fade_change:new t.bo(e,i.u_fade_change),u_label_plane_matrix:new t.b$(e,i.u_label_plane_matrix),u_coord_matrix:new t.b$(e,i.u_coord_matrix),u_is_text:new t.bZ(e,i.u_is_text),u_pitch_with_map:new t.bZ(e,i.u_pitch_with_map),u_is_along_line:new t.bZ(e,i.u_is_along_line),u_is_variable_anchor:new t.bZ(e,i.u_is_variable_anchor),u_texsize:new t.c2(e,i.u_texsize),u_texture:new t.bZ(e,i.u_texture),u_gamma_scale:new t.bo(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_is_halo:new t.bZ(e,i.u_is_halo),u_translation:new t.c2(e,i.u_translation),u_pitched_scale:new t.bo(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bZ(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bZ(e,i.u_is_size_feature_constant),u_size_t:new t.bo(e,i.u_size_t),u_size:new t.bo(e,i.u_size),u_camera_to_center_distance:new t.bo(e,i.u_camera_to_center_distance),u_pitch:new t.bo(e,i.u_pitch),u_rotate_symbol:new t.bZ(e,i.u_rotate_symbol),u_aspect_ratio:new t.bo(e,i.u_aspect_ratio),u_fade_change:new t.bo(e,i.u_fade_change),u_label_plane_matrix:new t.b$(e,i.u_label_plane_matrix),u_coord_matrix:new t.b$(e,i.u_coord_matrix),u_is_text:new t.bZ(e,i.u_is_text),u_pitch_with_map:new t.bZ(e,i.u_pitch_with_map),u_is_along_line:new t.bZ(e,i.u_is_along_line),u_is_variable_anchor:new t.bZ(e,i.u_is_variable_anchor),u_texsize:new t.c2(e,i.u_texsize),u_texsize_icon:new t.c2(e,i.u_texsize_icon),u_texture:new t.bZ(e,i.u_texture),u_texture_icon:new t.bZ(e,i.u_texture_icon),u_gamma_scale:new t.bo(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bo(e,i.u_device_pixel_ratio),u_is_halo:new t.bZ(e,i.u_is_halo),u_translation:new t.c2(e,i.u_translation),u_pitched_scale:new t.bo(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bo(e,i.u_opacity),u_color:new t.b_(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bo(e,i.u_opacity),u_image:new t.bZ(e,i.u_image),u_pattern_tl_a:new t.c2(e,i.u_pattern_tl_a),u_pattern_br_a:new t.c2(e,i.u_pattern_br_a),u_pattern_tl_b:new t.c2(e,i.u_pattern_tl_b),u_pattern_br_b:new t.c2(e,i.u_pattern_br_b),u_texsize:new t.c2(e,i.u_texsize),u_mix:new t.bo(e,i.u_mix),u_pattern_size_a:new t.c2(e,i.u_pattern_size_a),u_pattern_size_b:new t.c2(e,i.u_pattern_size_b),u_scale_a:new t.bo(e,i.u_scale_a),u_scale_b:new t.bo(e,i.u_scale_b),u_pixel_coord_upper:new t.c2(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.c2(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bo(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bZ(e,i.u_texture),u_ele_delta:new t.bo(e,i.u_ele_delta),u_fog_matrix:new t.b$(e,i.u_fog_matrix),u_fog_color:new t.b_(e,i.u_fog_color),u_fog_ground_blend:new t.bo(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bo(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.b_(e,i.u_horizon_color),u_horizon_fog_blend:new t.bo(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bo(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bo(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bZ(e,i.u_texture),u_terrain_coords_id:new t.bo(e,i.u_terrain_coords_id),u_ele_delta:new t.bo(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bo(e,i.u_input),u_output_expected:new t.bo(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.c1(e,i.u_sun_pos),u_atmosphere_blend:new t.bo(e,i.u_atmosphere_blend),u_globe_position:new t.c1(e,i.u_globe_position),u_globe_radius:new t.bo(e,i.u_globe_radius),u_inv_proj_matrix:new t.b$(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.b_(e,i.u_sky_color),u_horizon_color:new t.b_(e,i.u_horizon_color),u_horizon:new t.c2(e,i.u_horizon),u_horizon_normal:new t.c2(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bo(e,i.u_sky_horizon_blend),u_sky_blend:new t.bo(e,i.u_sky_blend)})};class xo{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload();}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const bo={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class yo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const a=e.gl;this.buffer=a.createBuffer(),e.bindVertexBuffer.set(this.buffer),a.bufferData(a.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?a.DYNAMIC_DRAW:a.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload();}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Jt.disabled,ti.disabled,e.colorModeForRenderPass(),Qt.disabled,$i(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!r||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.c9;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:E,angle:S});}else it(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");Ge(c,e,r,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,N,t);}const W=r&&P||V,q=x||W?ca:v?O:e.transform.clipSpaceToPixelsMatrix,$=p&&0!==o.paint.get(r?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?po(T.kind,S,b,v,x,W,e,q,Z,N,z,k,I):_o(T.kind,S,b,v,x,W,e,q,Z,N,r,z,0,I):uo(T.kind,S,b,v,x,W,e,q,Z,N,r,z,I);const X={program:E,buffers:u,uniformValues:H,projectionData:U,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:$};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aV([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const a=i.uniformValues;i.hasHalo&&(a.u_is_halo=1,ma(i.buffers,t.segments,o,e,i.program,T,u,d,a,i.projectionData,t.terrainData)),a.u_is_halo=0;}ma(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function ma(e,t,i,o,a,r,s,n,l,c,h){const u=o.context;a.draw(u,u.gl.TRIANGLES,r,s,n,Qt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function fa(e,i,o,a,r){const s=e.context,n=s.gl,l=ti.disabled,c=new Kt([n.ONE,n.ONE],t.bn.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=a.key;let d=o.heatmapFbos.get(u);d||(d=va(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bn.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!r),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(a);p.draw(s,n.TRIANGLES,Jt.disabled,l,c,Qt.disabled,Ki(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ga(e,t,i,o,a){const r=e.context,s=r.gl,n=e.transform;r.setColorMode(e.colorModeForRenderPass());const l=xa(r,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;r.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),r.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:a,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(r,s.TRIANGLES,Jt.disabled,ti.disabled,e.colorModeForRenderPass(),Qt.disabled,Yi(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function va(e,t,i){var o,a;const r=e.gl,s=r.createTexture();r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:r.UNSIGNED_BYTE,l=null!==(a=e.RGBA16F)&&void 0!==a?a:r.RGBA;r.texImage2D(r.TEXTURE_2D,0,l,t,i,0,r.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function xa(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function ba(e,i,o,a,r,s,n,l){let c=256;if(r.stepInterpolant){const a=i.getSource().maxzoom,r=n.canonical.z===a?Math.ceil(1<e.options.anisotropicFilterPitch&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const E=e.style.map.terrain&&e.style.map.terrain.getTerrainData(w),S=p.getProjectionData({overscaledTileID:w,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),R=co(I,C,M.fadeMix,i,n),z=m.getMeshFromTileID(u,w.canonical,r,s,"raster");_.draw(u,d.TRIANGLES,o,a?a[w.overscaledZ]:ti.disabled,f,l?Qt.frontCCW:Qt.backCCW,R,E,S,i.id,z.vertexBuffer,z.indexBuffer,z.segments);}}function Da(e,i,o,a){const r={parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:{tileOpacity:1,parentTileOpacity:1,fadeMix:{opacity:1,mix:0}}};if(0===o||a)return r;if(e.fadingParentID){const a=i.getLoadedTile(e.fadingParentID);if(!a)return r;const s=Math.pow(2,a.tileID.overscaledZ-e.tileID.overscaledZ),n=[e.tileID.canonical.x*s%1,e.tileID.canonical.y*s%1],l=function(e,i,o){const a=c(),r=(a-i.timeAdded)/o,s=e.fadingDirection===ce.Incoming,n=t.ak((a-e.timeAdded)/o,0,1),l=t.ak(1-r,0,1),h=s?n:l;return {tileOpacity:h,parentTileOpacity:s?l:n,fadeMix:{opacity:1,mix:1-h}}}(e,a,o);return {parentTile:a,parentScaleBy:s,parentTopLeft:n,fadeValues:l}}if(e.selfFading){const i=function(e,i){const o=(c()-e.timeAdded)/i,a=t.ak(o,0,1);return {tileOpacity:a,fadeMix:{opacity:a,mix:0}}}(e,o);return {parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:i}}return r}const Aa=new t.bn(1,0,0,1),La=new t.bn(0,1,0,1),ka=new t.bn(0,0,1,1),Fa=new t.bn(1,0,1,1),Ba=new t.bn(0,1,1,1);function Oa(e,t,i,o){Za(e,0,t+i/2,e.transform.width,i,o);}function ja(e,t,i,o){Za(e,t-i/2,0,i,e.transform.height,o);}function Za(e,t,i,o,a,r){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,a*e.pixelRatio),s.clear({color:r}),n.disable(n.SCISSOR_TEST);}function Na(e,i,o){const a=e.context,r=a.gl,s=e.useProgram("debug"),n=Jt.disabled,l=ti.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);a.activeTexture.set(r.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,a=e.debugOverlayCanvas.getContext("2d");a.clearRect(0,0,i.width,i.height),a.shadowColor="white",a.shadowBlur=2,a.lineWidth=1.5,a.strokeStyle="white",a.textBaseline="top",a.font="bold 36px Open Sans, sans-serif",a.fillText(t,5,5),a.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(a,r.TRIANGLES,n,l,Kt.alphaBlended,Qt.disabled,Xi(t.bn.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(a,r.LINE_STRIP,n,l,c,Qt.disabled,Xi(t.bn.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Ua(e,t,i,o){const{isRenderingGlobe:a}=o,r=e.context,s=r.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");r.bindFramebuffer.set(null),r.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);r.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Fi(_,p,e.style.sky,n.pitch,a),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(r,s.TRIANGLES,c,ti.disabled,l,Qt.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ga(e,i){if(!i.mesh){const o=new t.aU;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const a=new t.aW;a.emplaceBack(0,1,2),a.emplaceBack(0,2,3),i.mesh=new At(e.createVertexBuffer(o,Lt.members),e.createIndexBuffer(a),t.aV.simpleSegment(0,0,o.length,a.length));}return i.mesh}class Va{constructor(e,i){this.context=new sa(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ao(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Ae.maxOverzooming+Ae.maxUnderzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new St;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aU;i.emplaceBack(0,0),i.emplaceBack(t.a5,0),i.emplaceBack(0,t.a5),i.emplaceBack(t.a5,t.a5),this.tileExtentBuffer=e.createVertexBuffer(i,Lt.members),this.tileExtentSegments=t.aV.simpleSegment(0,0,4,2);const o=new t.aU;o.emplaceBack(0,0),o.emplaceBack(t.a5,0),o.emplaceBack(0,t.a5),o.emplaceBack(t.a5,t.a5),this.debugBuffer=e.createVertexBuffer(o,Lt.members),this.debugSegments=t.aV.simpleSegment(0,0,4,5);const a=new t.cg;a.emplaceBack(0,0,0,0),a.emplaceBack(t.a5,0,t.a5,0),a.emplaceBack(0,t.a5,0,t.a5),a.emplaceBack(t.a5,t.a5,t.a5,t.a5),this.rasterBoundsBuffer=e.createVertexBuffer(a,Li.members),this.rasterBoundsSegments=t.aV.simpleSegment(0,0,4,2);const r=new t.aU;r.emplaceBack(0,0),r.emplaceBack(t.a5,0),r.emplaceBack(0,t.a5),r.emplaceBack(t.a5,t.a5),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(r,Lt.members),this.rasterBoundsSegmentsPosOnly=t.aV.simpleSegment(0,0,4,5);const s=new t.aU;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Lt.members),this.viewportSegments=t.aV.simpleSegment(0,0,4,2);const n=new t.ch;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aW;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new ti({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new At(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.N();t.c6(o,0,this.width,this.height,0,0,1),t.Q(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const a={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Jt.disabled,this.stencilClearMode,Kt.disabled,Qt.disabled,null,null,a,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(Kt.disabled),o.setDepthMode(Jt.disabled);const a={};for(const e of t)a[e.key]=this.nextStencilID++;this._renderTileMasks(a,t,i,!0),this._renderTileMasks(a,t,i,!1),this._tileClippingMaskIDs=a;}_renderTileMasks(e,t,i,o){const a=this.context,r=a.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(a,r.TRIANGLES,Jt.disabled,new ti({func:r.ALWAYS,mask:0},t,255,r.KEEP,r.KEEP,r.REPLACE),Kt.disabled,i?Qt.disabled:Qt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,a=this.useProgram("depth"),r=this.getDepthModeFor3D(),s=Pe(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});a.draw(e,t.TRIANGLES,r,ti.disabled,Kt.disabled,Qt.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new ti({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new ti({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,a=i[0].overscaledZ-o+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,a=i[0].overscaledZ-o+1;if(this.clearStencil(),a>1){const e={},r={};for(let i=0;i0};for(const e in s){const t=s[e];t.used&&t.prepare(this.context),n[e]=t.getVisibleCoordinates(!1),l[e]=n[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bn.black:t.bn.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,a=((e,t,i)=>{const o=Math.cos(t.rollInRadians),a=Math.sin(t.rollInRadians),r=me(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-r*a)*i,(t.height/2+r*o)*i],u_horizon_normal:[-a,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),r=new Jt(o.LEQUAL,Jt.ReadWrite,[0,1]),s=ti.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ga(i,t);l.draw(i,o.TRIANGLES,r,s,n,Qt.disabled,a,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[r[this.currentLayer]],t=s[e.source],i=n[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:a}))(c,u,[p[0],p[1],p[2]],d,_),f=Ga(a,i);s.draw(a,r.TRIANGLES,n,ti.disabled,Kt.alphaBlended,Qt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.tileManagers[i.source]]:[])),a=o.filter((e=>"vector"===e.getSource().type)),r=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||r.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(r,e,t):null;da(s,d,_,c,h,f,i,p,g,t.aL(h,e,n,l),r.toUnwrapped(),o);}}}(a,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),r),0!==o.paint.get("icon-opacity").constantOr(1)&&pa(e,i,o,a,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&pa(e,i,o,a,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(la(e,i,o,a,!0),la(e,i,o,a,!1));}(e,i,o,a,this.style.placement.variableOffsets,r):t.cl(o)?function(e,i,o,a,r){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=r,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Jt.ReadOnly),m=ti.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let r=0;re.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:a,layoutVertexBuffer:r,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;a.draw(u,d.TRIANGLES,p,m,f,Qt.backCCW,n,l,c,o.id,r,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,a,r):t.cm(o)?function(e,i,o,a,r){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=r;if(e.style.map.terrain){for(const t of a){const a=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?fa(e,a,o,t,l):"translucent"===e.renderPass&&ga(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,a){const r=e.context,s=r.gl,n=e.transform,l=ti.disabled,c=new Kt([s.ONE,s.ONE],t.bn.transparent,[!0,!0,!0,!0]);((function(e,i,o){const a=e.gl;e.activeTexture.set(a.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let r=o.heatmapFbos.get(t.cc);r?(a.bindTexture(a.TEXTURE_2D,r.colorAttachment.get()),e.bindFramebuffer.set(r.framebuffer)):(r=va(e,i.width/4,i.height/4),o.heatmapFbos.set(t.cc,r));}))(r,e,o),r.clear({color:t.bn.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const a=!!this.style.map.terrain,r=this.style.projection,s=i?zt.projectionMercator:r.shaderPreludeCode,n=i?kt:r.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ft:r.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(a?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new ji(this.context,zt[e],t,vo[e],this._showOverdrawInspector,a,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){var e,t;if(this._tileTextures){for(const e in this._tileTextures){const t=this._tileTextures[e];if(t)for(const e of t)e.destroy();}this._tileTextures={};}if(this.tileExtentBuffer&&this.tileExtentBuffer.destroy(),this.debugBuffer&&this.debugBuffer.destroy(),this.rasterBoundsBuffer&&this.rasterBoundsBuffer.destroy(),this.rasterBoundsBufferPosOnly&&this.rasterBoundsBufferPosOnly.destroy(),this.viewportBuffer&&this.viewportBuffer.destroy(),this.tileBorderIndexBuffer&&this.tileBorderIndexBuffer.destroy(),this.quadTriangleIndexBuffer&&this.quadTriangleIndexBuffer.destroy(),this.tileExtentMesh&&(null===(e=this.tileExtentMesh.vertexBuffer)||void 0===e||e.destroy()),this.tileExtentMesh&&(null===(t=this.tileExtentMesh.indexBuffer)||void 0===t||t.destroy()),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this.cache){for(const e in this.cache){const t=this.cache[e];t&&t.program&&this.context.gl.deleteProgram(t.program);}this.cache={};}this.context&&this.context.setDefault();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Wa(e,t){let i,o=!1,a=null,r=null;const s=()=>{a=null,o&&(e.apply(r,i),a=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,r=this,i=e,a||s(),a)}Va.MAX_TEXTURE_POOL_SIZE_PER_BUCKET=50;class qa{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let a=window.location.href.replace(/(#.+)?$/,o);a=a.replace("&&","&"),window.history.replaceState(window.history.state,null,a);},this._updateHash=Wa(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),a=Math.pow(10,o),r=Math.round(t.lng*a)/a,s=Math.round(t.lat*a)/a,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${r}/${s}/${i}`:`${i}/${s}/${r}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.V(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),a=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&a>=this._map.getMinPitch()&&a<=this._map.getMaxPitch()}}const $a={linearity:.3,easing:t.cu(0,0,.3,1)},Ha=t.e({deceleration:2500,maxSpeed:1400},$a),Xa=t.e({deceleration:20,maxSpeed:1400},$a),Ka=t.e({deceleration:1e3,maxSpeed:360},$a),Ya=t.e({deceleration:1e3,maxSpeed:90},$a),Qa=t.e({deceleration:1e3,maxSpeed:360},$a);class Ja{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:c(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=c();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,a={};if(i.pan.mag()){const r=tr(i.pan.mag(),o,t.e({},Ha,e||{})),s=i.pan.mult(r.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);a.center=n.easingCenter,a.offset=n.easingOffset,er(a,r);}if(i.zoom){const e=tr(i.zoom,o,Xa),r=t.cv(this._map.transform.zoom+e.amount,this._map.getZoomSnap(),e.amount);a.zoom=r,er(a,e);}if(i.bearing){const e=tr(i.bearing,o,Ka);a.bearing=this._map.transform.bearing+t.ak(e.amount,-179,179),er(a,e);}if(i.pitch){const e=tr(i.pitch,o,Ya);a.pitch=this._map.transform.pitch+e.amount,er(a,e);}if(i.roll){const e=tr(i.roll,o,Qa);a.roll=this._map.transform.roll+t.ak(e.amount,-179,179),er(a,e);}if(a.zoom||a.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;a.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(a,{noMoveStart:!0})}}function er(e,t){(!e.duration||e.durationi.unproject(e))),n=r.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:r,point:n,lngLats:s,lngLat:i.unproject(n),originalEvent:o}),this._defaultPrevented=!1;}}class ar extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class rr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new ar(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new ir(e.type,this._map,e))}mouseup(e){this._map.fire(new ir(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new ir(e.type,this._map,e));}dblclick(e){return this._firePreventable(new ir(e.type,this._map,e))}mouseover(e){this._map.fire(new ir(e.type,this._map,e));}mouseout(e){this._map.fire(new ir(e.type,this._map,e));}touchstart(e){return this._firePreventable(new or(e.type,this._map,e))}touchmove(e){this._map.fire(new or(e.type,this._map,e));}touchend(e){this._map.fire(new or(e.type,this._map,e));}touchcancel(e){this._map.fire(new or(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class sr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new ir(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ir("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new ir(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class nr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class lr{constructor(e,t){this._map=e,this._tr=new nr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1,t.boxZoom&&"object"==typeof t.boxZoom&&(this._boxZoomEnd=t.boxZoom.boxZoomEnd);}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(h.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,a,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(this._box.remove(),this._box=null),h.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function cr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=cr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=cr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class ur{constructor(e){this.singleTap=new hr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class dr{constructor(e){this._tr=new nr(e),this._zoomIn=new ur({numTouches:1,numTaps:2}),this._zoomOut=new ur({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,i,o){const a=this._zoomIn.touchend(e,i,o),r=this._zoomOut.touchend(e,i,o),s=this._tr;return a?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:i=>i.easeTo({duration:300,zoom:t.cv(s.zoom+1,i.getZoomSnap()),around:s.unproject(a)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:i=>i.easeTo({duration:300,zoom:t.cv(s.zoom-1,i.getZoomSnap()),around:s.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class _r{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new vr){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const br=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class yr{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const a=cr(o,i),r=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in a){const t=a[e],i=this._touches[e];i&&(r._add(t),s._add(t.sub(i)),n++,a[e]=t);}if(this._touches=a,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class Sr extends wr{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,Er(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),a=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,a,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+a.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,a=t.mag()>=2;if(!o&&!a)return;if(!o||!a)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const r=e.y>0==t.y>0;return Er(e)&&Er(t)&&r}}const Rr={panStep:100,bearingStep:15,pitchStep:10};class zr{constructor(e){this._tr=new nr(e);const t=Rr;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let i=0,o=0,a=0,r=0,s=0;switch(e.keyCode){case 61:case 107:case 171:case 187:i=1;break;case 189:case 109:case 173:i=-1;break;case 37:e.shiftKey?o=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?o=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?a=1:(e.preventDefault(),s=-1);break;case 40:e.shiftKey?a=-1:(e.preventDefault(),s=1);break;default:return}return this._rotationDisabled&&(o=0,a=0),{cameraAnimation:n=>{const l=this._tr;n.easeTo({duration:300,easeId:"keyboardHandler",easing:Dr,zoom:i?t.cv(l.zoom+i*(e.shiftKey?2:1),n.getZoomSnap()):l.zoom,bearing:l.bearing+o*this._bearingStep,pitch:l.pitch+a*this._pitchStep,offset:[-r*this._panStep,-s*this._panStep],center:l.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function Dr(e){return e*(2-e)}const Ar=4.000244140625,Lr=1/450;class kr{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new nr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=Lr;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=c(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%Ar==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=h.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.V.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>Ar?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const a="number"!=typeof this._targetZoom?e.scale:t.an(this._targetZoom),r=e.applyConstrain(e.getCameraLngLat(),t.aq(a*o)).zoom,s=this._map.getZoomSnap();if("wheel"===this._type&&s>0){const i=t.cv(e.zoom,s);this._targetZoom=t.cv(r,s,r-i);}else this._targetZoom=r;"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,a=this._easing;let r,s=!1;if("wheel"===this._type&&o&&a){const e=c()-this._lastWheelEventTime,n=Math.min((e+5)/200,1),l=a(n);r=t.G.number(o,i,l),n<1?this._frameId||(this._frameId=!0):s=!0;}else r=i,s=!0;return this._active=!0,s&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=r,{noInertia:!0,needsRenderFrame:!s,zoomDelta:r-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.cx;if(this._prevEase){const e=this._prevEase,o=(c()-e.start)/e.duration,a=e.easing(o+.01)-e.easing(o),r=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-r*r);i=t.cu(r,s,.25,1);}return this._prevEase={start:c(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class Fr{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class Br{constructor(e){this._tr=new nr(e),this.reset();}reset(){this._active=!1;}dblclick(e,i){return e.preventDefault(),{cameraAnimation:o=>{o.easeTo({duration:300,zoom:t.cv(this._tr.zoom+(e.shiftKey?-1:1),o.getZoomSnap()),around:this._tr.unproject(i)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Or{constructor(){this._tap=new ur({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],a=e.timeStamp-this._tapTime<500,r=this._tapPoint.dist(o)<30;a&&r?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],a=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:a/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class jr{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Zr{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Nr{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ur{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=h.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const a=document.createElement("div");a.className="maplibregl-mobile-message",a.textContent=i,this._container.appendChild(a),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(this._container.remove(),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Gr=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Vr extends t.l{}function Wr(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class qr{get _ownerDocument(){var e;return (null===(e=this._el)||void 0===e?void 0:e.ownerDocument)||document}get _ownerWindow(){var e,t;return (null===(t=null===(e=this._el)||void 0===e?void 0:e.ownerDocument)||void 0===t?void 0:t.defaultView)||window}constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,a={needsRenderFrame:!1},r={},s={};for(const{handlerName:n,handler:l,allowed:c}of this._handlers){if(!l.isEnabled())continue;let u;if(this._blockedByActive(s,c,n))l.reset();else if(l[i||e.type]){if(t.cy(e,i||e.type)){const t=h.mousePos(this._map.getCanvas(),e);u=l[i||e.type](e,t);}else if(t.cz(e,i||e.type)){const t=this._getMapTouches(e.touches),o=h.touchPos(this._map.getCanvas(),t);u=l[i||e.type](e,o,t);}else t.cA(i||e.type)||(u=l[i||e.type](e));this.mergeHandlerResult(a,r,u,n,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||l.isActive())&&(s[n]=l);}const n={};for(const e in this._previousActiveHandlers)s[e]||(n[e]=o);this._previousActiveHandlers=s,(Object.keys(n).length||Wr(a))&&(this._changes.push([a,r,n]),this._triggerRenderFrame()),(Object.keys(s).length||Wr(a))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:l}=a;l&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],l(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ja(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[this._ownerDocument,"mousemove",{capture:!0}],[this._ownerDocument,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[this._ownerWindow,"blur",void 0]];for(const[e,t,i]of this._listeners)e.addEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)e.removeEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new rr(i,e));const a=i.boxZoom=new lr(i,e);this._add("boxZoom",a),e.interactive&&e.boxZoom&&a.enable();const r=i.cooperativeGestures=new Ur(i,e.cooperativeGestures);this._add("cooperativeGestures",r),e.cooperativeGestures&&r.enable();const s=new dr(i),n=new Br(i);i.doubleClickZoom=new Fr(n,s),this._add("tapZoom",s),this._add("clickZoom",n),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const l=new Or;this._add("tapDragZoom",l);const c=i.touchPitch=new Sr(i);this._add("touchPitch",c),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const h=()=>i.project(i.getCenter()),u=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:a=100,rotateDegreesPerPixelMoved:r=.8},s){const n=new gr({checkCorrectEvent:e=>0===e.button&&e.ctrlKey||2===e.button&&!e.ctrlKey});return new _r({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>a)return {bearingDelta:t.cw(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*r;return o&&i.y0===e.button&&e.ctrlKey||2===e.button});return new _r({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:br})}(e),_=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const a=new gr({checkCorrectEvent:e=>2===e.button&&e.ctrlKey});return new _r({clickTolerance:t,move:(e,t)=>{const a=o();let r=(t.x-e.x)*i;return t.y0===e.button&&!e.ctrlKey});return new _r({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:br})}(e),m=new yr(e,i);i.dragPan=new jr(o,p,m),this._add("mousePan",p),this._add("touchPan",m,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const f=new Mr,g=new Cr;i.touchZoomRotate=new Nr(o,g,f,l),this._add("touchRotate",f,["touchPan","touchZoom"]),this._add("touchZoom",g,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate),this._add("blockableMapEvent",new sr(i));const v=i.scrollZoom=new kr(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",v,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new zr(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable();}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Gr(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,a,r){if(!o)return;t.e(e,o);const s={handlerName:a,originalEvent:o.originalEvent||r};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[a,r,s]of this._changes)a.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(a.panDelta)),a.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+a.zoomDelta),a.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+a.bearingDelta),a.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+a.pitchDelta),a.rollDelta&&(e.rollDelta=(e.rollDelta||0)+a.rollDelta),void 0!==a.around&&(e.around=a.around),void 0!==a.pinchAround&&(e.pinchAround=a.pinchAround),a.noInertia&&(e.noInertia=a.noInertia),t.e(i,r),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,a=o._getTransformForUpdate(),r=o.terrain;if(!(Wr(e)||r&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,r&&!a.isPointOnMapSurface(u)&&(u=a.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!a.isPointOnMapSurface(u)&&(u=a.centerPoint);const p=u.distSqr(a.centerPoint)<.01?a.center:a.screenPointToLocation(s?u.sub(s):u);this._handleMapControls({terrain:r,tr:a,deltasForHelper:_,preZoomAroundLoc:p,combinedEventsInProgress:t,panDelta:s}),o._applyUpdatedTransform(a),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_handleMapControls({terrain:e,tr:t,deltasForHelper:i,preZoomAroundLoc:o,combinedEventsInProgress:a,panDelta:r}){const s=this._map.cameraHelper;if(s.handleMapControlsRollPitchBearingZoom(i,t),e)return s.useGlobeControls?(this._terrainMovement||!a.drag&&!a.zoom||(this._terrainMovement=!0,this._map._elevationFreeze=!0),void s.handleMapControlsPan(i,t,o)):this._terrainMovement||!a.drag&&!a.zoom?void(a.drag&&this._terrainMovement&&r?t.setCenter(t.screenPointToLocation(t.centerPoint.sub(r))):s.handleMapControlsPan(i,t,o)):(this._terrainMovement=!0,this._map._elevationFreeze=!0,void s.handleMapControlsPan(i,t,o));s.handleMapControlsPan(i,t,o);}_fireEvents(e,i,o){const a=Gr(this._eventsInProgress),r=Gr(e),s={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(s[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!a&&r&&this._fireEvent("movestart",r.originalEvent);for(const e in s)this._fireEvent(e,s[e]);r&&this._fireEvent("move",r.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Gr(this._eventsInProgress),u=(a||r)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Vr("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class $r extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((c()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this._zoomSnap=i.zoomSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform,!0),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.V(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,i){return this.zoomTo(t.cv(this.getZoom()+1,this._zoomSnap),e,i),this}zoomOut(e,i){return this.zoomTo(t.cv(this.getZoom()-1,this._zoomSnap),e,i),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setZoomSnap(e){return this._zoomSnap=e,this}getZoomSnap(){return this._zoomSnap}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.G.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:a,roll:r,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==a&&t.setZoom(a),void 0!==r&&t.setRoll(r),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t,!1);}this.transform.apply(i,!1);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,a=this._rotating,r=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),a&&this.fire(new t.l("rotateend",e)),r&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&n.prefersReducedMotion){const o=t.U(e,["center","zoom","bearing","pitch","roll","elevation","padding"]);return this.jumpTo(o,i)}this.stop(),"zoom"in(e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.cx},e))&&this._zoomSnap&&(e.zoom=t.cv(e.zoom,this._zoomSnap));const o=this._getTransformForUpdate(),a=o.bearing,r=o.pitch,s=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,a):a,h="pitch"in e?+e.pitch:r,u="roll"in e?this._normalizeBearing(e.roll,s):s,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),x=v/f.scaleOfZoom,b=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/b*2));const y=g*g;function w(e){const t=(x*x-v*v+(e?-1:1)*y*y*b*b)/(2*(e?x:v)*y*b);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/b;var t;},E=(w(!0)-C)/g;if(Math.abs(b)<2e-6||!isFinite(E)){if(Math.abs(v-x)<1e-6)return this.easeTo(e,i);const t=x0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*E/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=a!==c,this._pitching=h!==r,this._rolling=u!==s,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((n=>{const m=n*E,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.G.number(a,c,n)),this._pitching&&o.setPitch(t.G.number(r,h,n)),this._rolling&&o.setRoll(t.G.number(s,u,n)),this._padding&&(o.interpolatePadding(l,d,n),p=o.centerPoint.add(_)),f.easeFunc(n,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(n),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=c(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.W(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Xr{constructor(e=Hr){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=h.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=h.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=h.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.tileManagers;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=h.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Kr{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=h.create("div","maplibregl-ctrl");const t=h.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class Yr{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var Qr=t.aS([{name:"a_pos3d",type:"Int16",components:3}]);class Jr extends t.E{constructor(e){super(),this._lastTilesetChange=c(),this.tileManager=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.tileManager.usedForTerrain=!1,this.tileManager.tileSize=null;}getSource(){return this.tileManager._source}update(e,i){this.tileManager.update(e,i),this._renderableTilesKeys=[];const o={};for(const a of Pe(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.tileManager._source.calculateTileZoom}))o[a.key]=!0,this._renderableTilesKeys.push(a.key),this._tiles[a.key]||(a.terrainRttPosMatrix32f=new Float64Array(16),t.c6(a.terrainRttPosMatrix32f,0,t.a5,t.a5,0,0,1),this._tiles[a.key]=new he(a,this.tileSize),this._lastTilesetChange=c());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const a=this._tiles[o].tileID,r=e.clone(),s=t.bi();if(a.canonical.equals(e.canonical))t.c6(s,0,t.a5,t.a5,0,0,1);else if(a.canonical.isChildOf(e.canonical)){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i;t.c6(s,0,n,n,0,0,1),t.O(s,s,[-o*n,-r*n,0]);}else {if(!e.canonical.isChildOf(a.canonical))continue;{const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.c6(s,0,t.a5,t.a5,0,0,1),t.O(s,s,[o*n,r*n,0]),t.Q(s,s,[1/2**i,1/2**i,0]);}}r.terrainRttPosMatrix32f=new Float32Array(s),i[o]=r;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const a of this._renderableTilesKeys){const r=this._tiles[a].tileID;if(!this._isWithinTileRanges(r,i))continue;const s=e.clone(),n=t.bi();if(r.canonical.z===e.canonical.z){const i=e.canonical.x-r.canonical.x+e.wrap*(1<e.canonical.z){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i),l=e.canonical.y-(r.canonical.y>>i),c=t.a5>>i;t.c6(n,0,c,c,0,0,1),t.O(n,n,[-o*c+s*t.a5,-a*c+l*t.a5,0]);}else {const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-r.canonical.x,l=(e.canonical.y>>i)-r.canonical.y,c=t.a5<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&!(null==a?void 0:a.dem);)a=this.findTileInCaches(e.scaledTo(o--).key);return a}findTileInCaches(e){let t=this.tileManager.getTileByID(e);return t||(t=this.tileManager._outOfViewCache.getByKey(e),t)}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){const i=t[e.canonical.z];return !!i&&(e.wrap>i.minWrap||e.wrap=i.minTileXWrapped&&e.canonical.x<=i.maxTileXWrapped&&e.canonical.y>=i.minTileY&&e.canonical.y<=i.maxTileY)}}class es{constructor(e,t,i){this._meshCache={},this.painter=e,this.tileManager=new Jr(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}destroy(){this._fbo&&(this._fbo.destroy(),this._fbo=null),this._fboCoordsTexture&&(this._fboCoordsTexture.destroy(),this._fboCoordsTexture=null),this._fboDepthTexture&&(this._fboDepthTexture.destroy(),this._fboDepthTexture=null),this._emptyDemTexture&&(this._emptyDemTexture.destroy(),this._emptyDemTexture=null),this._emptyDepthTexture&&(this._emptyDepthTexture.destroy(),this._emptyDepthTexture=null),this._coordsTexture&&(this._coordsTexture.destroy(),this._coordsTexture=null);for(const e in this._meshCache)this._meshCache[e].destroy();this._meshCache={},this.tileManager.destruct();}getDEMElevation(e,i,o,a=t.a5){var r;const s=e.normalizeCoordinates(i,o,a);if(!s)return 0;const n=this.getTerrainData(s.tileID),l=null===(r=n.tile)||void 0===r?void 0:r.dem;if(!l)return 0;const c=t.cB([],[s.x/a*t.a5,s.y/a*t.a5],n.u_terrain_matrix),h=[c[0]*l.dim,c[1]*l.dim],u=Math.floor(h[0]),d=Math.floor(h[1]),_=h[0]-u,p=h[1]-d;return l.get(u,d)*(1-_)*(1-p)+l.get(u+1,d)*_*(1-p)+l.get(u,d+1)*(1-_)*p+l.get(u+1,d+1)*_*p}getElevationForLngLatZoom(e,i){if(!t.cC(i,e.wrap()))return 0;const{tileID:o,mercatorX:a,mercatorY:r}=this._getOverscaledTileIDFromLngLatZoom(e,i);return this.getElevation(o,a%t.a5,r%t.a5,t.a5)}getElevationForLngLat(e,t){const i=Pe(t,{maxzoom:this.tileManager.maxzoom,minzoom:this.tileManager.minzoom,tileSize:512,terrain:this});let o=0;for(const e of i)e.canonical.z>o&&(o=Math.min(e.canonical.z,this.tileManager.maxzoom));return this.getElevationForLngLatZoom(e,o)}getElevation(e,i,o,a=t.a5){return this.getDEMElevation(e,i,o,a)*this.exaggeration}getTerrainData(e){if(!this._emptyDemTexture){const e=this.painter.context,i=new t.R({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new t.T(e,i,e.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new t.T(e,new t.R({width:1,height:1}),e.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=t.ao([]);}const i=this.tileManager.getSourceTile(e,!0);if(i&&i.dem&&(!i.demTexture||i.needsTerrainPrepare)){const e=this.painter.context;i.demTexture=this.painter.getTileTexture(i.dem.stride),i.demTexture?i.demTexture.update(i.dem.getPixels(),{premultiply:!1}):i.demTexture=new t.T(e,i.dem.getPixels(),e.gl.RGBA,{premultiply:!1}),i.demTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),i.needsTerrainPrepare=!1;}const o=i&&i.toString()+i.tileID.key+e.key;if(o&&!this._demMatrixCache[o]){const o=this.tileManager.getSource().maxzoom;let a=e.canonical.z-i.tileID.canonical.z;e.overscaledZ>e.canonical.z&&(e.canonical.z>=o?a=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const r=e.canonical.x-(e.canonical.x>>a<>a<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),a=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return a.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=a,a}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,a=o.gl,r=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),a.readPixels(r,n-s-1,1,1,a.RGBA,a.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.tileManager.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,a=o&&0===e.canonical.y,r=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const is={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class os{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new ts(e.context,30,t.tileManager.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){var i,o;this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.tileManager.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.tileManagers){this._coordsAscending[t]={};const i=e.tileManagers[t].getVisibleCoordinates(),o=e.tileManagers[t].getSource(),a=o instanceof J?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.tileManager.getTerrainCoords(e,a);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._rttFingerprints={};for(const t of e._order){const a=e._layers[t],r=a.source;if(is[a.type]&&!this._rttFingerprints[r]){this._rttFingerprints[r]={};const t=null!==(o=null===(i=e.tileManagers[r])||void 0===i?void 0:i.getState().revision)&&void 0!==o?o:0;for(const e in this._coordsAscending[r])this._rttFingerprints[r][e]=`${this._coordsAscending[r][e].map((e=>e.key)).sort().join()}#${t}`;}}for(const e of this._renderableTiles)for(const t in this._rttFingerprints){const i=this._rttFingerprints[t][e.tileID.key];i&&i!==e.rttFingerprint[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),a=e.type,r=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(is[a]&&(this._prevType&&is[this._prevType]||this._stacks.push([]),this._prevType=a,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(is[this._prevType]||is[a]&&s){this._prevType=a;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const a of this._renderableTiles){if(this.pool.isFull()&&(Ua(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(a),a.rtt[e]){const t=this.pool.getObjectForId(a.rtt[e].id);if(t.stamp===a.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),a.rtt[e]={id:s.id,stamp:s.stamp},r.context.bindFramebuffer.set(s.fbo.framebuffer),r.context.clear({color:t.bn.transparent,stencil:0}),r.currentStencilSource=void 0;for(let e=0;ea.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=a.minPitch&&null!=a.maxPitch&&a.minPitch>a.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=a.minPitch&&a.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=a.maxPitch&&a.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const r=new Wt,s=new Xt;void 0!==a.minZoom&&r.setMinZoom(a.minZoom),void 0!==a.maxZoom&&r.setMaxZoom(a.maxZoom),void 0!==a.minPitch&&r.setMinPitch(a.minPitch),void 0!==a.maxPitch&&r.setMaxPitch(a.maxPitch),void 0!==a.renderWorldCopies&&r.setRenderWorldCopies(a.renderWorldCopies),null!==a.transformConstrain&&r.setConstrainOverride(a.transformConstrain),super(r,s,{bearingSnap:a.bearingSnap,zoomSnap:a.zoomSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Yr,this._controls=[],this._mapId=t.ac(),this._lostContextStyle={style:null,images:null},this._contextLost=e=>{if(e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.painter.destroy(),this._lostContextStyle=this._getStyleAndImages(),this.style){for(const e of Object.values(this.style._layers))if("custom"===e.type&&console.warn(`Custom layer with id '${e.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`),e._listeners)for(const[t]of Object.entries(e._listeners))console.warn(`Custom layer with id '${e.id}' had event listeners for event '${t}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);this.style.destroy(),this.style=null,this.fire(new t.l("webglcontextlost",{originalEvent:e}));}else this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._lostContextStyle.style&&this.setStyle(this._lostContextStyle.style,{diff:!1}),this._lostContextStyle.images&&(this.style.imageManager.images=this._lostContextStyle.images),this._lostContextStyle={style:null,images:null},this._setupPainter(),this.resize(),this._update(),this._resizeInternal(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=a.interactive,this._maxTileCacheSize=a.maxTileCacheSize,this._maxTileCacheZoomLevels=a.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},a.canvasContextAttributes),this._trackResize=!0===a.trackResize,this._bearingSnap=a.bearingSnap,this._zoomSnap=a.zoomSnap,this._centerClampedToGround=a.centerClampedToGround,this._refreshExpiredTiles=!0===a.refreshExpiredTiles,this._fadeDuration=a.fadeDuration,this._crossSourceCollisions=!0===a.crossSourceCollisions,this._collectResourceTiming=!0===a.collectResourceTiming,this._locale=Object.assign(Object.assign({},as),a.locale),this._clickTolerance=a.clickTolerance,this._overridePixelRatio=a.pixelRatio,this._maxCanvasSize=a.maxCanvasSize,this._zoomLevelsToOverscale=a.experimentalZoomLevelsToOverscale,this.transformCameraUpdate=a.transformCameraUpdate,this.transformConstrain=a.transformConstrain,this.cancelPendingTileRequestsWhileZooming=!0===a.cancelPendingTileRequestsWhileZooming,this.setAnisotropicFilterPitch(a.anisotropicFilterPitch),void 0!==a.reduceMotion&&(n.prefersReducedMotion=a.reduceMotion),this._imageQueueHandle=u.addThrottleControl((()=>this.isMoving())),this._requestManager=new d(a.transformRequest),this._container=this._resolveContainer(a.container),a.maxBounds&&this.setMaxBounds(a.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window&&(this._ownerWindow.addEventListener("online",this._onWindowOnline,!1),this._setupResizeObserver()),this.handlers=new qr(this,a),this._hash=a.hash&&new qa("string"==typeof a.hash&&a.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:a.center,elevation:a.elevation,zoom:a.zoom,bearing:a.bearing,pitch:a.pitch,roll:a.roll}),a.bounds&&(this.resize(),this.fitBounds(a.bounds,t.e({},a.fitBoundsOptions,{duration:0}))));const l="string"==typeof a.style||!("globe"===(null===(o=null===(i=a.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,l),this._localIdeographFontFamily=a.localIdeographFontFamily,this._validateStyle=a.validateStyle,a.style&&this.setStyle(a.style,{localIdeographFontFamily:a.localIdeographFontFamily}),a.attributionControl&&this.addControl(new Xr("boolean"==typeof a.attributionControl?void 0:a.attributionControl)),a.maplibreLogo&&this.addControl(new Kr,a.logoPosition),this.on("style.load",(()=>{if(l||this._resizeTransform(),this.transform.unmodified){const e=t.U(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const a=this._controlPositions[i];return -1!==i.indexOf("bottom")?a.insertBefore(o,a.firstChild):a.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return Pe(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLat(i,this.transform)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){if(null!==this._lostContextStyle.style)return this;this._resizeInternal(i);const o=!this._moving;return o&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),o&&this.fire(new t.l("moveend",e)),this}_resizeInternal(e=!0){const[t,i]=this._containerDimensions(),o=this._getClampedPixelRatio(t,i);if(this._resizeCanvas(t,i,o),this.painter.resize(t,i,o),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const o=this._getClampedPixelRatio(t,i);this._resizeCanvas(t,i,o),this.painter.resize(t,i,o);}this._resizeTransform(e);}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,a=this.getPixelRatio(),r=e*a,s=t*a;return Math.min(r>i?i/r:1,s>o?o/s:1)*a}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(N.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom){const i=this.transform.zoom,o=this._getTransformForUpdate();return o.setMinZoom(e),this._applyUpdatedTransform(o),this._update(),i!==this.transform.zoom&&this.fire(new t.l("zoomstart")).fire(new t.l("zoom")).fire(new t.l("zoomend")).fire(new t.l("movestart")).fire(new t.l("move")).fire(new t.l("moveend")),this}throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(e){if((e=null==e?22:e)>=this.transform.minZoom){const i=this.transform.zoom,o=this._getTransformForUpdate();return o.setMaxZoom(e),this._applyUpdatedTransform(o),this._update(),i!==this.transform.zoom&&this.fire(new t.l("zoomstart")).fire(new t.l("zoom")).fire(new t.l("zoomend")).fire(new t.l("movestart")).fire(new t.l("move")).fire(new t.l("moveend")),this}throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch){const i=this.transform.pitch,o=this._getTransformForUpdate();return o.setMinPitch(e),this._applyUpdatedTransform(o),this._update(),i!==this.transform.pitch&&this.fire(new t.l("pitchstart")).fire(new t.l("pitch")).fire(new t.l("pitchend")).fire(new t.l("movestart")).fire(new t.l("move")).fire(new t.l("moveend")),this}throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(e){if((e=null==e?60:e)>180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch){const i=this.transform.pitch,o=this._getTransformForUpdate();return o.setMaxPitch(e),this._applyUpdatedTransform(o),this._update(),i!==this.transform.pitch&&this.fire(new t.l("pitchstart")).fire(new t.l("pitch")).fire(new t.l("pitchend")).fire(new t.l("movestart")).fire(new t.l("move")).fire(new t.l("moveend")),this}throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getAnisotropicFilterPitch(){return this._anisotropicFilterPitch}setAnisotropicFilterPitch(e){if((e=null==e?20:e)>180)throw new Error("anisotropicFilterPitch must be less than or equal to 180");if(e<0)throw new Error("anisotropicFilterPitch must be greater than or equal to 0");return this._anisotropicFilterPitch=e,this._update()}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}setTransformConstrain(e){return this.transform.setConstrainOverride(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.V.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const a=a=>{const r=t.filter((e=>this.getLayer(e))),s=0!==r.length?this.queryRenderedFeatures(a.point,{layers:r}):[];s.length?o||(o=!0,i.call(this,new ir(e,this,a.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:a,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const a=a=>{const r=t.filter((e=>this.getLayer(e)));(0!==r.length?this.queryRenderedFeatures(a.point,{layers:r}):[]).length?o=!0:o&&(o=!1,i.call(this,new ir(e,this,a.originalEvent)));},r=t=>{o&&(o=!1,i.call(this,new ir(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:a,mouseout:r}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),a=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];a.length&&(e.features=a,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in a.delegates)this.off(e,a.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,a=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,a);for(const e in a.delegates)this.on(e,a.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,a=this._createDelegatedListener(e,o,i);for(const t in a.delegates){const r=a.delegates[t];a.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),r(...t);};}this._saveDelegatedListener(e,a);for(const e in a.delegates)this.once(e,a.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const a=e instanceof t.P||Array.isArray(e),r=a?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(a?{}:e)||{},r instanceof t.P||"number"==typeof r[0])o=[t.P.convert(r)];else {const e=t.P.convert(r[0]),i=t.P.convert(r[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o,a;if(null===(i=this._diffStyleRequest)||void 0===i||i.abort(),this._diffStyleRequest=null,t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new Ai(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),null===(a=null===(o=this.style)||void 0===o?void 0:o.projection)||void 0===a||a.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new Ai(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){return t._(this,void 0,void 0,(function*(){var o;if(null===(o=this._diffStyleRequest)||void 0===o||o.abort(),"string"==typeof e){const o=e;this._diffStyleRequest=new AbortController;const a=this._diffStyleRequest;try{const e=yield this._requestManager.transformRequest(o,"Style");if(a.signal.aborted)return void(this._diffStyleRequest=null);const r=yield t.j(e,a);this._diffStyleRequest=null,this._updateDiff(r.data,i);}catch(e){this._diffStyleRequest=null,t.Z(e)||this.fire(new t.k(e));}}else "object"==typeof e&&(this._diffStyleRequest=null,this._updateDiff(e,i));}))}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}_getStyleAndImages(){return this.style?{style:this.style.serialize(),images:this.style.imageManager.cloneImages()}:{style:null,images:{}}}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.tileManagers[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no tile manager with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.tileManagers[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("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.");}this.terrain=new es(this.painter,i,e),this.painter.renderToTexture=new os(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.tileManager.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.tileManager.freeRtt():this.terrain.tileManager.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.destroy(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.tileManagers;for(const t of Object.values(e))if(!t.areTilesLoaded())return !1;return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=ye(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.tileManagers)this.style.tileManagers[i].getSource().calculateTileZoom=ye(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.tileManagers[e];if(!o)throw new Error(`There is no tile manager with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a9(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:a=1,sdf:r=!1,stretchX:s,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:n,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:n},new Uint8Array(d)),pixelRatio:a,stretchX:s,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:r,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=n.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:a,stretchX:s,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:r,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const a=i instanceof HTMLImageElement||t.b(i)?n.getImageData(i):i,{width:r,height:s,data:l}=a;if(void 0===r||void 0===s)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(r!==o.data.width||s!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return t._(this,void 0,void 0,(function*(){return u.getImage(yield this._requestManager.transformRequest(e,"Image"),new AbortController)}))}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupResizeObserver(){var e;let t=!1;const i=Wa((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50),o=null!==(e=this._ownerWindow.ResizeObserver)&&void 0!==e?e:ResizeObserver;this._resizeObserver=new o((e=>{t?i(e):t=!0;})),this._resizeObserver.observe(this._container);}_resolveContainer(e){if("string"==typeof e){const t=document.getElementById(e);if(!t)throw new Error(`Container '${e}' not found.`);return t}if(e instanceof HTMLElement)return e;if(e&&"object"==typeof e&&1===e.nodeType)return e;throw new Error("Invalid type: 'container' must be a String or HTMLElement.")}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=h.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=h.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const a=this._controlContainer=h.create("div","maplibregl-control-container",e),r=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{r[e]=h.create("div",`maplibregl-ctrl-${e} `,a);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Va(i,this.transform);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,a,r,s;const n=this._idleTriggered?this._fadeDuration:0,l=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=c();this.style.zoomHistory.update(e,i);const o=new t.H(e,{now:i,fadeDuration:n,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),a=o.crossFadingFactor();1===a&&a===this._crossFadingFactor||(h=!0,this._crossFadingFactor=a),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==l;null===(a=this.style.projection)||void 0===a||a.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(r=this.style.projection)||void 0===r?void 0:r.transitionState,null===(s=this.style.projection)||void 0===s?void 0:s.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.tileManager.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,n,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:n,showPadding:this.showPadding,anisotropicFilterPitch:this.getAnisotropicFilterPitch()}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e,i;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),null===(e=this._diffStyleRequest)||void 0===e||e.abort(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&this._ownerWindow.removeEventListener("online",this._onWindowOnline,!1),u.removeThrottleControl(this._imageQueueHandle),null===(i=this._resizeObserver)||void 0===i||i.disconnect();const o=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==o?void 0:o.loseContext)&&o.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,n.frame(this._frameRequest,(e=>{this._frameRequest=null;try{this._render(e);}catch(e){if(!t.Z(e)&&!function(e){return e.message===aa}(e))throw e}}),(()=>{}),this._ownerWindow));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return rs}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}};const ls={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class cs{constructor(e,i,o=!1){this.mousedown=e=>{this.startMove(e,h.mousePos(this.element,e)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,h.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=h.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),window.addEventListener("touchmove",this.touchmove,{passive:!1}),window.addEventListener("touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=h.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const a=new xr;this._rotatePitchHandler=new _r({clickTolerance:3,move:(e,a)=>{const r=i.getBoundingClientRect(),s=new t.P((r.bottom-r.top)/2,(r.right-r.left)/2);return {bearingDelta:t.cw(new t.P(e.x,a.y),a,s),pitchDelta:o?-.5*(a.y-e.y):void 0}},moveStateManager:a,enable:!0,assignEvents:()=>{}}),this.map=e,i.addEventListener("mousedown",this.mousedown),i.addEventListener("touchstart",this.touchstart,{passive:!1}),i.addEventListener("touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),h.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:a}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),a&&i.setPitch(i.getPitch()+a);}off(){const e=this.element;e.removeEventListener("mousedown",this.mousedown),e.removeEventListener("touchstart",this.touchstart),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend),e.removeEventListener("touchcancel",this.reset),this.offTemp();}offTemp(){h.enableDrag(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend);}}let hs;function us(e,i,o,a=!1){if(a||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const r=new t.V(e.lng,e.lat);if(e=new t.V(e.lng,e.lat),i){const a=new t.V(e.lng-360,e.lat),r=new t.V(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(a).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==r.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:r}const ds={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function _s(e,t,i){const o=e.classList;for(const e in ds)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class ps extends t.E{constructor(e){if(super(),this._onClick=e=>{this.fire(new t.l("click",{originalEvent:e}));},this._onKeyPress=e=>{"Space"!==e.code&&"Enter"!==e.code||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=us(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),this._element.style.transform=`${ds[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`,n.frameAsync(new AbortController,this._map._ownerWindow).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=h.create("div");const i=h.createNS("http://www.w3.org/2000/svg","svg"),o=41,a=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${a}px`),i.setAttributeNS(null,"viewBox",`0 0 ${a} ${o}`);const r=h.createNS("http://www.w3.org/2000/svg","g");r.setAttributeNS(null,"stroke","none"),r.setAttributeNS(null,"stroke-width","1"),r.setAttributeNS(null,"fill","none"),r.setAttributeNS(null,"fill-rule","evenodd");const s=h.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const n=h.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"transform","translate(3.0, 29.0)"),n.setAttributeNS(null,"fill","#000000");const l=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of l){const t=h.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),n.appendChild(t);}const c=h.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill",this._color);const u=h.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),c.appendChild(u);const d=h.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=h.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=h.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=h.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=h.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=h.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(n),s.appendChild(c),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",a*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),_s(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),this._element.hasAttribute("role")||this._element.setAttribute("role","button"),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this._element.addEventListener("click",this._onClick),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),this._element.removeEventListener("click",this._onClick),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.V.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const a=null===(i=this._map)||void 0===i?void 0:i.terrain,r=this._map.transform.isLocationOccluded(this._lngLat);if(!a||r){const e=r?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLat(this._lngLat,s.transform);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const ms={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let fs=0,gs=!1;const vs={maxWidth:100,unit:"metric"};function xs(e,t,i){const o=i&&i.maxWidth||100,a=e._container.clientHeight/2,r=e._container.clientWidth/2,s=e.unproject([r-o/2,a]),n=e.unproject([r+o/2,a]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?bs(t,c,i/5280,e._getUIString("ScaleControl.Miles")):bs(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?bs(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?bs(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):bs(t,c,h,e._getUIString("ScaleControl.Meters"));}function bs(e,t,i,o){const a=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(a/i)+"px",e.innerHTML=`${a} ${o}`;}const ys={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0,padding:void 0},ws=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function Ts(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return Ts(new t.P(0,0))}const Ps=i;e.AJAXError=t.cF,e.EXTENT=t.a5,e.Event=t.l,e.Evented=t.E,e.LngLat=t.V,e.MercatorCoordinate=t.a6,e.Point=t.P,e.addProtocol=t.cG,e.config=t.c,e.removeProtocol=t.cH,e.AttributionControl=Xr,e.BoxZoomHandler=lr,e.CanvasSource=te,e.CooperativeGesturesHandler=Ur,e.DoubleClickZoomHandler=Fr,e.DragPanHandler=jr,e.DragRotateHandler=Zr,e.EdgeInsets=Ot,e.FullscreenControl=class extends t.E{constructor(e={}){var i;super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.webkitFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,this._pseudo=null!==(i=e.pseudo)&&void 0!==i&&i,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=h.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=h.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);h.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){this._pseudo?this._togglePseudoFullScreen():window.document.exitFullscreen?window.document.exitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._pseudo?this._togglePseudoFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=Q,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.V(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,a=this._map.getBearing(),r=t.e({bearing:a},this.options.fitBoundsOptions),s=N.fromLngLat(i,o);this._map.fitBounds(s,r,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.V(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&gs)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._onMoveStart=e=>{if(!this._map)return;const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=h.create("button","maplibregl-ctrl-geolocate",this._container),h.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=h.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new ps({element:this._dotElement}),this._circleElement=h.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new ps({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",this._onMoveStart);}},this.options=t.e({},ms,e);}onAdd(e){return this._map=e,this._container=h.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==hs&&!e)return hs;if(void 0===window.navigator.permissions)return hs=!!window.navigator.geolocation,hs;try{const e=yield window.navigator.permissions.query({name:"geolocation"});hs="denied"!==e.state;}catch(e){hs=!!window.navigator.geolocation;}return hs}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("movestart",this._onMoveStart),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,fs=0,gs=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":case "BACKGROUND_ERROR":case "OFF":case void 0:break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,a=2*this._accuracy/o;this._circleElement.style.width=`${a.toFixed(2)}px`,this._circleElement.style.height=`${a.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":fs--,gs=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),fs++,fs>1?(e={maximumAge:6e5,timeout:0},gs=!0):(e=this.options.positionOptions,gs=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=h.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=h.create("button","maplibregl-ctrl-globe",this._container),h.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._map.on("projectiontransition",this._updateGlobeIcon),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateGlobeIcon),this._map.off("projectiontransition",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=qa,e.ImageSource=J,e.KeyboardHandler=zr,e.LngLatBounds=N,e.LogoControl=Kr,e.Map=ns,e.MapLibreMap=ns,e.MapMouseEvent=ir,e.MapTouchEvent=or,e.MapWheelEvent=ar,e.Marker=ps,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},ls,e),this._container=h.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),h.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),h.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=h.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new cs(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){this._container.remove(),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=h.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&this._content.remove(),this._container&&(this._container.remove(),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._update),this._map.off("mouseup",this._update),this._map.off("drag",this._update),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=h.create("div","maplibregl-popup",this._map.getContainer()),this._tip=h.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}let t;if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=us(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),e&&"point"in e&&e.point&&(t=e.point),this._trackPointer&&!t)return;const i=this._flatPos=this._pos=this._trackPointer&&t?t:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&t?t:this._map.transform.locationToScreenPoint(this._lngLat));let o=this.options.anchor;const a=Ts(this.options.offset);if(!o){const e=this._container.offsetWidth,t=this._container.offsetHeight,r=function(e){var t,i,o,a;return e?{top:null!==(t=e.top)&&void 0!==t?t:0,right:null!==(i=e.right)&&void 0!==i?i:0,bottom:null!==(o=e.bottom)&&void 0!==o?o:0,left:null!==(a=e.left)&&void 0!==a?a:0}:{top:0,right:0,bottom:0,left:0}}(this.options.padding);let s;s=i.y+a.bottom.ythis._map.transform.height-t-r.bottom?["bottom"]:[],i.xthis._map.transform.width-e/2-r.right&&s.push("right"),o=0===s.length?"bottom":s.join("-");}let r=i.add(a[o]);this.options.subpixelPositioning||(r=r.round()),this._container.style.transform=`${ds[o]} translate(${r.x}px,${r.y}px)`,_s(this._container,o,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(ys),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._update),this._map.on("mouseup",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.V.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._update),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._update),this._map.on("drag",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=h.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}setPadding(e){this.options.padding=e,this._update();}_createCloseButton(){this.options.closeButton&&(this._closeButton=h.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(ws);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=V,e.ScaleControl=class{constructor(e){this._onMove=()=>{xs(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,xs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},vs),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=h.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=kr,e.Style=Ai,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=h.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=h.create("button","maplibregl-ctrl-terrain",this._container),h.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){this._container.remove(),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=Sr,e.TwoFingersTouchRotateHandler=Mr,e.TwoFingersTouchZoomHandler=Cr,e.TwoFingersTouchZoomRotateHandler=Nr,e.VectorTileSource=G,e.VideoSource=ee,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(oe(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{ie[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=z;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(E),z=null):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()"));},e.createTileMesh=si,e.getMaxParallelImageRequests=function(){return t.c.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return ne().getRTLTextPluginStatus()},e.getVersion=function(){return Ps},e.getWorkerCount=function(){return S.workerCount},e.getWorkerUrl=function(){return t.c.WORKER_URL},e.importScriptInWorkers=function(e){return k().broadcast("IS",e)},e.isTimeFrozen=function(){return l.isFrozen()},e.now=c,e.prewarm=function(){A().acquire(E);},e.restoreNow=function(){l.restoreNow();},e.setMaxParallelImageRequests=function(e){t.c.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setNow=function(e){l.setNow(e);},e.setRTLTextPlugin=function(e,t){return ne().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){S.workerCount=e;},e.setWorkerUrl=function(e){t.c.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/reports/static/report.css b/reports/static/report.css new file mode 100644 index 0000000..3afdcd8 --- /dev/null +++ b/reports/static/report.css @@ -0,0 +1,1444 @@ +@font-face { + font-family: "Bender"; + src: + url("fonts/Bender.woff2") format("woff2"), + url("fonts/Bender.woff") format("woff"); + font-weight: 400; + font-style: normal; +} + +@font-face { + font-family: "Bender"; + src: + url("fonts/Bender-Bold.woff2") format("woff2"), + url("fonts/Bender-Bold.woff") format("woff"); + font-weight: 700; + font-style: normal; +} + +@font-face { + font-family: "Bender"; + src: + url("fonts/Bender-Light.woff2") format("woff2"), + url("fonts/Bender-Light.woff") format("woff"); + font-weight: 300; + font-style: normal; +} + + +/* ============================================================ + Base + ============================================================ */ + +:root { + --bg: #0f141a; + --surface: #171e26; + --surface-light: #1c252f; + --border: #2b3743; + + --text: #e6edf3; + --muted: #8b98a6; + + --green: #45d483; + --yellow: #e5c07b; + --red: #ef6262; + --accent: #69a7ff; + + --terminal: #0a0f14; +} + + +* { + box-sizing: border-box; +} + + +html { + min-height: 100%; +} + + +body { + margin: 0; + padding: 0; + + min-height: 100vh; + + font-family: + "Bender", + Arial, + Helvetica, + sans-serif; + + background: var(--bg); + color: var(--text); +} + + +a { + color: var(--accent); + text-decoration: none; +} + + +a:hover { + color: #9bc4ff; +} + + +/* ============================================================ + Report header + ============================================================ */ + +.report-header { + position: sticky; + top: 0; + + z-index: 1000; + + width: 100%; + + background: rgba(15, 20, 26, 0.96); + + border-bottom: 1px solid var(--border); + + backdrop-filter: blur(12px); +} + + +.report-header-inner { + + width: 100%; + + max-width: 1800px; + + margin: 0 auto; + + min-height: 68px; + + display: flex; + + align-items: center; + + gap: 36px; + + padding: 0 30px; +} + + +.report-brand { + + flex: 0 0 auto; + + display: flex; + flex-direction: column; + + justify-content: center; + + color: var(--text); + + text-decoration: none; + + white-space: nowrap; +} + + +.report-brand-title { + + font-size: 19px; + font-weight: 700; + + letter-spacing: 0.4px; + + line-height: 1.1; +} + + +.report-brand-subtitle { + + margin-top: 3px; + + color: var(--muted); + + font-size: 12px; + font-weight: 400; + + letter-spacing: 0.7px; + + line-height: 1.1; +} + + +.report-brand:hover { + color: var(--text); + + text-decoration: none; +} + + +.report-nav { + display: flex; + align-items: center; + + gap: 6px; + + min-width: 0; + + overflow-x: auto; + + scrollbar-width: thin; +} + + +.report-nav a { + display: inline-flex; + align-items: center; + + min-height: 38px; + + padding: 0 14px; + + border-radius: 7px; + + color: var(--muted); + + font-size: 13px; + font-weight: 700; + + letter-spacing: 0.7px; + + white-space: nowrap; + + transition: + color 0.15s ease, + background 0.15s ease; +} + + +.report-nav a:hover { + color: var(--text); + + background: var(--surface-light); + + text-decoration: none; +} + + +.report-nav a.active { + color: var(--text); + + background: var(--surface-light); + + box-shadow: + inset 0 -2px 0 var(--accent); +} + + +/* ============================================================ + Page layout + ============================================================ */ + +.wrapper { + min-height: calc(100vh - 68px); + + display: block; +} + + +.content { + width: 100%; + + max-width: 1800px; + + margin: 0 auto; + + padding: 30px; +} + + +.page-title { + margin-top: 0; + margin-bottom: 8px; + + font-size: 34px; + font-weight: 700; + + letter-spacing: 0.2px; +} + + +.page-description { + color: var(--muted); + + margin-bottom: 30px; + + font-size: 15px; +} + + +/* ============================================================ + Cards + ============================================================ */ + +.card { + background: var(--surface); + + border: 1px solid var(--border); + + border-radius: 12px; + + padding: 22px; + + margin-bottom: 24px; + + box-shadow: + 0 2px 10px rgba(0, 0, 0, 0.20); +} + + +.card h2 { + margin-top: 0; + margin-bottom: 20px; + + color: var(--text); + + font-size: 21px; +} + + +.card h3 { + margin-top: 0; + + color: var(--text); +} + + +/* ============================================================ + Statistics + ============================================================ */ + +.stats-grid { + display: grid; + + grid-template-columns: + repeat( + auto-fit, + minmax(180px, 1fr) + ); + + gap: 18px; +} + + +.stat-card { + background: var(--surface); + + border: 1px solid var(--border); + + border-radius: 10px; + + padding: 18px; + + text-align: center; +} + + +.stat-value { + margin-bottom: 8px; + + color: var(--accent); + + font-size: 34px; + font-weight: 700; +} + + +.stat-title { + color: var(--muted); + + font-size: 14px; +} + + +/* ============================================================ + Tables + ============================================================ */ + +table { + width: 100%; + + border-collapse: collapse; +} + + +th { + background: var(--surface-light); + + color: var(--text); + + font-weight: 700; + + text-align: left; + + padding: 12px; + + border-bottom: 2px solid var(--border); + + position: sticky; + top: 0; + + z-index: 2; +} + + +td { + padding: 10px 12px; + + border-bottom: 1px solid var(--border); + + vertical-align: top; + + color: var(--text); +} + + +tbody tr:hover { + background: rgba(105, 167, 255, 0.05); +} + + +.table-container { + overflow-x: auto; + overflow-y: auto; + + max-height: 700px; + + border: 1px solid var(--border); + + border-radius: 10px; +} + + +/* ============================================================ + Search + ============================================================ */ + +.search { + width: 100%; + + padding: 12px; + + font-family: + "Bender", + Arial, + Helvetica, + sans-serif; + + font-size: 15px; + + color: var(--text); + + background: var(--terminal); + + border: 1px solid var(--border); + + border-radius: 8px; + + margin-bottom: 18px; +} + + +.search:focus { + outline: none; + + border-color: var(--accent); + + box-shadow: + 0 0 0 2px rgba(105, 167, 255, 0.12); +} + + +/* ============================================================ + Buttons + ============================================================ */ + +.button { + display: inline-block; + + background: var(--accent); + + color: #0f141a; + + padding: 10px 18px; + + border: 2px outset ButtonFace; + + border-radius: 7px; + + font-weight: 700; + + text-decoration: none; + + transition: + background 0.15s ease, + transform 0.15s ease; +} + + +.vendor-actions { + display: flex; + + justify-content: center; + + margin-top: 24px; +} + + +.button:hover { + background: #8abaff; + + color: #0f141a; + + text-decoration: none; +} + +.button:active { + border-style: inset; + + transform: translateY(1px); +} + +/* ============================================================ + Badges + ============================================================ */ + +.badge { + display: inline-block; + + padding: 4px 10px; + + border-radius: 999px; + + font-size: 12px; + font-weight: 700; +} + + +/* ============================================================ + Information block + ============================================================ */ + +.info { + background: var(--surface-light); + + border-left: 4px solid var(--accent); + + padding: 15px; + + border-radius: 7px; + + margin-bottom: 20px; +} + + +code { + background: var(--terminal); + + color: var(--accent); + + padding: 2px 6px; + + border-radius: 5px; +} + + +/* ============================================================ + Dashboard grids + ============================================================ */ + +.report-grid { + display: grid; + + grid-template-columns: + repeat( + auto-fit, + minmax(420px, 1fr) + ); + + gap: 24px; +} + +.vendor-sync { + width: 100%; +} + + +.vendor-sync-empty { + text-align: center; +} + + + +/* ============================================================ + Session map + ============================================================ */ + +#map { + width: 100%; + + height: 700px; + + border-radius: 12px; + + border: 1px solid var(--border); + + margin-bottom: 20px; + + overflow: hidden; +} + + +.map-layer-dot { + display: inline-block; + + width: 14px; + + height: 14px; + + flex: 0 0 14px; + + box-sizing: border-box; + + border: 1px solid #FFFFFF; + + border-radius: 50%; +} + + +.map-layer-dot-gps { + background: #1565C0; +} + + +.map-layer-dot-handshake { + background: #E5C07B; +} + + +.map-layer-dot-password { + background: #E53935; +} + + +.map-layer-dot-all { + background: #43A047; +} + + +.session-map-title { + display: flex; + + align-items: center; + + flex-wrap: wrap; + + gap: 18px; +} + + +.session-map-title-text { + flex: 0 0 auto; +} + + +.session-map-controls { + display: inline-flex; + + align-items: center; + + flex-wrap: wrap; + + gap: 14px; + + font-size: 13px; + + font-weight: normal; +} + + +.session-map-controls label { + display: inline-flex; + + align-items: center; + + gap: 6px; + + color: var(--text); + + cursor: pointer; + + white-space: nowrap; +} + + +.session-map-controls input { + margin: 0; +} + + +/* ============================================================ + Footer + ============================================================ */ + +.footer { + margin-top: 40px; + + padding-bottom: 20px; + + text-align: center; + + color: var(--muted); + + font-size: 14px; +} + + +/* ============================================================ + Responsive + ============================================================ */ + +@media (max-width: 1000px) { + + .report-header-inner { + min-height: auto; + + align-items: flex-start; + + flex-direction: column; + + gap: 8px; + + padding: + 14px 20px; + } + + + .report-nav { + width: 100%; + } + + + .content { + padding: 20px; + } + + + .stats-grid { + grid-template-columns: 1fr; + } + + + .report-grid { + grid-template-columns: 1fr; + } + + + #map { + height: 500px; + } +} + + +@media (max-width: 600px) { + + .report-brand { + font-size: 17px; + } + + + .report-nav { + gap: 2px; + } + + + .report-nav a { + padding: 0 10px; + + font-size: 12px; + } + + + .content { + padding: 15px; + } + + + .page-title { + font-size: 28px; + } + + + .card { + padding: 16px; + } +} + +/* ============================================================ + Search page + ============================================================ */ + +.search-card { + margin-bottom: 24px; +} + + +.search-form { + margin-top: 20px; +} + + +.search-label { + display: block; + + margin-bottom: 8px; + + color: var(--muted); + + font-size: 13px; + + font-weight: 700; + + text-transform: uppercase; +} + + +.search-input-row { + display: flex; + + gap: 12px; + + align-items: stretch; +} + + +.search-input { + flex: 1; + + min-width: 0; + + padding: 12px 14px; + + font-family: + "Bender", + Arial, + Helvetica, + sans-serif; + + font-size: 15px; + + color: var(--text); + + background: var(--terminal); + + border: 1px solid var(--border); + + border-radius: 8px; +} + + +.search-input:focus { + outline: none; + + border-color: var(--accent); + + box-shadow: + 0 0 0 2px rgba(105, 167, 255, 0.12); +} + + +.search-suggestions { + margin-top: 22px; +} + + +.search-suggestions-title { + margin-bottom: 10px; + + color: var(--muted); + + font-size: 13px; + + font-weight: 700; + + text-transform: uppercase; +} + + +.search-vendor-suggestions { + display: grid; + + grid-template-columns: + repeat( + auto-fit, + minmax(280px, 1fr) + ); + + gap: 5px 24px; + + padding: 4px 0; +} + + +.search-vendor-item { + display: flex; + + align-items: baseline; + + justify-content: space-between; + + gap: 16px; + + padding: 4px 0; + + color: var(--text); + + border-bottom: + 1px solid + rgba(43, 55, 67, 0.45); + + font-size: 13px; +} + + +.search-vendor-name { + min-width: 0; + + overflow-wrap: anywhere; + + user-select: text; + + cursor: text; +} + + +.search-vendor-count { + flex: 0 0 auto; + + color: var(--muted); + + font-size: 11px; + + user-select: text; +} + + +.search-future { + opacity: 0.78; +} + + +.search-future-content { + margin-top: 12px; + + padding: 14px; + + color: var(--muted); + + background: var(--terminal); + + border: 1px dashed var(--border); + + border-radius: 8px; +} + + +.search-results { + min-height: 300px; +} + + +.search-results-header { + display: flex; + + align-items: center; + + justify-content: space-between; + + gap: 20px; + + margin-bottom: 18px; +} + + +.search-results-header h2 { + margin-bottom: 5px; +} + + +.search-status { + color: var(--muted); + + font-size: 13px; +} + +.search-query { + margin-bottom: 5px; + + color: var(--text); + + font-size: 13px; + + font-weight: 700; +} + + +.search-matched-vendors { + margin-bottom: 18px; + + padding: 12px 14px; + + background: var(--terminal); + + border: + 1px solid + var(--border); + + border-radius: 8px; +} + + +.search-matched-vendors-title { + margin-bottom: 8px; + + color: var(--muted); + + font-size: 12px; + + font-weight: 700; + + text-transform: uppercase; +} + + +.search-matched-vendors-list { + display: grid; + + gap: 4px; +} + + +.search-matched-vendor { + display: flex; + + align-items: baseline; + + justify-content: space-between; + + gap: 20px; + + padding: 3px 0; + + color: var(--text); + + font-size: 13px; +} + + +.search-matched-vendor span:first-child { + min-width: 0; + + overflow-wrap: anywhere; +} + + +.search-matched-vendor span:last-child { + flex: 0 0 auto; + + color: var(--muted); + + font-size: 11px; +} + +.search-export { + white-space: nowrap; +} + + +.search-map-controls { + display: flex; + + flex-wrap: wrap; + + gap: 14px; + + margin-bottom: 14px; + + padding: 10px 12px; + + background: var(--surface-light); + + border: 1px solid var(--border); + + border-radius: 8px; +} + + +.search-map-controls label { + display: inline-flex; + + align-items: center; + + gap: 6px; + + color: var(--text); + + font-size: 13px; + + cursor: pointer; +} + + +.search-map-controls input { + margin: 0; +} + +.search-map-controls .map-layer-dot-password { + background: #E53935; +} + + +.search-map-controls .map-layer-dot-handshake { + background: #e5c07b; +} + + +.search-map-controls .map-layer-dot-other { + background: #69a7ff; +} + +.search-map { + width: 100%; + + height: 700px; + + border: 1px solid var(--border); + + border-radius: 12px; + + overflow: hidden; +} + + +.search-map-empty { + padding: 60px 20px; + + color: var(--muted); + + text-align: center; + + background: var(--terminal); + + border: 1px dashed var(--border); + + border-radius: 10px; +} + + +/* ============================================================ + Search map popups + ============================================================ */ + +.search-popup { + min-width: 260px; + + max-width: 380px; + + color: #e6edf3; + + font-family: + "Bender", + Arial, + Helvetica, + sans-serif; + + font-size: 13px; + + line-height: 1.45; +} + + +.search-popup-title { + margin-bottom: 8px; + + color: #ffffff; + + font-size: 16px; + + font-weight: 700; +} + + +.search-popup-line { + margin: 3px 0; +} + + +.search-popup-category { + display: inline-block; + + margin: 10px 0; + + padding: 5px 9px; + + border-radius: 5px; + + font-size: 12px; + + font-weight: 700; + + letter-spacing: 0.04em; +} + + +.search-popup-category.password { + background: rgba(69, 212, 131, 0.16); + + color: #45d483; +} + + +.search-popup-category.handshake { + background: rgba(229, 192, 123, 0.16); + + color: #e5c07b; +} + + +.search-popup-category.other { + background: rgba(105, 167, 255, 0.16); + + color: #69a7ff; +} + + +.search-popup-section { + margin-top: 9px; + + padding-top: 8px; + + border-top: 1px solid rgba(43, 55, 67, 0.8); +} + + +.search-popup-password-item { + margin-bottom: 8px; +} + + +.search-popup-password { + padding: 8px 10px; + + color: #ffffff; + + background: #0a0f14; + + border: 1px solid #2b3743; + + border-radius: 6px; + + font-family: monospace; + + font-size: 14px; + + word-break: break-word; +} + + +.search-popup-meta { + margin-top: 3px; + + color: #8b98a6; + + font-size: 11px; +} + + +.search-popup-list { + margin-top: 4px; + + color: #c5ced7; + + font-size: 12px; +} + + +.search-popup-muted { + color: #8b98a6; +} + + +@media (max-width: 700px) { + + .search-input-row { + flex-direction: column; + } + + + .search-results-header { + align-items: flex-start; + + flex-direction: column; + } + + + .search-export { + width: 100%; + } + + + .search-map { + height: 500px; + } + +} + +/* ============================================================ + MapLibre popups + ============================================================ */ + +body .maplibregl-popup-content { + padding: 12px 14px; + + color: var(--text); + + background: var(--surface); + + border: 1px solid var(--border); + + border-radius: 8px; + + box-shadow: + 0 8px 24px rgba(0, 0, 0, 0.35); +} + + +/* Popup arrow */ + +body .maplibregl-popup-anchor-top +.maplibregl-popup-tip { + border-bottom-color: var(--surface); +} + +body .maplibregl-popup-anchor-top-left +.maplibregl-popup-tip { + border-bottom-color: var(--surface); +} + +body .maplibregl-popup-anchor-top-right +.maplibregl-popup-tip { + border-bottom-color: var(--surface); +} + +body .maplibregl-popup-anchor-bottom +.maplibregl-popup-tip { + border-top-color: var(--surface); +} + +body .maplibregl-popup-anchor-bottom-left +.maplibregl-popup-tip { + border-top-color: var(--surface); +} + +body .maplibregl-popup-anchor-bottom-right +.maplibregl-popup-tip { + border-top-color: var(--surface); +} + +body .maplibregl-popup-anchor-left +.maplibregl-popup-tip { + border-right-color: var(--surface); +} + +body .maplibregl-popup-anchor-right +.maplibregl-popup-tip { + border-left-color: var(--surface); +} + + +/* Popup close button */ + +body .maplibregl-popup-close-button { + color: #ffffff; +} + +body .maplibregl-popup-close-button:hover { + color: #ffffff; + background: rgba(255, 255, 255, 0.08); +} + +.hashcat-card { + margin-bottom: 24px; +} + +.hashcat-command, +.hashcat-format { + margin: 16px 0; + padding: 16px; + overflow-x: auto; + border-radius: 6px; + font-family: monospace; +} + +.hashcat-file-row { + display: flex; + align-items: center; + gap: 16px; + margin-top: 20px; +} + +.hashcat-file-row input[type="file"] { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +.wifitrip-file-row { + display: flex; + align-items: center; + gap: 16px; + margin-top: 20px; +} + +.wifitrip-file-row input[type="file"] { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +.wifitrip-file-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.hashcat-file-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.hashcat-preflight { + margin-top: 20px; +} + +.hashcat-preflight .stats-grid { + margin-top: 20px; +} diff --git a/reports/statistics.py b/reports/statistics.py new file mode 100644 index 0000000..26e8637 --- /dev/null +++ b/reports/statistics.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Статистика базы данных WiFi GPS Mapper. + +Этот модуль ничего не рисует. + +Он только собирает информацию из SQLite и +возвращает обычные словари Python. + +Отображением занимается dashboard.py. +""" + +from pathlib import Path + +from .config import ( + DATABASE_FILE, + CAPTURES_DIR, +) + +from .database import ( + query_value, + query_one, +) + +from .utils import ( + format_size, +) + + +# ============================================================ +# Размер базы +# ============================================================ + +def database_size(): + + if not DATABASE_FILE.exists(): + + return 0 + + return DATABASE_FILE.stat().st_size + + +# ============================================================ +# Размер каталога +# ============================================================ + +def directory_size(path): + + path = Path(path) + + if not path.exists(): + + return 0 + + total = 0 + + for file in path.rglob("*"): + + if file.is_file(): + + total += file.stat().st_size + + return total + + +# ============================================================ +# Количество файлов +# ============================================================ + +def count_files(path): + + path = Path(path) + + if not path.exists(): + + return 0 + + total = 0 + + for file in path.rglob("*"): + + if file.is_file(): + + total += 1 + + return total + + +# ============================================================ +# Общая статистика +# ============================================================ + +def database_statistics(conn): + + statistics = {} + + statistics["access_points"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM access_points + """, + default=0 + ) + + statistics["access_points_without_coordinates"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM access_points + WHERE + last_latitude IS NULL + OR last_longitude IS NULL + """, + default=0 + ) + + statistics["vendors"] = query_value( + conn, + """ + SELECT COUNT(DISTINCT vendor) + FROM access_points + WHERE vendor IS NOT NULL + AND vendor!='' + """, + default=0 + ) + + statistics["sessions"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM capture_sessions + """, + default=0 + ) + + statistics["handshakes"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM handshakes + """, + default=0 + ) + + statistics["credentials"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM credentials + """, + default=0 + ) + + statistics["pmkid"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM access_points + WHERE has_pmkid=1 + """, + default=0 + ) + + statistics["cracked"] = query_value( + conn, + """ + SELECT COUNT(*) + FROM access_points + WHERE is_cracked=1 + """, + default=0 + ) + + statistics["capture_files"] = count_files( + CAPTURES_DIR + ) + + statistics["database_size"] = format_size( + database_size() + ) + + statistics["captures_size"] = format_size( + directory_size( + CAPTURES_DIR + ) + ) + + row = query_one( + conn, + """ + SELECT + + MIN(first_seen), + + MAX(last_seen) + + FROM access_points + """ + ) + + if row: + + statistics["first_seen"] = row[0] + + statistics["last_seen"] = row[1] + + else: + + statistics["first_seen"] = None + + statistics["last_seen"] = None + + return statistics + + +# ============================================================ +# Статистика производителей +# ============================================================ + +def top_vendors( + conn, + limit=20 +): + + sql = """ + SELECT + + vendor, + + COUNT(*) AS devices + + FROM access_points + + WHERE vendor IS NOT NULL + AND vendor!='' + + GROUP BY vendor + + ORDER BY devices DESC + + LIMIT ? + """ + + return conn.execute( + sql, + ( + limit, + ) + ).fetchall() + + +# ============================================================ +# Используемые каналы +# ============================================================ + +def channel_statistics(conn): + + sql = """ + SELECT + + channel, + + COUNT(*) AS total + + FROM access_points + + GROUP BY channel + + ORDER BY channel + """ + + return conn.execute(sql).fetchall() + + +# ============================================================ +# Типы шифрования +# ============================================================ + +def encryption_statistics(conn): + + sql = """ + SELECT + + encryption, + + COUNT(*) AS total + + FROM access_points + + GROUP BY encryption + + ORDER BY total DESC + """ + + return conn.execute(sql).fetchall() + + +# ============================================================ +# Самые часто встречающиеся ESSID +# ============================================================ + +def top_essid( + conn, + limit=25 +): + + sql = """ + SELECT + + essid, + + COUNT(*) AS total + + FROM access_points + + WHERE essid IS NOT NULL + AND essid!='' + + GROUP BY essid + + ORDER BY total DESC + + LIMIT ? + """ + + return conn.execute( + sql, + ( + limit, + ) + ).fetchall() + + +# ============================================================ +# Самые сильные сигналы +# ============================================================ + +def strongest_access_points( + conn, + limit=20 +): + + sql = """ + SELECT + + bssid, + + essid, + + vendor, + + last_rssi + + FROM access_points + + ORDER BY last_rssi DESC + + LIMIT ? + """ + + return conn.execute( + sql, + ( + limit, + ) + ).fetchall() \ No newline at end of file diff --git a/reports/template.py b/reports/template.py new file mode 100644 index 0000000..5bd7ca1 --- /dev/null +++ b/reports/template.py @@ -0,0 +1,690 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +HTML шаблон WiFi GPS Mapper Report. + +Все страницы используют единый шаблон. + +В дальнейшем здесь будет располагаться: + + • CSS + • JavaScript + • Навигация + • Каркас страниц + • Footer +""" + +from datetime import datetime, timezone + +from reports.utils import ( + format_datetime as format_report_datetime, +) + + +# ============================================================ +# Report context +# ============================================================ + +class ReportContext: + + def __init__( + self, + mode="static", + page="root", + ): + + if mode not in ( + "static", + "server", + ): + raise ValueError( + f"Unknown report mode: {mode}" + ) + + if page not in ( + "root", + "session", + "trips", + ): + raise ValueError( + f"Unknown report page: {page}" + ) + + self.mode = mode + self.page = page + + def session_page(self): + + return ReportContext( + mode=self.mode, + page="session", + ) + + def home_url(self): + + if self.mode == "server": + return "/" + + if self.page == "session": + return "../index.html" + + return "index.html" + + + def dashboard_url(self): + + if self.mode == "server": + return "/reports/" + + if self.page == "session": + return "../index.html" + + return "index.html" + + def capture_sessions_url(self): + + if self.mode == "server": + return "/reports/sessions/" + + if self.page == "session": + return "../capture_sessions.html" + + return "capture_sessions.html" + + def trips_url( + self, + ): + + if self.mode == "server": + return "/reports/trips/" + + return "index.html" + + def search_url( + self, + ): + if self.mode == "server": + return "/reports/search/" + + return "index.html" + + + def session_url( + self, + session_id, + ): + + if self.mode == "server": + return ( + f"/reports/session/{session_id}" + ) + + return ( + f"sessions/{session_id}.html" + ) + + def asset_url( + self, + path, + ): + + path = str(path).lstrip("/") + + if self.mode == "server": + return ( + f"/reports/static/{path}" + ) + + if self.page == "session": + return ( + f"../static/{path}" + ) + + return ( + f"static/{path}" + ) + +# ============================================================ +# HTML Header +# ============================================================ + +def html_header( + context=None, +): + + if context is None: + context = ReportContext() + + return f""" + + + + + + + + + +WiFi GPS Mapper Report + + + + + + + + +""" + +HTML_END = """ + + + + + +""" + +# ============================================================ +# Navigation +# ============================================================ + +def navigation( + active="dashboard", + context=None, +): + + if context is None: + context = ReportContext() + + menu = [ + + ( + "dashboard", + "Dashboard", + context.dashboard_url(), + ), + + ( + "capture_sessions", + "Capture Sessions", + context.capture_sessions_url(), + ), + + ] + + if context.mode == "server": + + menu.append( + ( + "trips", + "Trips", + context.trips_url(), + ) + ) + + if context.mode == "server": + + menu.extend( + [ + ( + "access_points", + "Access Points", + "/reports/access-points/", + ), + + ( + "vendors", + "Vendors", + "/reports/vendors/", + ), + + ( + "hashcat", + "Hashes", + "/reports/hashcat/", + ), + + ] + ) + + menu.append( + ( + "search", + "Search", + context.search_url(), + ) + ) + + html = """ +
+ +
+ + + + WiFi GPS Mapper + + + + Wireless network scanner + + + + + +
+ +
+""" + + return html + + +# ============================================================ +# Page begin +# ============================================================ + +def page_begin( + + title, + + description="", + + active="dashboard", + + context=None, + +): + + if context is None: + context = ReportContext() + + html = html_header( + context + ) + + html += """ + +
+ +""" + + html += navigation( + active, + context, + ) + + html += f""" + +
+ +

+ +{title} + +

+ +""" + + if description: + + html += f""" + +
+ +{description} + +
+ +""" + + return html + +# ============================================================ +# Page header +# ============================================================ + +def page_header( + + title, + + description="", + +): + + html = f""" + +

+ +{title} + +

+ +""" + + if description: + + html += f""" + +
+ +{description} + +
+ +""" + + return html + +# ============================================================ +# Page end +# ============================================================ + +def page_end(): + generated = format_report_datetime( + datetime.now( + timezone.utc + ).isoformat() + ) + + + + return f""" + + + +
+ +
+ +{HTML_END} + +""" + + + +# ============================================================ +# Card +# ============================================================ + +def card( + + title, + + body + +): + + return f""" + +
+ +

+ +{title} + +

+ +{body} + +
+ +""" + + + +# ============================================================ +# Info +# ============================================================ + +def info(text): + + return f""" + +
+ +{text} + +
+ +""" + + + +# ============================================================ +# Badge +# ============================================================ + +def badge( + + text, + + color="gray" + +): + + return f""" + + + +{text} + + + +""" + + + +# ============================================================ +# Button +# ============================================================ + +def button( + + title, + + url + +): + + return f""" + + + +{title} + + + +""" + + +# ============================================================ +# Statistics card +# ============================================================ + +def stat( + + value, + + title + +): + + return f""" + +
+ +
+ +{value} + +
+ +
+ +{title} + +
+ +
+ +""" + + + +# ============================================================ +# Statistics grid +# ============================================================ + +def stats_grid(items): + + html = """ + +
+ +""" + + + + html += "".join(items) + + + + html += """ + +
+ +""" + + + + return html + + +# ============================================================ +# Search field +# ============================================================ + +def search_box( + + table_id, + + placeholder="Search..." + +): + + return f""" + + + +""" + + + +# ============================================================ +# Table container +# ============================================================ + +def table_container(content): + + return f""" + +
+ +{content} + +
+ +""" + + +# ============================================================ +# Horizontal separator +# ============================================================ + +def hr(): + + return "
" diff --git a/reports/trips_page.py b/reports/trips_page.py new file mode 100644 index 0000000..7a7e9c4 --- /dev/null +++ b/reports/trips_page.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Server-side Trips report page for .wifitrip import/export. +""" + +from html import escape + +from reports.template import ( + ReportContext, + page_begin, + page_end, +) + + +def _stat_card(label, value): + return f""" +
+ +
+{escape(str(label))} +
+ +
+{escape(str(value))} +
+ +
+""" + + +def _message(message): + if not message: + return "" + + message_type = escape( + str(message.get("type", "info")) + ) + + message_text = escape( + str(message.get("text", "")) + ) + + return f""" +
+ +
+{message_text} +
+ +
+""" + + +def _import_result(result): + if not result: + return "" + + html = """ +
+ +

Import result

+ +
+""" + + html += _stat_card( + "Sessions in file", + result.get("sessions", 0), + ) + + html += _stat_card( + "Imported", + result.get("imported", 0), + ) + + html += _stat_card( + "Duplicates", + result.get("duplicates", 0), + ) + + html += _stat_card( + "Failed", + result.get("failed", 0), + ) + + html += """ +
+""" + + failed_sessions = result.get( + "failed_sessions", + [], + ) + + if failed_sessions: + + html += """ +

Failed sessions

+ +
+ + + + + + + + + + + +""" + + for item in failed_sessions: + + html += f""" + + + + + + + +""" + + html += """ + + +
Session hashError
+ +{escape(str(item.get("session_hash", "")))} + + +{escape(str(item.get("error", "")))} +
+ +
+""" + + html += """ +
+""" + + return html + + +def _validation_result(validation): + if not validation: + return "" + + if not validation.get("valid"): + + return f""" +
+ +

Package validation

+ +
+{escape( + str( + validation.get( + "error", + "Package is invalid." + ) + ) +)} +
+ +
+""" + + return f""" +
+ +

Package validation

+ +
+Package is valid and contains +{escape(str(validation.get("sessions", 0)))} +session(s). +
+ +
+ +{_stat_card( + "Sessions", + validation.get("sessions", 0) +)} + +{_stat_card( + "Access points", + validation.get("access_points", 0) +)} + +{_stat_card( + "GPS points", + validation.get("gps_points", 0) +)} + +{_stat_card( + "Observations", + validation.get("observations", 0) +)} + +{_stat_card( + "Handshakes", + validation.get("handshakes", 0) +)} + +{_stat_card( + "Handshake Cracked", + validation.get("credentials", 0) +)} + +
+ +
+""" + + +def render_trips_page( + conn, + context=None, + message=None, + import_result=None, + validation=None, +): + if context is None: + + context = ReportContext( + mode="server", + page="trips", + ) + + session_count = conn.execute( + """ + SELECT COUNT(*) AS count + FROM capture_sessions + """ + ).fetchone()["count"] + + html = page_begin( + "Trips", + ( + "Export and import capture sessions " + "as .wifitrip packages." + ), + "trips", + context, + ) + + html += _message( + message + ) + + html += """ +
+ +

Export capture sessions

+ +

+Export all capture sessions into one +.wifitrip package. +

+ +

+The package contains logical session data: +GPS track, access-point observations, +handshakes and credentials. Physical capture +files are not included. +

+ +
+""" + + html += _stat_card( + "Sessions available", + session_count, + ) + + html += """ +
+ +
+ + + +
+ +
+""" + + html += """ +
+ +

Import capture sessions

+ +

+Import one .wifitrip package. +The complete package is validated before +any database changes are made. +

+ +
+ + + +
+ + + + + + + Файл не выбран + + +
+ +
+ + + +
+ +
+ + + +
+""" + + html += _validation_result( + validation + ) + + html += _import_result( + import_result + ) + + html += page_end() + + return html diff --git a/reports/utils.py b/reports/utils.py new file mode 100644 index 0000000..ac25443 --- /dev/null +++ b/reports/utils.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Общие вспомогательные функции HTML Report. + +В этом модуле не должно быть SQL-запросов. + +Только: + + • форматирование + • HTML escaping + • работа с файлами + • чтение CSV + • чтение gps_track.nmea + • вычисления +""" + +from __future__ import annotations + +import csv +import html +import os + +from datetime import datetime, timezone +from pathlib import Path +from zoneinfo import ZoneInfo + +from .config import TIMEZONE + + +# ============================================================ +# HTML +# ============================================================ + + +def esc(value) -> str: + """ + Безопасный вывод значения в HTML. + """ + + if value is None: + return "" + + return html.escape(str(value)) + + +# ============================================================ +# Значение по умолчанию +# ============================================================ + + +def safe(value, default="-"): + + if value is None: + return default + + if value == "": + return default + + return value + + +# ============================================================ +# Размер файла +# ============================================================ + + +def format_size(size): + + if size is None: + return "-" + + size = float(size) + + units = [ + "B", + "KB", + "MB", + "GB", + "TB" + ] + + for unit in units: + + if size < 1024: + + return f"{size:.1f} {unit}" + + size /= 1024 + + return f"{size:.1f} PB" + + +def file_size(path): + + path = Path(path) + + if not path.exists(): + + return "-" + + return format_size( + path.stat().st_size + ) + + +# ============================================================ +# Дата / время +# ============================================================ + + +def parse_datetime(text): + if not text: + return None + + try: + dt = datetime.fromisoformat(text) + + # + # Старые записи проекта хранят UTC + # как naive datetime. + # + if dt.tzinfo is None: + dt = dt.replace( + tzinfo=timezone.utc + ) + + return dt + + except Exception: + return None + + +def format_datetime( + text, + output_format="%d.%m.%Y %H:%M:%S" +): + dt = parse_datetime(text) + + if dt is None: + return safe(text) + + display_timezone = ZoneInfo(TIMEZONE) + + return dt.astimezone( + display_timezone + ).strftime( + output_format + ) + + +def format_duration(start, end): + + start = parse_datetime(start) + + end = parse_datetime(end) + + if start is None: + + return "-" + + if end is None: + + return "-" + + delta = end - start + + seconds = int( + delta.total_seconds() + ) + + hours = seconds // 3600 + + minutes = ( + seconds % 3600 + ) // 60 + + seconds = seconds % 60 + + return ( + f"{hours:02}:{minutes:02}:{seconds:02}" + ) + + +# Совместимость со старым кодом +duration = format_duration + +# ============================================================ +# CSV +# ============================================================ + + +def read_csv(filename): + + filename = Path(filename) + + if not filename.exists(): + + return [] + + with open( + filename, + newline="", + encoding="utf-8", + errors="ignore" + ) as f: + + reader = csv.DictReader(f) + + return list(reader) + + +# ============================================================ +# Текстовый файл +# ============================================================ + + +def read_lines(filename): + + filename = Path(filename) + + if not filename.exists(): + + return [] + + with open( + filename, + encoding="utf-8", + errors="ignore" + ) as f: + + return [ + line.rstrip() + for line in f + ] + + +# ============================================================ +# gps_track.nmea +# ============================================================ + + +def read_nmea(filename): + + """ + Читает gps_track.nmea. + + Формат строки: + + 2026-07-16T12:47:51.938726;$GPRMC,... + + Возвращает: + + [ + ( + datetime, + "$GPRMC,..." + ), + ... + ] + """ + + result = [] + + filename = Path(filename) + + if not filename.exists(): + + return result + + with open( + filename, + encoding="utf-8", + errors="ignore" + ) as f: + + for line in f: + + line = line.strip() + + if not line: + + continue + + if ";" not in line: + + continue + + timestamp, sentence = line.split( + ";", + 1 + ) + + dt = parse_datetime( + timestamp + ) + + if dt is None: + + continue + + result.append( + ( + dt, + sentence + ) + ) + + return result + + +# ============================================================ +# Каталог +# ============================================================ + + +def list_directories(path): + + path = Path(path) + + if not path.exists(): + + return [] + + return sorted( + + [ + item + + for item in path.iterdir() + + if item.is_dir() + ] + + ) + + +# ============================================================ +# Список файлов +# ============================================================ + + +def list_files(path): + + path = Path(path) + + if not path.exists(): + + return [] + + return sorted( + + [ + item + + for item in path.iterdir() + + if item.is_file() + ] + + ) + + +# ============================================================ +# Проверка существования +# ============================================================ + + +def exists(path): + + return Path(path).exists() + + +# ============================================================ +# Имя файла +# ============================================================ + + +def filename(path): + + return Path(path).name + + +# ============================================================ +# Имя каталога +# ============================================================ + + +def dirname(path): + + return Path(path).parent.name + + +# ============================================================ +# Последнее изменение +# ============================================================ + + +def modified(path): + path = Path(path) + + if not path.exists(): + return "-" + + display_timezone = ZoneInfo(TIMEZONE) + + return datetime.fromtimestamp( + path.stat().st_mtime, + timezone.utc, + ).astimezone( + display_timezone + ).strftime( + "%d.%m.%Y %H:%M:%S" + ) + + +# ============================================================ +# Количество строк файла +# ============================================================ + + +def line_count(filename): + + filename = Path(filename) + + if not filename.exists(): + + return 0 + + with open( + filename, + encoding="utf-8", + errors="ignore" + ) as f: + + return sum( + 1 + for _ in f + ) \ No newline at end of file diff --git a/reports/vendors.py b/reports/vendors.py new file mode 100644 index 0000000..6e65475 --- /dev/null +++ b/reports/vendors.py @@ -0,0 +1,900 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Vendors report page. + +Страница управления базой OUI. + +Бизнес-логика находится в VendorService. +Этот модуль отвечает только за HTML-представление. +""" + +from html import escape + +from .statistics import ( + top_vendors, +) + +from .utils import ( + format_datetime as format_report_datetime, +) + +from .template import ( + page_begin, + page_end, + card, +) + + +# ============================================================ +# Helpers +# ============================================================ + +def format_size(size): + if not size: + return "-" + + size = float(size) + + units = ( + "B", + "KB", + "MB", + "GB", + ) + + for unit in units: + + if size < 1024: + return f"{size:.1f} {unit}" + + size /= 1024 + + return f"{size:.1f} TB" + + +def format_value(value): + if value is None or value == "": + return "-" + + return escape( + str(value) + ) + + +# ============================================================ +# Database status +# ============================================================ + +def database_status_block(status): + if not status["exists"]: + health = "Not found" + + elif status["healthy"]: + health = "Healthy" + + else: + health = "Error" + + html = f""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValue
Database{format_value(status["database"])}
Status{health}
Total entries{status["total"]}
MA-L{status["ma_l"]}
MA-M{status["ma_m"]}
MA-S{status["ma_s"]}
Schema version{format_value(status["schema_version"])}
Last import{format_report_datetime(status["last_import"])}
Import status{format_value(status["import_status"])}
Size{format_size(status["size"])}
+""" + + return card( + "🏭 OUI Database", + html, + ) + + +# ============================================================ +# Top Vendors +# ============================================================ + +def top_vendors_block(conn): + rows = top_vendors( + conn, + limit=15 + ) + + html = """ + + + + + + + +""" + + if not rows: + + html += """ + + + + +""" + + else: + + for vendor, total in rows: + + if not vendor: + vendor = "-" + + html += f""" + + + + + +""" + + html += """ +
VendorDevices
No vendor data.
{escape(str(vendor))}{total}
+""" + + return card( + "🏭 Top Vendors", + html, + ) + + +# ============================================================ +# Vendors page +# ============================================================ + +def update_block( + service, + preview=None, + token=None, + job=None +): + html = """ +""" + + sources = service.sources + mirrors = service.mirrors + + source_html = """ + + + + + + + + +""" + + for name, url in sources.items(): + + mirror = mirrors.get( + name + ) + + source_html += f""" + + + + + + +""" + + source_html += """ +
SourceURLMirror
{escape(str(name))}{escape(str(url))}{escape(str(mirror)) if mirror else "—"}
+ +""" + + html += """ +
+ +""" + + html += card( + "🌐 Configured Sources", + source_html, + ) + + if preview is None: + + if job is not None: + + stage_labels = { + "starting": + "Запуск обновления", + "downloading": + "Загрузка источника", + "validating": + "Проверка источника", + "fallback": + "Переход на резервное зеркало", + "building": + "Построение базы OUI", + "analyzing": + "Анализ изменений", + "ready": + "Обновление готово", + "error": + "Ошибка обновления" + } + + stage = job.get( + "stage" + ) + + stage_label = stage_labels.get( + stage, + stage or "Неизвестный этап" + ) + + source = job.get( + "source" + ) + + message = job.get( + "message" + ) + + error = job.get( + "error" + ) + + html += f""" +
+ +

Обновление базы OUI

+ +

+Этап: + +{escape(stage_label)} + +

+ +

+Источник: + +{escape(str(source)) if source else "—"} + +

+ +

+ +{escape(str(message)) if message else ""} + +

+ +

+{escape(str(error)) if error else ""} +

+ + + +""" + + if job.get( + "status" + ) == "running": + + html += """ +

+Обновление выполняется. Страница автоматически +обновит результат после завершения. +

+""" + + elif job.get( + "status" + ) == "error": + + html += """ +
+ +
+ + + +
+ +
+ +""" + + html += """ +
+ +""" + + else: + + html += """ +
+ +

Обновление базы OUI

+ +
+ +
+ + + +
+ +
+ +
+ +""" + + html += """ +
+ +""" + + return html + + oui = preview["oui"] + build = preview["build"] + ap = preview["ap"] + + ap_total = ( + ap["unknown_to_vendor"] + + ap["vendor_to_vendor"] + + ap["vendor_to_unknown"] + ) + + if oui["identical"]: + + status_html = """ +

+База OUI не изменилась. Обновление не требуется. +

+""" + + elif ap_total == 0: + + status_html = """ +

+База OUI содержит изменения, но существующие записи +AP не требуют изменения vendor. +

+ +

+Обновление базы OUI можно применить отдельно. +Оно обновит справочник для будущих определений vendor. +

+""" + + else: + + status_html = """ +

+База OUI содержит изменения. +Сначала проверьте изменения в справочнике, затем при +необходимости выберите синхронизацию vendor у существующих AP. +

+""" + + change_html = f""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ПараметрЗначение
Текущих записей{oui["current"]}
Записей в новой базе{oui["candidate"]}
Добавлено{oui["added"]}
Изменено{oui["changed"]}
Удалено{oui["removed"]}
Без изменений{oui["unchanged"]}
Импортировано{build["imported"]}
Пропущено{build["skipped"]}
+ +""" + + html += card( + "🔄 Предварительный просмотр обновления", + status_html + change_html, + ) + + html += """ + + +""" + + if oui["identical"]: + + pass + + else: + + html += f""" +
+ + + +""" + + if ap_total > 0: + + html += """ +
+ +
+ +

+Синхронизация существующих AP +

+ +

+Следующие параметры не изменяют саму базу OUI. +Они определяют, какие изменения vendor применить +к уже существующим записям WiFi AP. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Изменение vendorКоличествоПрименить
+Unknown → Vendor + +
+Что это означает? +

+Заполнить поле vendor у существующих AP, для которых +vendor сейчас неизвестен. Новое значение определяется +по обновлённой базе OUI. +

+
+ +
""" + str(ap["unknown_to_vendor"]) + """ + +
+Vendor → другой Vendor + +
+Что это означает? +

+Заменить текущее значение vendor, если обновлённая +база OUI определяет тот же AP как принадлежащий +другому vendor. +

+
+ +
""" + str(ap["vendor_to_vendor"]) + """ + +
+Vendor → Unknown + +
+Что это означает? +

+Удалить текущее значение vendor, если обновлённая +база OUI больше не позволяет определить vendor +для данного AP. +

+
+ +
""" + str(ap["vendor_to_unknown"]) + """ + +
+ +

+Выбрано изменений AP: +""" + str( + ap["unknown_to_vendor"] +) + """ +

+ +

+Синхронизация AP необязательна. Снятые категории +не будут изменять существующие записи AP. +

+ +
+ +""" + + else: + + html += """ +
+ +
+ +

+Синхронизация существующих AP +

+ +

+Существующие записи AP не требуют изменения vendor. +Для этого обновления синхронизация AP недоступна. +

+ +
+ +""" + + html += """ +
+ + + +
+ +
+ +""" + + if ap_total > 0: + + html += f""" + + +""" + + return html + + +def render_vendors_page( + conn, + service, + preview=None, + token=None, + message=None, + context=None, + job=None +): + status = service.status() + + html = page_begin( + title="Vendors", + description=( + "Vendor database and OUI management" + ), + active="vendors", + context=context, + ) + + if message: + + html += f""" +
+ +

+{escape(message["text"])} +

+ +
+ +""" + + html += """ +
+ +""" + + html += database_status_block( + status + ) + + html += top_vendors_block( + conn + ) + + html += """ +
+ +""" + + html += update_block( + service, + preview, + token, + job + ) + + html += page_end() + + return html \ No newline at end of file diff --git a/reports/wifitrip.py b/reports/wifitrip.py new file mode 100644 index 0000000..938a6ae --- /dev/null +++ b/reports/wifitrip.py @@ -0,0 +1,2111 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Общий сервис импорта и экспорта capture sessions в формате .wifitrip. + +Модуль не зависит от Flask и scanner. +CLI и Web UI используют один и тот же сервисный код. +""" + +import hashlib +import json +import logging +import os +import re +import tempfile +import time +import zipfile +from datetime import datetime, timezone +from pathlib import Path + + +logger = logging.getLogger(__name__) + + +WIFITRIP_FORMAT = "wifitrip" +WIFITRIP_VERSION = 1 +SESSION_HASH_VERSION = 1 + +REQUIRED_FILES = ( + "manifest.json", + "sessions.json", + "gps_tracks.json", + "access_points.json", + "observations.json", + "handshakes.json", + "credentials.json", +) + +SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + + +class WifitripError(ValueError): + """Ошибка формата или обработки .wifitrip.""" + + +def _json_bytes(value): + return json.dumps( + value, + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + + +def _json_loads(data, filename): + try: + return json.loads( + data.decode("utf-8"), + parse_constant=_reject_non_finite, + ) + except UnicodeDecodeError as exc: + raise WifitripError( + f"{filename} must be valid UTF-8." + ) from exc + except json.JSONDecodeError as exc: + raise WifitripError( + f"{filename} contains invalid JSON: {exc}" + ) from exc + + +def _reject_non_finite(value): + raise ValueError( + f"non-finite JSON number is not allowed: {value}" + ) + + +def _require_dict(value, name): + if not isinstance(value, dict): + raise WifitripError( + f"{name} must contain a JSON object." + ) + + +def _require_list(value, name): + if not isinstance(value, list): + raise WifitripError( + f"{name} must contain a JSON array." + ) + + +def _require_string(value, field, allow_none=False): + if value is None and allow_none: + return + + if not isinstance(value, str): + raise WifitripError( + f"{field} must be a string." + ) + + +def _require_number(value, field, allow_none=True): + if value is None and allow_none: + return + + if not isinstance(value, (int, float)) or isinstance(value, bool): + raise WifitripError( + f"{field} must be a number or null." + ) + + +def _require_integer(value, field, allow_none=False): + if value is None and allow_none: + return + + if not isinstance(value, int) or isinstance(value, bool): + raise WifitripError( + f"{field} must be an integer." + ) + + +def _require_bssid(value, field): + _require_string(value, field) + + if not value.strip(): + raise WifitripError( + f"{field} must not be empty." + ) + + +def _validate_hash(value, field): + _require_string(value, field) + + if not SHA256_RE.fullmatch(value): + raise WifitripError( + f"{field} must be a 64-character lowercase SHA-256 hash." + ) + + +def _read_package(path): + path = Path(path) + + if not path.exists(): + raise WifitripError( + f"File does not exist: {path}" + ) + + if not path.is_file(): + raise WifitripError( + f"Not a regular file: {path}" + ) + + try: + archive = zipfile.ZipFile(path, "r") + except (OSError, zipfile.BadZipFile) as exc: + raise WifitripError( + f"Invalid .wifitrip ZIP archive: {path}" + ) from exc + + with archive: + infos = archive.infolist() + + names = [info.filename for info in infos] + + if len(names) != len(set(names)): + raise WifitripError( + "Archive contains duplicate file names." + ) + + missing = [ + name + for name in REQUIRED_FILES + if name not in names + ] + + if missing: + raise WifitripError( + "Archive is missing required files: " + + ", ".join(missing) + ) + + data = {} + + for filename in REQUIRED_FILES: + try: + raw = archive.read(filename) + except KeyError as exc: + raise WifitripError( + f"Unable to read {filename}." + ) from exc + + data[filename] = _json_loads( + raw, + filename, + ) + + _validate_package(data) + + return data + + +def _validate_package(data): + for filename in REQUIRED_FILES: + if filename not in data: + raise WifitripError( + f"Missing package member: {filename}" + ) + + manifest = data["manifest.json"] + sessions = data["sessions.json"] + gps_tracks = data["gps_tracks.json"] + access_points = data["access_points.json"] + observations = data["observations.json"] + handshakes = data["handshakes.json"] + credentials = data["credentials.json"] + + _require_dict( + manifest, + "manifest.json", + ) + _require_list( + sessions, + "sessions.json", + ) + _require_list( + gps_tracks, + "gps_tracks.json", + ) + _require_list( + access_points, + "access_points.json", + ) + _require_list( + observations, + "observations.json", + ) + _require_list( + handshakes, + "handshakes.json", + ) + _require_list( + credentials, + "credentials.json", + ) + + if manifest.get("format") != WIFITRIP_FORMAT: + raise WifitripError( + "Unsupported package format." + ) + + if manifest.get("format_version") != WIFITRIP_VERSION: + raise WifitripError( + "Unsupported .wifitrip format version: " + f"{manifest.get('format_version')}" + ) + + _require_string( + manifest.get("created_at"), + "manifest.created_at", + ) + + if manifest.get("sessions") != len(sessions): + raise WifitripError( + "manifest.sessions does not match sessions.json." + ) + + session_hash_versions = manifest.get( + "session_hash_versions" + ) + + if not isinstance( + session_hash_versions, + list, + ): + raise WifitripError( + "manifest.session_hash_versions must be a list." + ) + + if not session_hash_versions: + raise WifitripError( + "manifest.session_hash_versions must not be empty." + ) + + if any( + version != SESSION_HASH_VERSION + for version in session_hash_versions + ): + raise WifitripError( + "Package contains an unsupported session hash version." + ) + + session_map = {} + session_versions = {} + + for index, session in enumerate(sessions): + _require_dict( + session, + f"sessions.json[{index}]", + ) + + session_hash = session.get( + "session_hash" + ) + session_hash_version = session.get( + "session_hash_version" + ) + + _validate_hash( + session_hash, + f"sessions.json[{index}].session_hash", + ) + + _require_integer( + session_hash_version, + f"sessions.json[{index}].session_hash_version", + ) + + if session_hash_version != SESSION_HASH_VERSION: + raise WifitripError( + "Unsupported session hash version: " + f"{session_hash_version}" + ) + + key = ( + session_hash, + session_hash_version, + ) + + if key in session_map: + raise WifitripError( + "Duplicate session hash in package: " + f"{session_hash}" + ) + + _require_string( + session.get("start_time"), + f"sessions.json[{index}].start_time", + ) + + _require_string( + session.get("end_time"), + f"sessions.json[{index}].end_time", + allow_none=True, + ) + + session_type = session.get( + "session_type" + ) + + if session_type is not None: + if session_type not in ( + "gps", + "non_gps", + ): + raise WifitripError( + "Invalid session_type in " + f"sessions.json[{index}]." + ) + + session_map[key] = session + session_versions[session_hash] = ( + session_hash_version + ) + + ap_map = {} + + for index, access_point in enumerate( + access_points + ): + _require_dict( + access_point, + f"access_points.json[{index}]", + ) + + bssid = access_point.get( + "bssid" + ) + + _require_bssid( + bssid, + f"access_points.json[{index}].bssid", + ) + + if bssid in ap_map: + raise WifitripError( + "Duplicate BSSID in package: " + f"{bssid}" + ) + + ap_map[bssid] = True + + gps_sequences = {} + + for index, point in enumerate( + gps_tracks + ): + _require_dict( + point, + f"gps_tracks.json[{index}]", + ) + + session_hash = point.get( + "session_hash" + ) + + _validate_hash( + session_hash, + f"gps_tracks.json[{index}].session_hash", + ) + + if session_hash not in session_versions: + raise WifitripError( + "GPS track references unknown session: " + f"{session_hash}" + ) + + sequence_no = point.get( + "sequence_no" + ) + + _require_integer( + sequence_no, + f"gps_tracks.json[{index}].sequence_no", + ) + + if sequence_no < 0: + raise WifitripError( + "GPS sequence_no must not be negative." + ) + + _require_string( + point.get("timestamp"), + f"gps_tracks.json[{index}].timestamp", + allow_none=True, + ) + + _require_number( + point.get("latitude"), + f"gps_tracks.json[{index}].latitude", + ) + + _require_number( + point.get("longitude"), + f"gps_tracks.json[{index}].longitude", + ) + + _require_number( + point.get("speed"), + f"gps_tracks.json[{index}].speed", + ) + + sequences = gps_sequences.setdefault( + session_hash, + set(), + ) + + if sequence_no in sequences: + raise WifitripError( + "Duplicate GPS sequence_no for session: " + f"{session_hash}" + ) + + sequences.add(sequence_no) + + for session_hash, sequences in gps_sequences.items(): + expected = set( + range(len(sequences)) + ) + + if sequences != expected: + raise WifitripError( + "GPS sequence numbers must be contiguous " + f"starting at zero for session {session_hash}." + ) + + for index, observation in enumerate( + observations + ): + _require_dict( + observation, + f"observations.json[{index}]", + ) + + session_hash = observation.get( + "session_hash" + ) + bssid = observation.get( + "bssid" + ) + + _validate_hash( + session_hash, + f"observations.json[{index}].session_hash", + ) + + _require_bssid( + bssid, + f"observations.json[{index}].bssid", + ) + + if session_hash not in session_versions: + raise WifitripError( + "Observation references unknown session: " + f"{session_hash}" + ) + + if bssid not in ap_map: + raise WifitripError( + "Observation references unknown BSSID: " + f"{bssid}" + ) + + _require_string( + observation.get("observed_at"), + f"observations.json[{index}].observed_at", + ) + + _require_number( + observation.get("latitude"), + f"observations.json[{index}].latitude", + ) + + _require_number( + observation.get("longitude"), + f"observations.json[{index}].longitude", + ) + + _require_number( + observation.get("speed"), + f"observations.json[{index}].speed", + ) + + _require_integer( + observation.get("rssi"), + f"observations.json[{index}].rssi", + allow_none=True, + ) + + _require_integer( + observation.get("channel"), + f"observations.json[{index}].channel", + allow_none=True, + ) + + _require_integer( + observation.get("frequency"), + f"observations.json[{index}].frequency", + allow_none=True, + ) + + for field in ( + "essid", + "encryption", + "cipher", + "akm", + "country", + ): + _require_string( + observation.get(field), + f"observations.json[{index}].{field}", + allow_none=True, + ) + + handshake_keys = {} + + for index, handshake in enumerate( + handshakes + ): + _require_dict( + handshake, + f"handshakes.json[{index}]", + ) + + session_hash = handshake.get( + "session_hash" + ) + bssid = handshake.get( + "bssid" + ) + handshake_key = handshake.get( + "handshake_key" + ) + + _validate_hash( + session_hash, + f"handshakes.json[{index}].session_hash", + ) + + _require_bssid( + bssid, + f"handshakes.json[{index}].bssid", + ) + + _require_string( + handshake_key, + f"handshakes.json[{index}].handshake_key", + ) + + if session_hash not in session_versions: + raise WifitripError( + "Handshake references unknown session: " + f"{session_hash}" + ) + + if bssid not in ap_map: + raise WifitripError( + "Handshake references unknown BSSID: " + f"{bssid}" + ) + + session_keys = handshake_keys.setdefault( + session_hash, + set(), + ) + + if handshake_key in session_keys: + raise WifitripError( + "Duplicate handshake_key for session: " + f"{session_hash}: {handshake_key}" + ) + + session_keys.add(handshake_key) + + _require_string( + handshake.get("type"), + f"handshakes.json[{index}].type", + ) + + _require_string( + handshake.get("hash22000"), + f"handshakes.json[{index}].hash22000", + allow_none=True, + ) + + _require_string( + handshake.get("message_pair"), + f"handshakes.json[{index}].message_pair", + allow_none=True, + ) + + _require_string( + handshake.get("captured_at"), + f"handshakes.json[{index}].captured_at", + allow_none=True, + ) + + _require_number( + handshake.get("latitude"), + f"handshakes.json[{index}].latitude", + ) + + _require_number( + handshake.get("longitude"), + f"handshakes.json[{index}].longitude", + ) + + _require_number( + handshake.get("speed"), + f"handshakes.json[{index}].speed", + ) + + for index, credential in enumerate( + credentials + ): + _require_dict( + credential, + f"credentials.json[{index}]", + ) + + session_hash = credential.get( + "session_hash" + ) + bssid = credential.get( + "bssid" + ) + handshake_key = credential.get( + "handshake_key" + ) + + _validate_hash( + session_hash, + f"credentials.json[{index}].session_hash", + ) + + _require_bssid( + bssid, + f"credentials.json[{index}].bssid", + ) + + if session_hash not in session_versions: + raise WifitripError( + "Credential references unknown session: " + f"{session_hash}" + ) + + if bssid not in ap_map: + raise WifitripError( + "Credential references unknown BSSID: " + f"{bssid}" + ) + + if handshake_key is not None: + _require_string( + handshake_key, + f"credentials.json[{index}].handshake_key", + ) + + if handshake_key not in handshake_keys.get( + session_hash, + set(), + ): + raise WifitripError( + "Credential references unknown handshake_key: " + f"{session_hash}: {handshake_key}" + ) + + _require_string( + credential.get("password"), + f"credentials.json[{index}].password", + ) + + if not credential.get("password"): + raise WifitripError( + "Credential password must not be empty." + ) + + _require_string( + credential.get("source"), + f"credentials.json[{index}].source", + allow_none=True, + ) + + _require_string( + credential.get("created_at"), + f"credentials.json[{index}].created_at", + allow_none=True, + ) + + verified = credential.get( + "verified" + ) + + _require_integer( + verified, + f"credentials.json[{index}].verified", + allow_none=False, + ) + + if verified not in (0, 1): + raise WifitripError( + "Credential verified must be 0 or 1." + ) + + +def _session_hash(conn, session_id): + session = conn.execute( + """ + SELECT + start_time, + end_time + FROM capture_sessions + WHERE id=? + """, + (session_id,), + ).fetchone() + + if session is None: + raise WifitripError( + f"Session {session_id} does not exist." + ) + + gps_rows = conn.execute( + """ + SELECT + timestamp, + latitude, + longitude + FROM gps_track + WHERE session_id=? + ORDER BY sequence_no + """, + (session_id,), + ).fetchall() + + handshake_rows = conn.execute( + """ + SELECT + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + FROM handshakes + JOIN access_points + ON access_points.id = + handshakes.access_point_id + WHERE handshakes.session_id=? + ORDER BY + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + """, + (session_id,), + ).fetchall() + + handshake_data = [ + [ + row["bssid"], + row["type"], + row["hash22000"], + row["message_pair"], + row["captured_at"], + ] + for row in handshake_rows + ] + + if gps_rows: + gps_data = [ + [ + row["timestamp"], + row["latitude"], + row["longitude"], + ] + for row in gps_rows + ] + + canonical = [ + "GPS_SESSION_V1", + gps_data, + handshake_data, + ] + + else: + observation_rows = conn.execute( + """ + SELECT + observations.observed_at, + access_points.bssid + FROM access_point_observations AS observations + JOIN access_points + ON access_points.id = + observations.access_point_id + WHERE observations.session_id=? + ORDER BY + observations.observed_at, + access_points.bssid + """, + (session_id,), + ).fetchall() + + observation_data = [ + [ + row["observed_at"], + row["bssid"], + ] + for row in observation_rows + ] + + canonical = [ + "NON_GPS_SESSION_V1", + session["start_time"], + session["end_time"], + observation_data, + handshake_data, + ] + + return hashlib.sha256( + _json_bytes(canonical) + ).hexdigest() + + +def _default_export_path(): + timestamp = datetime.now( + timezone.utc + ).strftime( + "%Y%m%d-%H%M%S" + ) + + return Path.cwd() / ( + "wifi-gps-mapper-trips-" + f"{timestamp}.wifitrip" + ) + + +def _zip_write_json(archive, filename, value): + archive.writestr( + filename, + _json_bytes(value), + ) + + +def export_wifitrip(conn, output_path=None): + started = time.monotonic() + + if output_path is None: + output_path = _default_export_path() + + output_path = Path(output_path) + + if output_path.suffix.lower() != ".wifitrip": + output_path = output_path.with_suffix( + ".wifitrip" + ) + + output_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + sessions = conn.execute( + """ + SELECT + id, + start_time, + end_time, + session_hash, + session_hash_version + FROM capture_sessions + ORDER BY id + """ + ).fetchall() + + session_by_id = {} + exported_sessions = [] + + for row in sessions: + session_id = row["id"] + session_hash = row["session_hash"] + hash_version = row[ + "session_hash_version" + ] + + if not session_hash or hash_version is None: + raise WifitripError( + "Session " + f"{session_id} has no session hash." + ) + + if hash_version != SESSION_HASH_VERSION: + raise WifitripError( + "Session " + f"{session_id} has unsupported session hash " + f"version {hash_version}." + ) + + _validate_hash( + session_hash, + f"session {session_id} hash", + ) + + calculated_hash = _session_hash( + conn, + session_id, + ) + + if calculated_hash != session_hash: + raise WifitripError( + "Session " + f"{session_id} hash verification failed: " + f"expected {session_hash}, " + f"calculated {calculated_hash}" + ) + + gps_count = conn.execute( + """ + SELECT COUNT(*) + FROM gps_track + WHERE session_id=? + """, + (session_id,), + ).fetchone()[0] + + session_type = ( + "gps" + if gps_count + else "non_gps" + ) + + session_record = { + "session_hash": session_hash, + "session_hash_version": hash_version, + "start_time": row["start_time"], + "end_time": row["end_time"], + "session_type": session_type, + } + + session_by_id[session_id] = session_record + exported_sessions.append( + session_record + ) + + session_ids = list(session_by_id) + + if not session_ids: + raise WifitripError( + "No capture sessions available for export." + ) + + placeholders = ",".join( + "?" for _ in session_ids + ) + + gps_rows = conn.execute( + f""" + SELECT + gps_track.session_id, + gps_track.sequence_no, + gps_track.timestamp, + gps_track.latitude, + gps_track.longitude, + gps_track.speed + FROM gps_track + WHERE gps_track.session_id IN ( + {placeholders} + ) + ORDER BY + gps_track.session_id, + gps_track.sequence_no + """, + session_ids, + ).fetchall() + + gps_tracks = [ + { + "session_hash": session_by_id[ + row["session_id"] + ]["session_hash"], + "sequence_no": row["sequence_no"], + "timestamp": row["timestamp"], + "latitude": row["latitude"], + "longitude": row["longitude"], + "speed": row["speed"], + } + for row in gps_rows + ] + + observation_rows = conn.execute( + f""" + SELECT + observations.session_id, + access_points.bssid, + observations.observed_at, + observations.latitude, + observations.longitude, + observations.speed, + observations.rssi, + observations.channel, + observations.frequency, + observations.essid, + observations.encryption, + observations.cipher, + observations.akm, + observations.country, + observations.id + FROM access_point_observations AS observations + JOIN access_points + ON access_points.id = + observations.access_point_id + WHERE observations.session_id IN ( + {placeholders} + ) + ORDER BY + observations.session_id, + observations.observed_at, + observations.id + """, + session_ids, + ).fetchall() + + observations = [ + { + "session_hash": session_by_id[ + row["session_id"] + ]["session_hash"], + "bssid": row["bssid"], + "observed_at": row["observed_at"], + "latitude": row["latitude"], + "longitude": row["longitude"], + "speed": row["speed"], + "rssi": row["rssi"], + "channel": row["channel"], + "frequency": row["frequency"], + "essid": row["essid"], + "encryption": row["encryption"], + "cipher": row["cipher"], + "akm": row["akm"], + "country": row["country"], + } + for row in observation_rows + ] + + handshake_rows = conn.execute( + f""" + SELECT + handshakes.id, + handshakes.session_id, + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at, + handshakes.latitude, + handshakes.longitude, + handshakes.speed + FROM handshakes + JOIN access_points + ON access_points.id = + handshakes.access_point_id + WHERE handshakes.session_id IN ( + {placeholders} + ) + ORDER BY + handshakes.session_id, + handshakes.id + """, + session_ids, + ).fetchall() + + handshake_key_by_id = {} + handshake_records = {} + + handshakes = [] + + for row in handshake_rows: + session_hash = session_by_id[ + row["session_id"] + ]["session_hash"] + + records = handshake_records.setdefault( + session_hash, + [], + ) + + handshake_key = ( + f"h{len(records) + 1:06d}" + ) + + handshake_key_by_id[ + row["id"] + ] = ( + session_hash, + handshake_key, + ) + + records.append( + handshake_key + ) + + handshakes.append( + { + "session_hash": session_hash, + "handshake_key": handshake_key, + "bssid": row["bssid"], + "type": row["type"], + "hash22000": row["hash22000"], + "message_pair": row["message_pair"], + "captured_at": row["captured_at"], + "latitude": row["latitude"], + "longitude": row["longitude"], + "speed": row["speed"], + } + ) + + session_ap_ids = {} + + for row in observation_rows: + session_ap_ids.setdefault( + row["session_id"], + set(), + ).add( + row["bssid"] + ) + + for row in handshake_rows: + session_ap_ids.setdefault( + row["session_id"], + set(), + ).add( + row["bssid"] + ) + + credentials_rows = conn.execute( + """ + SELECT + credentials.id, + credentials.access_point_id, + credentials.handshake_id, + access_points.bssid, + credentials.password, + credentials.source, + credentials.created_at, + credentials.verified, + handshakes.session_id AS handshake_session_id + FROM credentials + JOIN access_points + ON access_points.id = + credentials.access_point_id + LEFT JOIN handshakes + ON handshakes.id = + credentials.handshake_id + ORDER BY credentials.id + """ + ).fetchall() + + credentials = [] + + for row in credentials_rows: + if row["handshake_session_id"] is not None: + session_id = row[ + "handshake_session_id" + ] + + if session_id not in session_by_id: + continue + + session_hash = session_by_id[ + session_id + ]["session_hash"] + + handshake_ref = ( + handshake_key_by_id.get( + row["handshake_id"] + ) + ) + + handshake_key = ( + handshake_ref[1] + if handshake_ref + else None + ) + + credentials.append( + { + "session_hash": session_hash, + "bssid": row["bssid"], + "handshake_key": handshake_key, + "password": row["password"], + "source": row["source"], + "created_at": row["created_at"], + "verified": row["verified"], + } + ) + + continue + + for session_id, bssids in ( + session_ap_ids.items() + ): + if row["bssid"] not in bssids: + continue + + if session_id not in session_by_id: + continue + + credentials.append( + { + "session_hash": session_by_id[ + session_id + ]["session_hash"], + "bssid": row["bssid"], + "handshake_key": None, + "password": row["password"], + "source": row["source"], + "created_at": row["created_at"], + "verified": row["verified"], + } + ) + + bssids = set() + + for observation in observations: + bssids.add( + observation["bssid"] + ) + + for handshake in handshakes: + bssids.add( + handshake["bssid"] + ) + + for credential in credentials: + bssids.add( + credential["bssid"] + ) + + access_points = [ + { + "bssid": bssid + } + for bssid in sorted(bssids) + ] + + manifest = { + "format": WIFITRIP_FORMAT, + "format_version": WIFITRIP_VERSION, + "created_at": time.strftime( + "%Y-%m-%dT%H:%M:%SZ", + time.gmtime(), + ), + "sessions": len( + exported_sessions + ), + "session_hash_versions": [ + SESSION_HASH_VERSION + ], + } + + logger.info( + "Starting .wifitrip export: sessions=%d file=%s", + len(exported_sessions), + output_path, + ) + + fd, temporary_name = tempfile.mkstemp( + prefix=".wifitrip-", + suffix=".tmp", + dir=str(output_path.parent), + ) + + os.close(fd) + + temporary_path = Path( + temporary_name + ) + + try: + with zipfile.ZipFile( + temporary_path, + "w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=6, + ) as archive: + _zip_write_json( + archive, + "manifest.json", + manifest, + ) + + _zip_write_json( + archive, + "sessions.json", + exported_sessions, + ) + + _zip_write_json( + archive, + "gps_tracks.json", + gps_tracks, + ) + + _zip_write_json( + archive, + "access_points.json", + access_points, + ) + + _zip_write_json( + archive, + "observations.json", + observations, + ) + + _zip_write_json( + archive, + "handshakes.json", + handshakes, + ) + + _zip_write_json( + archive, + "credentials.json", + credentials, + ) + + os.replace( + temporary_path, + output_path, + ) + + except Exception: + try: + temporary_path.unlink() + except FileNotFoundError: + pass + + raise + + size = output_path.stat().st_size + duration = ( + time.monotonic() - started + ) + + result = { + "sessions": len( + exported_sessions + ), + "access_points": len( + access_points + ), + "gps_points": len( + gps_tracks + ), + "observations": len( + observations + ), + "handshakes": len( + handshakes + ), + "credentials": len( + credentials + ), + "file": str(output_path), + "size": size, + "duration": duration, + } + + logger.info( + "Completed .wifitrip export: " + "sessions=%d observations=%d handshakes=%d " + "credentials=%d file=%s size=%d duration=%.3fs", + result["sessions"], + result["observations"], + result["handshakes"], + result["credentials"], + output_path, + size, + duration, + ) + + return result + + +def _get_or_create_import_ap( + conn, + bssid, + created_access_points, +): + row = conn.execute( + """ + SELECT id + FROM access_points + WHERE bssid=? + """, + (bssid,), + ).fetchone() + + if row is not None: + return row["id"] + + cursor = conn.execute( + """ + INSERT INTO access_points ( + bssid, + times_seen + ) + VALUES (?, 0) + """, + (bssid,), + ) + + access_point_id = cursor.lastrowid + + created_access_points.add( + access_point_id + ) + + return access_point_id + + +def _update_imported_ap_aggregates( + conn, + access_point_id, + imported_observation_count, + imported_first_seen, + imported_last_seen, + latest_observation, +): + if imported_observation_count == 0: + return + + existing = conn.execute( + """ + SELECT + first_seen, + last_seen, + times_seen + FROM access_points + WHERE id=? + """, + (access_point_id,), + ).fetchone() + + if existing is None: + raise WifitripError( + f"Access point {access_point_id} does not exist." + ) + + first_seen = existing["first_seen"] + + if ( + first_seen is None + or imported_first_seen < first_seen + ): + first_seen = imported_first_seen + + last_seen = existing["last_seen"] + + latest_is_global_latest = ( + last_seen is None + or imported_last_seen >= last_seen + ) + + if ( + last_seen is None + or imported_last_seen > last_seen + ): + last_seen = imported_last_seen + + if latest_is_global_latest: + conn.execute( + """ + UPDATE access_points + SET + first_seen=?, + last_seen=?, + times_seen=COALESCE(times_seen, 0) + + ?, + last_rssi=?, + last_latitude=?, + last_longitude=?, + last_speed=?, + channel=COALESCE(?, channel), + frequency=COALESCE(?, frequency), + essid=COALESCE(?, essid), + encryption=COALESCE(?, encryption), + cipher=COALESCE(?, cipher), + akm=COALESCE(?, akm), + country=COALESCE(?, country) + WHERE id=? + """, + ( + first_seen, + last_seen, + imported_observation_count, + latest_observation["rssi"], + latest_observation["latitude"], + latest_observation["longitude"], + latest_observation["speed"], + latest_observation["channel"], + latest_observation["frequency"], + latest_observation["essid"], + latest_observation["encryption"], + latest_observation["cipher"], + latest_observation["akm"], + latest_observation["country"], + access_point_id, + ), + ) + + else: + conn.execute( + """ + UPDATE access_points + SET + first_seen=?, + last_seen=?, + times_seen=COALESCE(times_seen, 0) + + ? + WHERE id=? + """, + ( + first_seen, + last_seen, + imported_observation_count, + access_point_id, + ), + ) + + +def _session_id_by_hash( + conn, + session_hash, + session_hash_version, +): + row = conn.execute( + """ + SELECT id + FROM capture_sessions + WHERE session_hash=? + AND session_hash_version=? + LIMIT 1 + """, + ( + session_hash, + session_hash_version, + ), + ).fetchone() + + if row is None: + return None + + return row["id"] + + +def import_wifitrip(conn, package_path): + started = time.monotonic() + + logger.info( + "Starting .wifitrip import: file=%s", + package_path, + ) + + package = _read_package( + package_path + ) + + manifest = package["manifest.json"] + sessions = package["sessions.json"] + gps_tracks = package["gps_tracks.json"] + observations = package["observations.json"] + handshakes = package["handshakes.json"] + credentials = package["credentials.json"] + + gps_by_session = {} + observations_by_session = {} + handshakes_by_session = {} + credentials_by_session = {} + + for point in gps_tracks: + gps_by_session.setdefault( + point["session_hash"], + [], + ).append(point) + + for observation in observations: + observations_by_session.setdefault( + observation["session_hash"], + [], + ).append(observation) + + for handshake in handshakes: + handshakes_by_session.setdefault( + handshake["session_hash"], + [], + ).append(handshake) + + for credential in credentials: + credentials_by_session.setdefault( + credential["session_hash"], + [], + ).append(credential) + + result = { + "file": str(package_path), + "sessions": len(sessions), + "imported": 0, + "duplicates": 0, + "failed": 0, + "failed_sessions": [], + } + + conn.execute( + "PRAGMA foreign_keys=ON" + ) + + if conn.in_transaction: + raise WifitripError( + "Database connection already has an active transaction." + ) + + for session in sessions: + session_hash = session[ + "session_hash" + ] + hash_version = session[ + "session_hash_version" + ] + + existing_id = _session_id_by_hash( + conn, + session_hash, + hash_version, + ) + + if existing_id is not None: + result["duplicates"] += 1 + + logger.info( + "Skipping duplicate .wifitrip session: " + "hash=%s local_id=%s", + session_hash, + existing_id, + ) + + continue + + try: + conn.execute( + "BEGIN" + ) + + cursor = conn.execute( + """ + INSERT INTO capture_sessions ( + start_time, + end_time, + capture_file, + session_hash, + session_hash_version + ) + VALUES (?, ?, ?, ?, ?) + """, + ( + session["start_time"], + session["end_time"], + f"wifitrip:{session_hash}", + session_hash, + hash_version, + ), + ) + + local_session_id = cursor.lastrowid + + created_access_points = set() + ap_ids = {} + + session_observations = ( + observations_by_session.get( + session_hash, + [], + ) + ) + + session_handshakes = ( + handshakes_by_session.get( + session_hash, + [], + ) + ) + + session_credentials = ( + credentials_by_session.get( + session_hash, + [], + ) + ) + + bssids = set() + + for observation in session_observations: + bssids.add( + observation["bssid"] + ) + + for handshake in session_handshakes: + bssids.add( + handshake["bssid"] + ) + + for credential in session_credentials: + bssids.add( + credential["bssid"] + ) + + for bssid in sorted(bssids): + ap_ids[bssid] = ( + _get_or_create_import_ap( + conn, + bssid, + created_access_points, + ) + ) + + for point in gps_by_session.get( + session_hash, + [], + ): + conn.execute( + """ + INSERT INTO gps_track ( + session_id, + sequence_no, + latitude, + longitude, + speed, + timestamp + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + local_session_id, + point["sequence_no"], + point["latitude"], + point["longitude"], + point["speed"], + point["timestamp"], + ), + ) + + imported_observations_by_ap = {} + + for observation in session_observations: + access_point_id = ap_ids[ + observation["bssid"] + ] + + conn.execute( + """ + INSERT INTO access_point_observations ( + access_point_id, + session_id, + observed_at, + latitude, + longitude, + speed, + rssi, + channel, + frequency, + essid, + encryption, + cipher, + akm, + country + ) + VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, + ?, ?, ?, ?, ?, ? + ) + """, + ( + access_point_id, + local_session_id, + observation["observed_at"], + observation["latitude"], + observation["longitude"], + observation["speed"], + observation["rssi"], + observation["channel"], + observation["frequency"], + observation["essid"], + observation["encryption"], + observation["cipher"], + observation["akm"], + observation["country"], + ), + ) + + imported_observations_by_ap.setdefault( + access_point_id, + [], + ).append(observation) + + for access_point_id, imported_observations in ( + imported_observations_by_ap.items() + ): + imported_first_seen = min( + observation["observed_at"] + for observation in imported_observations + ) + + imported_last_seen = max( + observation["observed_at"] + for observation in imported_observations + ) + + latest_observation = max( + imported_observations, + key=lambda observation: ( + observation["observed_at"], + ), + ) + + _update_imported_ap_aggregates( + conn, + access_point_id, + len(imported_observations), + imported_first_seen, + imported_last_seen, + latest_observation, + ) + + handshake_ids = {} + + for handshake in session_handshakes: + access_point_id = ap_ids[ + handshake["bssid"] + ] + + cursor = conn.execute( + """ + INSERT INTO handshakes ( + access_point_id, + session_id, + type, + hash22000, + message_pair, + captured_at, + latitude, + longitude, + speed + ) + VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, ? + ) + """, + ( + access_point_id, + local_session_id, + handshake["type"], + handshake["hash22000"], + handshake["message_pair"], + handshake["captured_at"], + handshake["latitude"], + handshake["longitude"], + handshake["speed"], + ), + ) + + handshake_ids[ + handshake["handshake_key"] + ] = cursor.lastrowid + + if handshake["type"] == "PMKID": + conn.execute( + """ + UPDATE access_points + SET + has_pmkid=1 + WHERE id=? + """, + (access_point_id,), + ) + else: + conn.execute( + """ + UPDATE access_points + SET + has_handshake=1 + WHERE id=? + """, + (access_point_id,), + ) + + calculated_hash = _session_hash( + conn, + local_session_id, + ) + + if calculated_hash != session_hash: + raise WifitripError( + "Session hash verification failed: " + f"expected {session_hash}, " + f"calculated {calculated_hash}" + ) + + for credential in session_credentials: + access_point_id = ap_ids[ + credential["bssid"] + ] + + handshake_id = None + + if credential[ + "handshake_key" + ] is not None: + handshake_id = handshake_ids[ + credential[ + "handshake_key" + ] + ] + + existing_credential = conn.execute( + """ + SELECT id + FROM credentials + WHERE access_point_id=? + AND handshake_id IS ? + AND password=? + LIMIT 1 + """, + ( + access_point_id, + handshake_id, + credential["password"], + ), + ).fetchone() + + if existing_credential is not None: + continue + + conn.execute( + """ + INSERT INTO credentials ( + access_point_id, + handshake_id, + password, + source, + created_at, + verified + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + access_point_id, + handshake_id, + credential["password"], + credential["source"], + credential["created_at"], + credential["verified"], + ), + ) + + conn.execute( + """ + UPDATE access_points + SET + is_cracked=1 + WHERE id=? + """, + (access_point_id,), + ) + + conn.commit() + + result["imported"] += 1 + + logger.info( + "Imported .wifitrip session: " + "hash=%s local_id=%s", + session_hash, + local_session_id, + ) + + except Exception as exc: + conn.rollback() + + result["failed"] += 1 + result["failed_sessions"].append( + { + "session_hash": session_hash, + "error": str(exc), + } + ) + + logger.exception( + "Failed to import .wifitrip session: " + "hash=%s", + session_hash, + ) + + result["duration"] = ( + time.monotonic() - started + ) + + logger.info( + "Completed .wifitrip import: " + "sessions=%d imported=%d duplicates=%d " + "failed=%d file=%s duration=%.3fs", + result["sessions"], + result["imported"], + result["duplicates"], + result["failed"], + package_path, + result["duration"], + ) + + return result + + +def validate_wifitrip(package_path): + """ + Полная проверка .wifitrip без изменения БД. + + Возвращает краткую информацию о пакете. + """ + package = _read_package( + package_path + ) + + manifest = package["manifest.json"] + + return { + "valid": True, + "format": manifest["format"], + "format_version": manifest[ + "format_version" + ], + "sessions": len( + package["sessions.json"] + ), + "access_points": len( + package["access_points.json"] + ), + "gps_points": len( + package["gps_tracks.json"] + ), + "observations": len( + package["observations.json"] + ), + "handshakes": len( + package["handshakes.json"] + ), + "credentials": len( + package["credentials.json"] + ), + "session_hash_versions": manifest[ + "session_hash_versions" + ], + } diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..9a3d279 --- /dev/null +++ b/src/config.py @@ -0,0 +1,365 @@ +from pathlib import Path +import subprocess +import yaml + + +class Config: + + def __init__(self): + + # Путь к конфигурационному файлу + config_file = ( + Path(__file__).parent.parent + / + "config" + / + "config.yaml" + ) + + + # Загрузка YAML + with open( + config_file, + "r" + ) as file: + + self.cfg = yaml.safe_load(file) + + self._interface = None + + + + # ----------------------------- + # GPS + # ----------------------------- + + @property + def gps_source(self): + gps = self.cfg["gps"] + + return gps.get( + "source", + "gpsrelay" + ) + + @property + def gpsrelay_host(self): + gps = self.cfg["gps"] + + if "gpsrelay" in gps: + return gps["gpsrelay"]["host"] + + return gps["host"] + + @property + def gpsrelay_port(self): + gps = self.cfg["gps"] + + if "gpsrelay" in gps: + return gps["gpsrelay"]["port"] + + return gps["port"] + + @property + def gnss_device(self): + gnss = self.cfg["gps"]["gnss"] + handler = gnss["handler"] + + return gnss[handler]["device"] + + @property + def gnss_at_device(self): + return self.cfg["gps"]["gnss"]["modem"]["at_device"] + + @property + def gnss_handler(self): + return self.cfg["gps"]["gnss"]["handler"] + + + + # ----------------------------- + # Database + # ----------------------------- + + @property + def database(self): + + return self.cfg["database"]["file"] + + @property + def vendor_database(self): + + return ( + Path(__file__).parent.parent + / + self.cfg["vendor"]["database"] + ) + + @property + def vendor_sources(self): + + return self.cfg["vendor"]["sources"] + + + # ----------------------------- + # WiFi + # ----------------------------- + + @property + def interface(self): + + if self._interface is None: + + raise RuntimeError( + "WiFi interface is not selected." + ) + + return self._interface + + def select_interface(self): + + result = subprocess.run( + + [ + "sudo", + "-n", + "iw", + "dev" + ], + + capture_output=True, + + text=True + + ) + + interfaces = [] + + current = None + + for line in result.stdout.splitlines(): + + line = line.strip() + + if line.startswith("Interface"): + + current = line.split()[1] + + elif ( + line.startswith("type") + and + current + ): + + if "monitor" in line or "managed" in line: + + interfaces.append( + current + ) + + current = None + + + if not interfaces: + + raise RuntimeError( + "No WiFi interface found." + ) + + + iwlist = subprocess.run( + + [ + "sudo", + "-n", + "iw", + "list" + ], + + capture_output=True, + + text=True + + ).stdout + + + if "monitor" not in iwlist.lower(): + + raise RuntimeError( + "No adapter supports monitor mode." + ) + + + import os + + requested_interface = os.environ.get( + "WIFI_INTERFACE" + ) + + if requested_interface: + + if requested_interface in interfaces: + + self._interface = ( + requested_interface + ) + + return self._interface + + raise RuntimeError( + f"WiFi interface '{requested_interface}' " + "is not available." + ) + + + if len(interfaces) == 1: + + self._interface = interfaces[0] + + return self._interface + + + print() + + print( + "Available WiFi interfaces:" + ) + + print() + + for index, iface in enumerate( + interfaces, + start=1 + ): + + print( + f"{index}) {iface}" + ) + + print() + + while True: + + try: + + value = int( + input( + "Select interface: " + ) + ) + + if ( + 1 + <= value + <= len(interfaces) + ): + + self._interface = ( + interfaces[value - 1] + ) + + return self._interface + + except Exception: + + pass + + print( + "Invalid selection." + ) + + @property + def wifi_enable_2_4ghz(self): + + return self.cfg["wifi"]["enable_2_4ghz"] + + + @property + def wifi_channels_2_4ghz(self): + + return self.cfg["wifi"]["channels_2_4ghz"] + + + @property + def wifi_enable_5ghz(self): + + return self.cfg["wifi"]["enable_5ghz"] + + + @property + def wifi_channels_5ghz(self): + + return self.cfg["wifi"]["channels_5ghz"] + + + @property + def wifi_enable_6ghz(self): + + return self.cfg["wifi"]["enable_6ghz"] + + + @property + def wifi_channels_6ghz(self): + + return self.cfg["wifi"]["channels_6ghz"] + + + @property + def wifi_filtermode(self): + + return self.cfg["wifi"]["filtermode"] + + + @property + def wifi_extra_args(self): + + return self.cfg["wifi"]["extra_args"] + + + +# ----------------------------- +# Tools +# ----------------------------- + + @property + def hcxdumptool(self): + + return ( + Path(__file__).parent.parent + / + "bin" + / + "hcxdumptool" + ) + + + @property + def hcxpcapngtool(self): + + return ( + Path(__file__).parent.parent + / + "bin" + / + "hcxpcapngtool" + ) + + # ----------------------------- + # Capture + # ----------------------------- + + @property + def capture_directory(self): + + return self.cfg["captures"]["directory"] + + + + # ----------------------------- + # Status + # ----------------------------- + + @property + def status_interval(self): + + return self.cfg["status"]["interval"] \ No newline at end of file diff --git a/src/database.py b/src/database.py new file mode 100644 index 0000000..538af35 --- /dev/null +++ b/src/database.py @@ -0,0 +1,1973 @@ +import hashlib +import json +import logging +import sqlite3 + +from pathlib import Path +from datetime import datetime, timezone + + +class Database: + + + def __init__(self, db_path): + + Path(db_path).parent.mkdir( + parents=True, + exist_ok=True + ) + + + self.conn = sqlite3.connect( + db_path, + check_same_thread=False + ) + + + self.conn.row_factory = sqlite3.Row + + # + # Оптимизация SQLite + # + self.conn.execute( + "PRAGMA journal_mode=WAL" + ) + + self.conn.execute( + "PRAGMA synchronous=NORMAL" + ) + + self.conn.execute( + "PRAGMA temp_store=MEMORY" + ) + + self.conn.execute( + "PRAGMA cache_size=-100000" + ) + + # + # Буфер наблюдений точек доступа + # + self.observation_buffer = [] + + self.observation_batch_size = 1000 + + self.create_tables() + + + + # ========================================================= + # Создание таблиц + # ========================================================= + + def create_tables(self): + + + # + # Сессии захвата + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS capture_sessions ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + start_time TEXT NOT NULL, + + end_time TEXT, + + capture_file TEXT NOT NULL, + + session_hash TEXT, + + session_hash_version INTEGER + + ) + """) + + + + # + # Точки доступа + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS access_points ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + + bssid TEXT NOT NULL UNIQUE, + + essid TEXT, + + + encryption TEXT, + + cipher TEXT, + + akm TEXT, + + + country TEXT, + + channel INTEGER, + + frequency INTEGER, + + + vendor TEXT, + + + first_seen TEXT, + + last_seen TEXT, + + + times_seen INTEGER DEFAULT 1, + + + last_rssi INTEGER, + + + last_latitude REAL, + + last_longitude REAL, + + last_speed REAL, + + + has_handshake INTEGER DEFAULT 0, + + has_pmkid INTEGER DEFAULT 0, + + is_cracked INTEGER DEFAULT 0 + + ) + """) + + + + # + # Все найденные handshake / PMKID + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS handshakes ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + + access_point_id INTEGER NOT NULL, + + session_id INTEGER, + + + type TEXT NOT NULL, + + + hash22000 TEXT, + + + message_pair TEXT, + + + captured_at TEXT, + + + latitude REAL, + + longitude REAL, + + speed REAL, + + FOREIGN KEY(access_point_id) + REFERENCES access_points(id), + + + FOREIGN KEY(session_id) + REFERENCES capture_sessions(id) + + ) + """) + + + + # + # Найденные пароли после hashcat + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS credentials ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + + access_point_id INTEGER NOT NULL, + + + handshake_id INTEGER, + + + password TEXT NOT NULL, + + + source TEXT, + + + created_at TEXT, + + + verified INTEGER DEFAULT 0, + + + UNIQUE(access_point_id, handshake_id, password), + + + FOREIGN KEY(access_point_id) + REFERENCES access_points(id), + + + FOREIGN KEY(handshake_id) + REFERENCES handshakes(id) + + ) + """) + + + + # + # GPS трек + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS gps_track ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + + session_id INTEGER, + + + sequence_no INTEGER NOT NULL, + + + latitude REAL, + + + longitude REAL, + + + speed REAL, + + + timestamp TEXT, + + + FOREIGN KEY(session_id) + REFERENCES capture_sessions(id) + + ) + """) + + # + # История наблюдений точек доступа + # + self.conn.execute(""" + CREATE TABLE IF NOT EXISTS access_point_observations ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + access_point_id INTEGER NOT NULL, + + session_id INTEGER NOT NULL, + + observed_at TEXT NOT NULL, + + latitude REAL, + + longitude REAL, + + speed REAL, + + rssi INTEGER, + + channel INTEGER, + + frequency INTEGER, + + essid TEXT, + + encryption TEXT, + + cipher TEXT, + + akm TEXT, + + country TEXT, + + FOREIGN KEY(access_point_id) + REFERENCES access_points(id), + + FOREIGN KEY(session_id) + REFERENCES capture_sessions(id) + + ) + """) + + # + # Индексы handshakes + # + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_handshakes_hash + + ON handshakes( + hash22000 + ) + """) + + + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_handshakes_access_point + + ON handshakes( + access_point_id + ) + """) + + # + # Индексы истории наблюдений + # + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_observation_access_point + + ON access_point_observations( + access_point_id + ) + """) + + + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_observation_session + + ON access_point_observations( + session_id + ) + """) + + + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_observation_time + + ON access_point_observations( + observed_at + ) + """) + + + self.conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_observation_ap_time + + ON access_point_observations( + access_point_id, + observed_at + ) + """) + + + self._migrate_credentials_table() + + self._migrate_gps_track() + + self._migrate_session_hash() + + self.conn.commit() + + def _migrate_credentials_table( + self + ): + columns = self.conn.execute( + """ + PRAGMA table_info(credentials) + """ + ).fetchall() + + column_names = { + column[1] + for column in columns + } + + unique_indexes = self.conn.execute( + """ + PRAGMA index_list(credentials) + """ + ).fetchall() + + has_provenance_unique = False + + for index in unique_indexes: + + if not index[2]: + continue + + index_name = index[1] + + index_columns = self.conn.execute( + f""" + PRAGMA index_info("{index_name}") + """ + ).fetchall() + + names = [ + column[2] + for column in index_columns + ] + + if names == [ + "access_point_id", + "handshake_id", + "password", + ]: + has_provenance_unique = True + break + + if ( + "handshake_id" in column_names + and has_provenance_unique + ): + return + + # + # Старая таблица credentials. + # Пересоздаем её с актуальной схемой. + # + self.conn.execute( + """ + ALTER TABLE credentials + RENAME TO credentials_old + """ + ) + + self.conn.execute(""" + CREATE TABLE credentials ( + + id INTEGER PRIMARY KEY AUTOINCREMENT, + + + access_point_id INTEGER NOT NULL, + + + handshake_id INTEGER, + + + password TEXT NOT NULL, + + + source TEXT, + + + created_at TEXT, + + + verified INTEGER DEFAULT 0, + + + UNIQUE(access_point_id, handshake_id, password), + + + FOREIGN KEY(access_point_id) + REFERENCES access_points(id), + + + FOREIGN KEY(handshake_id) + REFERENCES handshakes(id) + + ) + """) + + if "handshake_id" in column_names: + + self.conn.execute( + """ + INSERT INTO credentials + ( + id, + access_point_id, + handshake_id, + password, + source, + created_at, + verified + ) + SELECT + id, + access_point_id, + handshake_id, + password, + source, + created_at, + verified + FROM credentials_old + """ + ) + + else: + + self.conn.execute( + """ + INSERT INTO credentials + ( + id, + access_point_id, + password, + source, + created_at, + verified + ) + SELECT + id, + access_point_id, + password, + source, + created_at, + verified + FROM credentials_old + """ + ) + + self.conn.execute( + """ + DROP TABLE credentials_old + """ + ) + + def _migrate_session_hash( + self + ): + columns = self.conn.execute( + """ + PRAGMA table_info(capture_sessions) + """ + ).fetchall() + + column_names = { + column[1] + for column in columns + } + + if "session_hash" not in column_names: + self.conn.execute( + """ + ALTER TABLE capture_sessions + ADD COLUMN session_hash TEXT + """ + ) + + if "session_hash_version" not in column_names: + self.conn.execute( + """ + ALTER TABLE capture_sessions + ADD COLUMN session_hash_version INTEGER + """ + ) + + self.conn.commit() + + self.conn.execute( + "BEGIN" + ) + + try: + sessions = self.conn.execute( + """ + SELECT id + FROM capture_sessions + WHERE session_hash IS NULL + OR session_hash_version IS NULL + ORDER BY id + """ + ).fetchall() + + for session in sessions: + session_hash = self._calculate_session_hash( + session["id"] + ) + + self.conn.execute( + """ + UPDATE capture_sessions + SET + session_hash=?, + session_hash_version=1 + WHERE id=? + """, + ( + session_hash, + session["id"] + ) + ) + + self.conn.commit() + + except Exception: + self.conn.rollback() + raise + + def _migrate_gps_track( + self + ): + columns = self.conn.execute( + """ + PRAGMA table_info(gps_track) + """ + ).fetchall() + + column_names = { + column[1] + for column in columns + } + + if "sequence_no" in column_names: + return + + self.conn.execute( + """ + ALTER TABLE gps_track + ADD COLUMN sequence_no INTEGER + """ + ) + + sessions = self.conn.execute( + """ + SELECT DISTINCT session_id + FROM gps_track + WHERE session_id IS NOT NULL + ORDER BY session_id + """ + ).fetchall() + + for session in sessions: + rows = self.conn.execute( + """ + SELECT id + FROM gps_track + WHERE session_id=? + ORDER BY id + """, + ( + session["session_id"], + ) + ).fetchall() + + for sequence_no, row in enumerate(rows): + self.conn.execute( + """ + UPDATE gps_track + SET sequence_no=? + WHERE id=? + """, + ( + sequence_no, + row["id"] + ) + ) + + self.conn.commit() + + def _canonical_json( + self, + value + ): + return json.dumps( + value, + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False + ) + + def _calculate_session_hash( + self, + session_id + ): + session = self.conn.execute( + """ + SELECT + start_time, + end_time + FROM capture_sessions + WHERE id=? + """, + (session_id,) + ).fetchone() + + if session is None: + raise ValueError( + f"Capture session not found: {session_id}" + ) + + gps_rows = self.conn.execute( + """ + SELECT + timestamp, + latitude, + longitude + FROM gps_track + WHERE session_id=? + ORDER BY + sequence_no + """, + (session_id,) + ).fetchall() + + handshakes = self.conn.execute( + """ + SELECT + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + FROM handshakes + JOIN access_points + ON access_points.id=handshakes.access_point_id + WHERE handshakes.session_id=? + ORDER BY + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + """, + (session_id,) + ).fetchall() + + handshake_data = [ + [ + row["bssid"], + row["type"], + row["hash22000"], + row["message_pair"], + row["captured_at"] + ] + for row in handshakes + ] + + if gps_rows: + gps_data = [ + [ + row["timestamp"], + row["latitude"], + row["longitude"] + ] + for row in gps_rows + ] + + canonical = [ + "GPS_SESSION_V1", + gps_data, + handshake_data + ] + + else: + observation_rows = self.conn.execute( + """ + SELECT + observations.observed_at, + access_points.bssid + FROM access_point_observations AS observations + JOIN access_points + ON access_points.id=observations.access_point_id + WHERE observations.session_id=? + ORDER BY + observations.observed_at, + access_points.bssid + """, + (session_id,) + ).fetchall() + + observation_data = [ + [ + row["observed_at"], + row["bssid"] + ] + for row in observation_rows + ] + + canonical = [ + "NON_GPS_SESSION_V1", + session["start_time"], + session["end_time"], + observation_data, + handshake_data + ] + + payload = self._canonical_json( + canonical + ).encode( + "utf-8" + ) + + return hashlib.sha256( + payload + ).hexdigest() + + # ========================================================= + # Capture sessions + # ========================================================= + + + def create_session( + self, + capture_file + ): + + + cursor = self.conn.execute( + """ + INSERT INTO capture_sessions + ( + start_time, + capture_file + ) + + VALUES (?,?) + """, + + ( + datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ), + capture_file + ) + ) + + return cursor.lastrowid + + def begin( + self + ): + + self.conn.execute( + "BEGIN" + ) + + + def commit( + self + ): + + self.conn.commit() + + + def rollback( + self + ): + + self.conn.rollback() + + def close_session( + self, + session_id + ): + + + self.conn.execute( + """ + UPDATE capture_sessions + + SET end_time=? + + WHERE id=? + """, + + ( + datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ), + session_id + ) + ) + + + def finalize_session( + self, + session_id + ): + gps_count = self.conn.execute( + """ + SELECT COUNT(*) + FROM gps_track + WHERE session_id=? + """, + (session_id,) + ).fetchone()[0] + + observation_count = self.conn.execute( + """ + SELECT COUNT(*) + FROM access_point_observations + WHERE session_id=? + """, + (session_id,) + ).fetchone()[0] + + handshake_count = self.conn.execute( + """ + SELECT COUNT(*) + FROM handshakes + WHERE session_id=? + """, + (session_id,) + ).fetchone()[0] + + if ( + gps_count == 0 + and observation_count == 0 + and handshake_count == 0 + ): + self.conn.execute( + """ + DELETE FROM capture_sessions + WHERE id=? + """, + (session_id,) + ) + + logging.getLogger("project-wifi").info( + "Session %s marked for removal during finalization: " + "no GPS points, no AP observations, no handshakes/PMKID", + session_id + ) + + return False + + self.close_session(session_id) + + session_hash = self._calculate_session_hash( + session_id + ) + + self.conn.execute( + """ + UPDATE capture_sessions + SET + session_hash=?, + session_hash_version=1 + WHERE id=? + """, + ( + session_hash, + session_id + ) + ) + + logging.getLogger("project-wifi").info( + "Session hash created: session_id=%s, version=1, hash=%s", + session_id, + session_hash + ) + + return True + + + # ========================================================= + # Access points + # ========================================================= + + + def get_or_create_access_point( + self, + data + ): + + + bssid = data["bssid"] + + cursor = self.conn.execute( + """ + SELECT id + + FROM access_points + + WHERE bssid=? + """, + + ( + bssid, + ) + ) + + row = cursor.fetchone() + + + + now = data.get( + "timestamp" + ) + + if hasattr(now, "isoformat"): + now = now.isoformat() + + + + if row: + + + ap_id = row["id"] + + current = self.conn.execute( + """ + SELECT * + + FROM access_points + + WHERE id=? + """, + + ( + ap_id, + ) + ).fetchone() + + essid = data.get("essid") or current["essid"] + + encryption = ( + data.get("encryption") + or current["encryption"] + ) + + cipher = ( + data.get("cipher") + or current["cipher"] + ) + + akm = ( + data.get("akm") + or current["akm"] + ) + + country = ( + data.get("country") + or current["country"] + ) + + channel = ( + data.get("channel") + or current["channel"] + ) + + frequency = ( + data.get("frequency") + or current["frequency"] + ) + + vendor = ( + data.get("vendor") + or current["vendor"] + ) + + + incoming_latitude = data.get( + "latitude" + ) + + incoming_longitude = data.get( + "longitude" + ) + + current_latitude = current["last_latitude"] + + current_longitude = current["last_longitude"] + + current_has_coordinates = ( + current_latitude is not None + and current_longitude is not None + and current_latitude != 0 + and current_longitude != 0 + ) + + incoming_has_coordinates = ( + incoming_latitude is not None + and incoming_longitude is not None + and incoming_latitude != 0 + and incoming_longitude != 0 + ) + + if ( + not current_has_coordinates + and incoming_has_coordinates + ): + aggregate_latitude = incoming_latitude + aggregate_longitude = incoming_longitude + + else: + aggregate_latitude = current_latitude + aggregate_longitude = current_longitude + + + changed = ( + + essid != current["essid"] + + or encryption != current["encryption"] + + or cipher != current["cipher"] + + or akm != current["akm"] + + or country != current["country"] + + or channel != current["channel"] + + or frequency != current["frequency"] + + or vendor != current["vendor"] + + or data.get("rssi") != current["last_rssi"] + + or aggregate_latitude != current["last_latitude"] + + or aggregate_longitude != current["last_longitude"] + + or data.get("speed") != current["last_speed"] + + ) + + + if changed: + + self.conn.execute( + """ + UPDATE access_points + + SET + + essid=?, + + encryption=?, + + cipher=?, + + akm=?, + + country=?, + + channel=?, + + frequency=?, + + vendor=?, + + last_seen=?, + + times_seen=times_seen+1, + + last_rssi=?, + + last_latitude=?, + + last_longitude=?, + + last_speed=? + + WHERE id=? + """, + + ( + + essid, + + encryption, + + cipher, + + akm, + + country, + + channel, + + frequency, + + vendor, + + now, + + data.get("rssi"), + + aggregate_latitude, + + aggregate_longitude, + + data.get("speed"), + + ap_id + + ) + ) + + else: + + self.conn.execute( + """ + UPDATE access_points + + SET + + last_seen=?, + + times_seen=times_seen+1 + + WHERE id=? + """, + + ( + + now, + + ap_id + + ) + ) + + + else: + + + cursor = self.conn.execute( + """ + INSERT INTO access_points + + ( + + bssid, + + essid, + + encryption, + + cipher, + + akm, + + country, + + channel, + + frequency, + + vendor, + + first_seen, + + last_seen, + + last_rssi, + + last_latitude, + + last_longitude, + + last_speed + + ) + + + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + + """, + + ( + + data.get("bssid"), + + data.get("essid"), + + data.get("encryption"), + + data.get("cipher"), + + data.get("akm"), + + data.get("country"), + + data.get("channel"), + + data.get("frequency"), + + data.get("vendor"), + + now, + + now, + + data.get("rssi"), + + data.get("latitude"), + + data.get("longitude"), + + data.get("speed") + + ) + ) + + + ap_id = cursor.lastrowid + + return ap_id + + def get_access_point_by_bssid( + self, + bssid + ): + + cursor = self.conn.execute( + """ + SELECT + + id, + + essid, + + encryption, + + cipher, + + akm, + + country, + + channel, + + frequency, + + vendor + + FROM access_points + + WHERE bssid=? + """, + + ( + bssid, + ) + ) + + row = cursor.fetchone() + + return row + + def handshake_exists( + self, + access_point_id, + session_id, + hash22000 + ): + + cursor = self.conn.execute( + """ + SELECT id + + FROM handshakes + + WHERE + + access_point_id=? + + AND + + session_id=? + + AND + + hash22000=? + + LIMIT 1 + """, + + ( + access_point_id, + session_id, + hash22000 + ) + ) + + return cursor.fetchone() is not None + + # ========================================================= + # Handshakes / PMKID + # ========================================================= + + + def add_handshake( + self, + data + ): + + + try: + + + self.conn.execute( + """ + INSERT INTO handshakes + + ( + + access_point_id, + + session_id, + + type, + + hash22000, + + message_pair, + + captured_at, + + latitude, + + longitude, + + speed + + ) + + + VALUES (?,?,?,?,?,?,?,?,?) + + """, + + ( + + data["access_point_id"], + + data.get("session_id"), + + data["type"], + + data.get("hash22000"), + + data.get("message_pair"), + + data.get("captured_at"), + + data.get("latitude"), + + data.get("longitude"), + + data.get("speed") + + ) + ) + + + + if data["type"] == "PMKID": + + + self.conn.execute( + """ + UPDATE access_points + + SET has_pmkid=1 + + WHERE id=? + + """, + + ( + data["access_point_id"], + ) + ) + + + + if data["type"] == "EAPOL": + + + self.conn.execute( + """ + UPDATE access_points + + SET has_handshake=1 + + WHERE id=? + + """, + + ( + data["access_point_id"], + ) + ) + + + + return True + + + except sqlite3.IntegrityError: + + + return False + + + + # ========================================================= + # Credentials / hashcat + # ========================================================= + + + def add_credential( + self, + access_point_id, + password, + source="hashcat" + ): + + + self.conn.execute( + """ + INSERT OR IGNORE INTO credentials + + ( + + access_point_id, + + password, + + source, + + created_at + + ) + + VALUES (?,?,?,?) + + """, + + ( + + access_point_id, + + password, + + source, + + datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ) + + ) + ) + + + + self.conn.execute( + """ + UPDATE access_points + + SET is_cracked=1 + + WHERE id=? + + """, + + ( + access_point_id, + ) + ) + + + def credential_exists( + self, + access_point_id, + password + ): + + cursor = self.conn.execute( + """ + SELECT id + + FROM credentials + + WHERE + + access_point_id=? + + AND + + password=? + + """, + + ( + access_point_id, + password + ) + ) + + return cursor.fetchone() is not None + + + # ========================================================= + # Hashcat + # ========================================================= + + def add_credential_by_hash( + self, + hash22000, + password + ): + + access_point_id = self.get_access_point_by_hash( + hash22000 + ) + + if access_point_id is None: + + return False + + + if self.credential_exists( + + access_point_id, + + password + + ): + + return False + + + self.add_credential( + + access_point_id=access_point_id, + + password=password, + + source="hashcat" + + ) + + return True + + # ========================================================= + # Access point observations + # ========================================================= + + def add_observation( + self, + access_point_id, + session_id, + data + ): + + """ + Добавляет одно наблюдение точки доступа. + + Каждая запись соответствует одному + обнаружению точки доступа во время + обработки access_points.csv. + """ + + + observed_at = data.get( + "timestamp" + ) + + + if hasattr( + observed_at, + "isoformat" + ): + + observed_at = observed_at.isoformat() + + + self.observation_buffer.append( + + ( + + access_point_id, + + session_id, + + observed_at, + + data.get( + "latitude" + ), + + data.get( + "longitude" + ), + + data.get( + "speed" + ), + + data.get( + "rssi" + ), + + data.get( + "channel" + ), + + data.get( + "frequency" + ), + + data.get( + "essid" + ), + + data.get( + "encryption" + ), + + data.get( + "cipher" + ), + + data.get( + "akm" + ), + + data.get( + "country" + ) + + ) + + ) + + + if ( + + len( + self.observation_buffer + ) + + >= + + self.observation_batch_size + + ): + + self.flush_observations() + + def flush_observations( + self + ): + + if not self.observation_buffer: + + return + + + self.conn.executemany( + """ + INSERT INTO access_point_observations + ( + + access_point_id, + + session_id, + + observed_at, + + latitude, + + longitude, + + speed, + + rssi, + + channel, + + frequency, + + essid, + + encryption, + + cipher, + + akm, + + country + + ) + + VALUES + ( + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + ) + """, + + self.observation_buffer + ) + + + self.observation_buffer.clear() + + # ========================================================= + # Полная регистрация наблюдения точки доступа + # ========================================================= + + def record_access_point_observation( + self, + session_id, + data + ): + + """ + Полностью обрабатывает одно наблюдение + точки доступа. + + Метод: + + • создает новую точку доступа + при необходимости; + + • обновляет агрегированную карточку; + + • сохраняет историю наблюдений. + """ + + + access_point_id = ( + self.get_or_create_access_point( + data + ) + ) + + + self.add_observation( + + access_point_id=access_point_id, + + session_id=session_id, + + data=data + + ) + + if ( + + len( + self.observation_buffer + ) + + >= + + self.observation_batch_size + + ): + + self.flush_observations() + + return access_point_id + + + # ========================================================= + # GPS + # ========================================================= + + + def add_gps_point( + self, + session_id, + gps + ): + + + sequence_no = self.conn.execute( + """ + SELECT + COALESCE( + MAX(sequence_no), + -1 + ) + 1 + FROM gps_track + WHERE session_id=? + """, + ( + session_id, + ) + ).fetchone()[0] + + + self.conn.execute( + """ + INSERT INTO gps_track + + ( + + session_id, + + sequence_no, + + latitude, + + longitude, + + speed, + + timestamp + + ) + + VALUES (?,?,?,?,?,?) + + """, + + + ( + + session_id, + + sequence_no, + + gps.latitude, + + gps.longitude, + + gps.speed, + + gps.timestamp.isoformat().replace( + "+00:00", + "Z" + ) + + ) + ) + + + # ========================================================= + # Close + # ========================================================= + + + def close(self): + + self.flush_observations() + + self.conn.commit() + + self.conn.close() \ No newline at end of file diff --git a/src/environment.py b/src/environment.py new file mode 100644 index 0000000..1a50d8c --- /dev/null +++ b/src/environment.py @@ -0,0 +1,314 @@ +import os +import subprocess +import logging +import sqlite3 +import csv + +from vendor_import import VendorImporter + +class EnvironmentChecker: + """ + Проверка окружения проекта. + + Проверяются: + + - наличие необходимых каталогов; + - наличие бинарных файлов; + - права на выполнение; + - версия hcxdumptool; + - наличие базы производителей. + + Основная база проекта не проверяется, + так как она может быть создана автоматически + при первом запуске. + """ + + + def __init__( + self, + config + ): + + self.config = config + + self.log = logging.getLogger( + "environment" + ) + + + + # --------------------------------------------------------- + # Главная проверка + # --------------------------------------------------------- + + def check(self): + + self.log.info( + "Checking application environment..." + ) + + + self.check_binary( + self.config.hcxdumptool, + "hcxdumptool" + ) + + + self.check_binary( + self.config.hcxpcapngtool, + "hcxpcapngtool" + ) + + + self.check_hcxdumptool_version() + + + self.check_vendor_database() + + + self.log.info( + "Environment OK" + ) + + + + # --------------------------------------------------------- + # Проверка бинарника + # --------------------------------------------------------- + + def check_binary( + self, + path, + name + ): + + if not path.exists(): + + raise RuntimeError( + + f"{name} not found:\n\n{path}" + + ) + + + if not path.is_file(): + + raise RuntimeError( + + f"{name} is not a file:\n\n{path}" + + ) + + + if not os.access( + path, + os.X_OK + ): + + raise RuntimeError( + + f"{name} is not executable:\n\n" + f"{path}\n\n" + f"Run:\n" + f"chmod +x {path}" + + ) + + + self.log.info( + f"{name}: OK" + ) + + + + # --------------------------------------------------------- + # Проверка версии hcxdumptool + # --------------------------------------------------------- + + def check_hcxdumptool_version(self): + + result = subprocess.run( + + [ + str( + self.config.hcxdumptool + ), + "--help" + ], + + capture_output=True, + + text=True + + ) + + + output = ( + result.stdout + + + result.stderr + ) + + + if "7." not in output: + + raise RuntimeError( + + "Unsupported hcxdumptool version.\n" + "Version 7.x is required." + + ) + + + self.log.info( + "hcxdumptool version: OK" + ) + + + + # --------------------------------------------------------- + # Проверка базы производителей + # --------------------------------------------------------- + + def check_vendor_database(self): + + database = self.config.vendor_database + + rebuild = False + + if not database.exists(): + + self.log.warning( + "Vendor database not found" + ) + + rebuild = True + + elif database.stat().st_size == 0: + + self.log.warning( + "Vendor database is empty" + ) + + rebuild = True + + else: + + try: + + connection = sqlite3.connect( + database + ) + + cursor = connection.cursor() + + cursor.execute( + "SELECT name FROM sqlite_master " + "WHERE type='table' " + "AND name='oui'" + ) + + if cursor.fetchone() is None: + + raise RuntimeError( + "vendors table not found" + ) + + cursor.execute( + + "SELECT COUNT(*) FROM oui" + + ) + + records = cursor.fetchone()[0] + + if records < 50000: + + raise RuntimeError( + + f"Only {records} records" + + ) + + cursor.execute( + + "SELECT value " + "FROM metadata " + "WHERE key='import_status'" + + ) + + row = cursor.fetchone() + + if ( + + row is None + + or + + row[0] != "ok" + + ): + + raise RuntimeError( + + "Invalid import_status" + + ) + + connection.close() + + self.log.info( + + f"Vendor database: OK ({records} records)" + + ) + + return + + except KeyboardInterrupt: + + self.log.warning( + "Download cancelled by user" + ) + + raise + + except Exception as error: + + self.log.warning( + + f"Vendor database is invalid: {error}" + + ) + + rebuild = True + + if rebuild: + + database.unlink( + missing_ok=True + ) + + self.log.info( + "Creating vendor database..." + ) + + importer = VendorImporter( + self.config + ) + + importer.bootstrap() + + if not database.exists(): + + raise RuntimeError( + + "Unable to create vendor database." + + ) + + self.log.info( + "Vendor database created" + ) + diff --git a/src/gps.py b/src/gps.py new file mode 100644 index 0000000..8dcc53a --- /dev/null +++ b/src/gps.py @@ -0,0 +1,480 @@ +import socket +import threading +import select +import os +import termios +import logging +import subprocess +import pynmea2 + +from datetime import datetime, timezone + +from models import GPSData + + +class GPSRelaySource: + + def __init__(self, host, port): + + self.host = host + self.port = port + + self.socket = None + + + def open(self): + + self.socket = socket.create_connection( + ( + self.host, + self.port + ) + ) + + return self.socket.makefile() + + + def close(self): + + if self.socket: + + self.socket.close() + + +class GpsdSource: + + def __init__(self, host="127.0.0.1", port=2947): + + self.host = host + self.port = port + + self.socket = None + + + def open(self): + + self.socket = socket.create_connection( + ( + self.host, + self.port + ) + ) + + file = self.socket.makefile() + + file.readline() + + self.socket.sendall( + b'?WATCH={"enable":true,"json":false,"nmea":true};\n' + ) + + return file + + + def close(self): + + if self.socket: + + self.socket.close() + + +class SerialSource: + + def __init__(self, device): + + self.device = device + + self.fd = None + + self.lock = threading.Lock() + + + def open(self): + + self.fd = os.open( + self.device, + os.O_RDWR | os.O_NOCTTY + ) + + attributes = termios.tcgetattr( + self.fd + ) + + attributes[0] = 0 + attributes[1] = 0 + attributes[2] = ( + termios.CLOCAL | + termios.CREAD | + termios.CS8 + ) + attributes[3] = 0 + + attributes[4] = termios.B9600 + attributes[5] = termios.B9600 + + attributes[6][ + termios.VMIN + ] = 0 + + attributes[6][ + termios.VTIME + ] = 5 + + termios.tcsetattr( + self.fd, + termios.TCSANOW, + attributes + ) + + return self + + + def readline(self): + + with self.lock: + + buffer = b"" + + while True: + + ready, _, _ = select.select( + [self.fd], + [], + [], + 0.5 + ) + + if not ready: + return "" + + data = os.read( + self.fd, + 1 + ) + + if not data: + return "" + + buffer += data + + if data == b"\n": + return buffer.decode( + errors="replace" + ) + + + def close(self): + + with self.lock: + + if self.fd is not None: + + os.close( + self.fd + ) + + self.fd = None + +class ModemGNSSSource: + + def __init__( + self, + device, + at_device + ): + + self.device = device + self.at_device = at_device + + self.serial = SerialSource( + device + ) + + + def send_at(self, command): + + result = subprocess.run( + [ + "sudo", + "-n", + "atinout", + "-", + self.at_device, + "-" + ], + input=command + "\r\n", + text=True, + capture_output=True, + timeout=10 + ) + + if result.returncode != 0: + + raise RuntimeError( + "AT command failed: " + + result.stderr.strip() + ) + + return result.stdout + + + def ensure_gnss_enabled(self): + + response = self.send_at( + "AT+QGPS?" + ) + + if "+QGPS: 1" not in response: + + self.send_at( + "AT+QGPS=1" + ) + + response = self.send_at( + "AT+QGPS?" + ) + + if "+QGPS: 1" not in response: + + raise RuntimeError( + "GNSS did not start." + ) + + + def open(self): + + self.ensure_gnss_enabled() + + return self.serial.open() + + + def readline(self): + + return self.serial.readline() + + + def close(self): + + self.serial.close() + + +def create_gps_source(cfg): + + if cfg.gps_source == "gpsrelay": + + return GPSRelaySource( + cfg.gpsrelay_host, + cfg.gpsrelay_port + ) + + if cfg.gps_source == "gnss": + + if cfg.gnss_handler == "gpsd": + + return GpsdSource() + + if cfg.gnss_handler == "modem": + + return ModemGNSSSource( + cfg.gnss_device, + cfg.gnss_at_device + ) + + if cfg.gnss_handler == "direct": + + return SerialSource( + cfg.gnss_device + ) + + raise ValueError( + f"Unknown GNSS handler: {cfg.gnss_handler}" + ) + + raise ValueError( + f"Unknown GPS source: {cfg.gps_source}" + ) + + +def parse_nmea( + line, + received +): + + if not line.startswith("$"): + + return None + + try: + msg = pynmea2.parse( + line + ) + + except Exception: + + return None + + message_type = getattr( + msg, + "sentence_type", + "" + ) + + if message_type == "RMC": + + if msg.status != "A": + return None + + speed = float( + msg.spd_over_grnd or 0 + ) + + elif message_type == "GNS": + + mode = getattr( + msg, + "mode_indicator", + "" + ) + + if not mode or mode[0] == "N": + return None + + speed = 0 + + else: + return None + + try: + + return GPSData( + latitude=msg.latitude, + longitude=msg.longitude, + speed=speed, + timestamp=received, + valid=True + ) + + except (TypeError, ValueError): + return None + + +class GPSManager: + + def __init__(self, source, session): + + self.source = source + + self.session = session + + self.current = None + + self.running = False + + self.thread = None + + self.log = logging.getLogger("gps") + + + def start(self): + + self.running = True + + self.thread = threading.Thread( + target=self.worker, + daemon=True + ) + + self.thread.start() + + + def parse_nmea( + self, + line, + received + ): + + gps = parse_nmea( + line, + received + ) + + if gps is None: + return + + self.current = gps + self.session.update_gps( + gps + ) + + + def worker(self): + + file = None + + try: + + file = self.source.open() + + self.log.info( + "GPS connection established" + ) + + with open( + self.session.gps_file, + "a" + ) as gps_log: + + while self.running: + + if hasattr( + self.source, + "readline" + ): + + line = self.source.readline() + + else: + + line = file.readline() + + if not line: + continue + + received = datetime.now( + timezone.utc + ) + + gps_log.write( + f"{received.isoformat().replace('+00:00', 'Z')};{line}" + ) + + gps_log.flush() + + self.session.add_nmea() + + self.parse_nmea( + line, + received + ) + + except Exception as error: + + self.log.error( + f"GPS error: {error}" + ) + + finally: + + self.source.close() + + + def get(self): + + return self.current + + + def stop(self): + + self.running = False + + self.source.close() diff --git a/src/gps_test.py b/src/gps_test.py new file mode 100644 index 0000000..bf2805d --- /dev/null +++ b/src/gps_test.py @@ -0,0 +1,291 @@ +import threading +import time + +from datetime import datetime, timezone + +from gps import create_gps_source, parse_nmea + + +class GPSTestService: + + def __init__( + self, + cfg, + callback=None + ): + + self.cfg = cfg + self.callback = callback + + self.thread = None + self.stop_event = threading.Event() + + self.running = False + self.state = "READY" + + self.nmea_received = False + self.fix_received = False + + self.nmea_count = 0 + self.fix_count = 0 + + self.latitude = None + self.longitude = None + + self.error = None + + + def emit(self, message): + + if self.callback: + self.callback(message) + + + def start(self): + + if ( + self.thread is not None + and + self.thread.is_alive() + ): + return False + + self.stop_event.clear() + + self.running = True + self.state = "STARTING" + self.nmea_received = False + self.fix_received = False + self.nmea_count = 0 + self.fix_count = 0 + self.latitude = None + self.longitude = None + self.error = None + + self.thread = threading.Thread( + target=self.worker, + daemon=True + ) + + self.thread.start() + + return True + + + def stop(self): + + self.stop_event.set() + + + def worker(self): + + source = None + file = None + + try: + + self.emit( + "[GPS TEST] Starting GPS test " + "from saved configuration." + ) + + source = create_gps_source( + self.cfg + ) + + self.emit( + "[GPS TEST] Connecting to GPS source..." + ) + + file = source.open() + + self.state = "CONNECTED" + + self.emit( + "[GPS TEST] GPS source connected. " + "Waiting for NMEA..." + ) + + last_no_fix_message = 0 + + while not self.stop_event.is_set(): + + if hasattr( + source, + "readline" + ): + + line = source.readline() + + else: + + line = file.readline() + + if not line: + continue + + self.nmea_count += 1 + self.nmea_received = True + + if self.state == "CONNECTED": + + self.state = "NMEA" + + self.emit( + "[GPS TEST] NMEA received. " + "Waiting for valid FIX..." + ) + + received = datetime.now( + timezone.utc + ) + + gps = parse_nmea( + line, + received + ) + + if gps is not None: + + first_fix = not self.fix_received + + self.fix_count += 1 + self.fix_received = True + self.state = "FIX" + self.latitude = gps.latitude + self.longitude = gps.longitude + + self.emit( + "[GPS TEST] FIX received: " + f"lat={gps.latitude:.6f} " + f"lon={gps.longitude:.6f}" + ) + + if first_fix: + + self.emit( + "[GPS TEST] GPS is ready " + "for scanning." + ) + + elif self.fix_count % 10 == 0: + + self.emit( + "[GPS TEST] GPS is ready " + "for scanning. " + f"FIX: lat={gps.latitude:.6f} " + f"lon={gps.longitude:.6f}" + ) + + elif ( + self.nmea_received + and + not self.fix_received + and + self.nmea_count % 10 == 0 + and + time.monotonic() - last_no_fix_message >= 5 + ): + + last_no_fix_message = ( + time.monotonic() + ) + + self.emit( + "[GPS TEST] GPS is not ready: " + "NMEA received, but no valid FIX yet. " + f"NMEA: {self.nmea_count}" + ) + + except Exception as error: + + self.state = "ERROR" + self.error = str(error) + + self.emit( + f"[GPS TEST] GPS source error: {error}" + ) + + finally: + + if source is not None: + + try: + source.close() + + except Exception as error: + + self.emit( + f"[GPS TEST] Close error: {error}" + ) + + self.running = False + + if self.state != "ERROR": + + self.state = "STOPPED" + + self.emit( + "[GPS TEST] Test stopped." + ) + + +def run_gps_test(cfg): + + def output(message): + + print( + message, + flush=True + ) + + service = GPSTestService( + cfg, + callback=output + ) + + service.start() + + try: + + while service.running: + + time.sleep(0.2) + + except KeyboardInterrupt: + + print( + "[GPS TEST] Test interrupted by user.", + flush=True + ) + + if service.fix_received: + + print( + "[GPS TEST] Result: " + "GPS is ready for scanning.", + flush=True + ) + + print( + "[GPS TEST] Last position: " + f"lat={service.latitude:.6f} " + f"lon={service.longitude:.6f}", + flush=True + ) + + else: + + print( + "[GPS TEST] Result: " + "GPS is not ready for scanning.", + flush=True + ) + + service.stop() + + while service.running: + + time.sleep(0.1) + + return 0 if service.fix_received else 1 \ No newline at end of file diff --git a/src/logger.py b/src/logger.py new file mode 100644 index 0000000..631354f --- /dev/null +++ b/src/logger.py @@ -0,0 +1,52 @@ +import logging +from pathlib import Path + + + +def setup_logger(): + + + Path( + "logs" + ).mkdir( + exist_ok=True + ) + + + + logging.basicConfig( + + + level=logging.INFO, + + + format=( + + "%(asctime)s " + "[%(levelname)s] " + "%(name)s: " + "%(message)s" + + ), + + + handlers=[ + + + logging.FileHandler( + "logs/project.log" + ), + + + logging.StreamHandler() + + ] + + + ) + + + + return logging.getLogger( + "project-wifi" + ) \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..8593a27 --- /dev/null +++ b/src/main.py @@ -0,0 +1,496 @@ +import signal +import sys +import time +import logging + + +from config import Config +from database import Database +from gps import GPSManager, create_gps_source +from gps_test import run_gps_test +from logger import setup_logger +from network import NetworkManagerControl +from wifi import WiFiManager +from session import Session +from environment import EnvironmentChecker +from sudo import SudoChecker + + +# ============================================================ +# Инициализация +# ============================================================ + + +cfg = Config() + + +if "--gps-test" in sys.argv: + + sudo_checker = SudoChecker() + + sudo_checker.check() + + sys.exit( + run_gps_test( + cfg + ) + ) + +logger = setup_logger() + + +logger.info( + "Project started" +) + + +# ============================================================ +# Проверка окружения +# ============================================================ + +try: + + environment = EnvironmentChecker( + cfg + ) + + environment.check() + + sudo_checker = SudoChecker() + + sudo_checker.check() + + cfg.select_interface() + + logger.info( + f"WiFi interface: {cfg.interface}" + ) + +except KeyboardInterrupt: + + logger.info( + "Startup cancelled" + ) + + sys.exit(0) + +# ============================================================ +# Network +# ============================================================ + + +network = NetworkManagerControl( + cfg.interface +) + +wifi = None + +gps = None + +session = None + +db = None + +parser = None + +session_id = None + +network_prepared = False + +shutdown_requested = False + +scanner_state = "READY" + +def set_scanner_state(state): + + global scanner_state + + if scanner_state == state: + return + + scanner_state = state + + print( + f"ScannerState: {state}", + flush=True + ) + + +def shutdown(signum=None, frame=None): + + global shutdown_requested + global network_prepared + + if shutdown_requested: + return + + shutdown_requested = True + + set_scanner_state( + "STOPPED" + ) + + logger.info( + "Shutdown requested" + ) + + + try: + + if wifi: + + wifi.stop() + + + except Exception as error: + + logger.error( + f"WiFi stop error: {error}" + ) + + try: + + if parser and session: + + parser.parse( + session, + session_id + ) + + + except Exception as error: + + logger.error( + f"Parser error: {error}" + ) + + try: + + if gps: + + gps.stop() + + + except Exception as error: + + logger.error( + f"GPS stop error: {error}" + ) + + + + try: + + if (db and session_id is not None): + + db.flush_observations() + + db.finalize_session( + session_id + ) + + db.commit() + + except Exception as error: + + logger.error( + f"Database finalize error: {error}" + ) + + + + try: + + if network_prepared: + + network.restore() + + + except Exception as error: + + logger.error( + f"Network restore error: {error}" + ) + + + + try: + + if db: + + db.close() + + + except Exception: + + pass + + + + logger.info( + "Project stopped" + ) + + + + sys.exit(0) + + +signal.signal( + signal.SIGINT, + shutdown +) + +signal.signal( + signal.SIGTERM, + shutdown +) + +from parser import CaptureParser + +# ============================================================ +# Подготовка оборудования +# ============================================================ + + +try: + + network_prepared = True + + network.prepare() + + # ============================================================ + # Сессия + # ============================================================ + + session = Session( + cfg.capture_directory + ) + + logger.info( + f"Session directory: {session.path}" + ) + + logger.info( + f"Capture file: {session.capture_file}" + ) + + logger.info( + f"GPS track: {session.gps_file}" + ) + + + # ============================================================ + # Database + # ============================================================ + + db = Database( + cfg.database + ) + + logger.info( + "SQLite initialized" + ) + + parser = CaptureParser( + cfg, + db + ) + + session_id = db.create_session( + str(session.capture_file) + ) + + session.id = session_id + + wifi = WiFiManager( + cfg, + session, + cfg.interface + ) + + gps_source = create_gps_source( + cfg + ) + + gps = GPSManager( + gps_source, + session + ) + + wifi.start() + + gps.start() + + set_scanner_state( + "ACTIVE" + ) + + +except KeyboardInterrupt: + + logger.info( + "Startup cancelled" + ) + + shutdown() + +except Exception as error: + + logger.error( + f"Startup error: {error}" + ) + + shutdown() + + +# ============================================================ +# Главный цикл +# ============================================================ + + +last_status = 0 + +last_capture_size = 0 + +capture_stall_count = 0 + +last_sudo_keepalive = time.time() + +sudo_keepalive_interval = 60 + + +while True: + + + now = time.time() + + if ( + now - last_sudo_keepalive + >= sudo_keepalive_interval + ): + + if sudo_checker.refresh(): + + logger.debug( + "Sudo keepalive: OK" + ) + + else: + + logger.warning( + "WARNING: sudo keepalive failed" + ) + + last_sudo_keepalive = now + + + if wifi and wifi.process: + + return_code = wifi.process.poll() + + if return_code is not None: + + if return_code == 0: + + logger.info( + "hcxdumptool finished" + ) + + else: + + logger.error( + f"hcxdumptool exited with code {return_code}" + ) + + shutdown() + + + + if ( now - last_status >= cfg.status_interval ): + capture_bytes = 0 + try: + capture_bytes = ( session.capture_file.stat().st_size ) + except Exception: + pass + + # + # контроль роста capture.pcapng + # + if last_capture_size: + if capture_bytes <= last_capture_size: + capture_stall_count += 1 + else: + capture_stall_count = 0 + + last_capture_size = capture_bytes + capture_size = ( capture_bytes / 1024 ) + capture_text = ( f"{capture_size:.1f}KB") + + + + pid = "-" + + if wifi and wifi.process: + + pid = wifi.process.pid + + gps_data = session.current_gps + + + + if gps_data: + + + logger.info( + + "Status: " + f"elapsed={session.elapsed()}s " + f"nmea={session.nmea_messages} " + f"gps={session.gps_positions} " + f"lat={gps_data.latitude:.6f} " + f"lon={gps_data.longitude:.6f} " + f"capture={capture_text} " + f"pid={pid}" + + ) + + + + else: + + + logger.info( + + "Status: " + f"elapsed={session.elapsed()}s " + f"nmea={session.nmea_messages} " + f"gps={session.gps_positions} " + f"capture={capture_text} " + f"pid={pid} " + "gps=no signal" + + ) + + + + + last_status = now + + if capture_stall_count >= 3: + + logger.warning( + "WARNING: capture file is not growing" + ) + + set_scanner_state( + "WARNING" + ) + + else: + + set_scanner_state( + "ACTIVE" + ) + + time.sleep(1) \ No newline at end of file diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..c387234 --- /dev/null +++ b/src/models.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +from datetime import datetime + + +@dataclass +class GPSData: + latitude: float + longitude: float + speed: float + timestamp: datetime + valid: bool diff --git a/src/network.py b/src/network.py new file mode 100644 index 0000000..9dd297e --- /dev/null +++ b/src/network.py @@ -0,0 +1,210 @@ +import logging +import subprocess + + +class NetworkManagerControl: + + + def __init__(self, interface): + + self.interface = interface + + self.log = logging.getLogger( + "network" + ) + + + self.restore_networkmanager = False + + self.restore_wpa = False + + + + def _run(self, command): + + subprocess.run( + [ + "sudo", + "-n" + ] + + + command, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + + + + def _is_active(self, service): + + + result = subprocess.run( + + [ + "systemctl", + "is-active", + service + ], + + capture_output=True, + + text=True + + ) + + + return ( + result.stdout.strip() + == + "active" + ) + + + + def prepare(self): + + + self.restore_networkmanager = self._is_active( + "NetworkManager" + ) + + + self.restore_wpa = self._is_active( + "wpa_supplicant" + ) + + + + self.log.info( + f"NetworkManager : {'running' if self.restore_networkmanager else 'stopped'}" + ) + + + self.log.info( + f"wpa_supplicant : {'running' if self.restore_wpa else 'stopped'}" + ) + + + + if self.restore_networkmanager: + + + self._run( + [ + "systemctl", + "stop", + "NetworkManager" + ] + ) + + + + if self.restore_wpa: + + + self._run( + [ + "systemctl", + "stop", + "wpa_supplicant" + ] + ) + + + + self.log.info( + "Network services stopped" + ) + + + + def restore(self): + + self.log.info( + "Restoring WiFi interface" + ) + + self._run( + [ + "ip", + "link", + "set", + self.interface, + "down" + ] + ) + + self._run( + [ + "iw", + "dev", + self.interface, + "set", + "type", + "managed" + ] + ) + + self._run( + [ + "ip", + "link", + "set", + self.interface, + "up" + ] + ) + + self.log.info( + "WiFi interface restored to managed mode" + ) + + + if self.restore_wpa: + + self._run( + [ + "systemctl", + "start", + "wpa_supplicant" + ] + ) + + + if self.restore_networkmanager: + + self._run( + [ + "systemctl", + "start", + "NetworkManager" + ] + ) + + + if self.restore_networkmanager: + + self._run( + [ + "nmcli", + "device", + "set", + self.interface, + "managed", + "yes" + ] + ) + + self._run( + [ + "nmcli", + "device", + "connect", + self.interface + ] + ) + + + self.log.info( + "Network services restored" + ) \ No newline at end of file diff --git a/src/oui_import.py b/src/oui_import.py new file mode 100644 index 0000000..d5b3494 --- /dev/null +++ b/src/oui_import.py @@ -0,0 +1,229 @@ +import csv +import logging + + +class OUIImporter: + + + def __init__( + self, + resolver, + files + ): + + self.logger = logging.getLogger( + "oui-import" + ) + + self.resolver = resolver + + self.files = files + + + # ===================================================== + # Импорт IEEE + # ===================================================== + + def import_database(self): + + + count = 0 + + skipped = 0 + + + stats = { + + "MA-L": 0, + + "MA-M": 0, + + "MA-S": 0 + + } + + + for filename in self.files: + + + if not filename.exists(): + + self.logger.warning( + f"{filename.name} not found" + ) + + continue + + + self.logger.info( + f"Importing {filename.name}" + ) + + + with open( + + filename, + + "r", + + encoding="utf-8", + + errors="ignore" + + ) as file: + + + reader = csv.DictReader( + file + ) + + + for row in reader: + + + registry = row.get( + "Registry" + ) + + assignment = row.get( + "Assignment" + ) + + organization = row.get( + "Organization Name" + ) + + + if not registry: + + continue + + + if registry not in stats: + + continue + + + if not assignment: + + skipped += 1 + + continue + + + if not organization: + + skipped += 1 + + continue + + + assignment = ( + + assignment + + .replace( + "-", + "" + ) + + .replace( + ":", + "" + ) + + .replace( + ".", + "" + ) + + .strip() + + .upper() + + ) + + + if not all( + + char in "0123456789ABCDEF" + + for char in assignment + + ): + + skipped += 1 + + continue + + + if len( + assignment + ) not in ( + + 6, + + 7, + + 9 + + ): + + skipped += 1 + + continue + + + result = self.resolver.add_vendor( + + assignment, + + organization.strip(), + + registry + + ) + + + if result: + + count += 1 + + stats[ + registry + ] += 1 + + else: + + skipped += 1 + + + self.resolver.commit() + + + total = self.resolver.count() + + + self.logger.info( + f"Imported: {count}" + ) + + self.logger.info( + f"Skipped: {skipped}" + ) + + self.logger.info( + f"Database records: {total}" + ) + + return { + + "imported": count, + + "skipped": skipped, + + "total": total, + + "stats": stats + + } \ No newline at end of file diff --git a/src/parser.py b/src/parser.py new file mode 100644 index 0000000..2f7a96a --- /dev/null +++ b/src/parser.py @@ -0,0 +1,1199 @@ +import subprocess +import logging +import csv + +from datetime import datetime, timedelta, timezone +import pynmea2 +from scapy.all import PcapNgReader +from scapy.layers.dot11 import Dot11 +from scapy.layers.eap import EAPOL +from bisect import bisect_left +from vendor import VendorResolver + +class CaptureParser: + + def __init__( + self, + config, + database + ): + + self.config = config + + self.db = database + + # + # Определение производителей + # + self.vendor = VendorResolver( + self.config.vendor_database + ) + + self.log = logging.getLogger( + "parser" + ) + +# +# GPS трек текущей сессии +# + self.gps_track = [] + +# +# Только временные метки +# Используются для быстрого бинарного поиска +# + self.gps_times = [] + +# +# Индекс найденных EAPOL кадров +# + self.handshake_index = {} + +# +# Соответствие +# BSSID -> access_point_id +# + self.access_point_index = {} + + def setup_session_logger( + self, + session + ): + + handler = logging.FileHandler( + session.parser_log + ) + + formatter = logging.Formatter( + "%(asctime)s [%(levelname)s] %(message)s" + ) + + handler.setFormatter( + formatter + ) + + self.log.addHandler( + handler + ) + + self.log.setLevel( + logging.INFO + ) + + + def parse( + self, + session, + session_id + ): + + self.setup_session_logger( + session + ) + + self.log.info( + "Parser started" + ) + + cmd = [ + + str( + self.config.hcxpcapngtool + ), + + "--csv", + + str( + session.access_points_file + ), + + "-o", + + str( + session.handshakes_file + ), + + "-E", + + str( + session.essid_file + ), + + "-I", + + str( + session.identity_file + ), + + str( + session.capture_file + ) + ] + + + self.log.info( + "Running hcxpcapngtool" + ) + + + self.log.info( + "Command: %s", + " ".join(cmd) + ) + + + subprocess.run( + cmd, + check=True + ) + + + self.log.info( + "hcxpcapngtool finished" + ) + + self.load_gps_track( + session, + session_id + ) + + self.load_handshake_index( + session + ) + + + self.parse_access_points( + session, + session_id + ) + + self.parse_handshakes( + session, + session_id + ) + + + self.log.info( + "Parser finished" + ) + + + def parse_access_points( + self, + session, + session_id + ): + + csv_file = session.access_points_file + + if not csv_file.exists(): + + self.log.warning( + "CSV file not found" + ) + + return + + count = 0 + + self.access_point_index.clear() + + with open( + csv_file, + "r", + encoding="utf-8", + errors="ignore" + ) as file: + + reader = csv.reader( + file, + delimiter="\t" + ) + + for row in reader: + + data = self.parse_csv_row( + row + ) + + if not data: + + continue + + data["session_id"] = session_id + + self.log.debug( + "AP %s -> GPS (%s, %s)", + data["bssid"], + data["latitude"], + data["longitude"] + ) + + access_point_id = ( + self.db.record_access_point_observation( + + session_id=session_id, + + data=data + + ) + ) + + self.access_point_index[ + data["bssid"] + ] = access_point_id + + count += 1 + + self.log.info( + "Imported access points: %s", + count + ) + + def parse_existing( + self, + session, + session_id + ): + + self.setup_session_logger( + session + ) + + self.log.info( + "Parser started (existing files)" + ) + + self.load_gps_track( + session, + session_id + ) + + self.load_handshake_index( + session + ) + + self.parse_access_points( + session, + session_id + ) + + self.parse_handshakes( + session, + session_id + ) + + self.restore_session_times( + session_id + ) + + self.log.info( + "Parser finished" + ) + + def parse_csv_row( + self, + row + ): + + + try: + + if len(row) < 10: + + return None + + timestamp = self.parse_csv_timestamp( + row + ) + + + if timestamp is None: + + return None + + + gps = self.gps_from_timestamp( + timestamp + ) + + vendor = self.vendor.lookup( + row[2] + ) + + + return { + + "bssid": + row[2].lower(), + + + "essid": + row[3], + + + "encryption": + row[4], + + + "cipher": + row[5], + + + "akm": + row[6], + + + "country": + row[7], + + + "vendor": + vendor, + + "channel": + self.to_int( + row[8] + ), + + + "rssi": + self.to_int( + row[9] + ), + + + "timestamp": + timestamp, + + + "latitude": + gps["latitude"], + + + "longitude": + gps["longitude"], + + + "speed": + gps["speed"] + + } + + + except Exception as error: + + self.log.error( + f"CSV parse error: {error}" + ) + + return None + + + def to_int( + self, + value + ): + + try: + + return int(value) + + except Exception: + + return None + + + +# ========================================================= +# Import handshakes.22000 +# ========================================================= + + def parse_csv_timestamp( + self, + row + ): + + """ + Преобразует дату и время + из access_points.csv. + """ + + try: + + return datetime.strptime( + + f"{row[0]} {row[1]}", + + "%Y-%m-%d %H:%M:%S" + + ).replace( + tzinfo=timezone.utc + ) + + except Exception: + + return None + + + def parse_handshakes( + self, + session, + session_id + ): + + + file = session.handshakes_file + + + if not file.exists(): + + self.log.warning( + "Handshake file not found" + ) + + return + + + count = 0 + + + with open( + file, + "r", + encoding="utf-8", + errors="ignore" + ) as f: + + + for line in f: + + + line = line.strip() + + + if not line: + + continue + + + + parts = line.split("*") + + + if len(parts) < 6: + + continue + + + + # WPA*02*hash*APMAC*CLIENTMAC*ESSID*... + hash22000 = line + + ap_bssid = self.normalize_mac( + parts[3] + ) + + client_mac = self.normalize_mac( + parts[4] + ) + + captured_at = self.find_handshake_time( + ap_bssid, + client_mac + ) + + gps = self.gps_from_timestamp( + captured_at + ) + + ap_id = self.access_point_index.get( + ap_bssid + ) + + if ap_id is None: + + row = self.db.get_access_point_by_bssid( + ap_bssid + ) + + if row is not None: + + ap_id = row["id"] + + self.access_point_index[ + ap_bssid + ] = ap_id + + if ap_id is None: + + self.log.warning( + "Handshake AP not found: %s", + ap_bssid + ) + + continue + + if self.db.handshake_exists( + + access_point_id=ap_id, + + session_id=session_id, + + hash22000=hash22000 + + ): + + continue + + self.db.add_handshake( + + { + + "access_point_id": + ap_id, + + + "session_id": + session_id, + + + "type": + "EAPOL", + + + "hash22000": + hash22000, + + + "message_pair": + parts[-1], + + + "captured_at": + captured_at.isoformat().replace( + "+00:00", + "Z" + ) + if captured_at + else None, + + + "latitude": + gps["latitude"], + + + "longitude": + gps["longitude"], + + + "speed": + gps["speed"] + + + } + + ) + + + count += 1 + + + self.log.info( + "Imported handshakes: %s", + count + ) + + def normalize_mac( + self, + mac + ): + + """ + Приводит MAC к виду: + xx:xx:xx:xx:xx:xx + """ + + mac = mac.lower() + + mac = mac.replace( + ":", + "" + ) + + if len(mac) != 12: + return mac + + + return ":".join( + [ + mac[i:i+2] + for i in range( + 0, + 12, + 2 + ) + ] + ) + +# ========================================================= +# GPS track +# ========================================================= + + def load_gps_track( + self, + session, + session_id + ): + + """ + Загружает gps_track.nmea + в память. + """ + + self.gps_track.clear() + self.gps_times.clear() + + + if not session.gps_file.exists(): + + self.log.warning( + "GPS track not found" + ) + + return + + + with open( + session.gps_file, + "r", + encoding="utf-8", + errors="ignore" + ) as file: + + + for line in file: + + + line = line.strip() + + + if not line: + + continue + + + try: + + timestamp_text, nmea = line.split( + ";", + 1 + ) + + + if not nmea.startswith( + "$" + ) or nmea[3:6] != "RMC": + continue + + + msg = pynmea2.parse( + nmea + ) + + + if msg.status != "A": + + continue + + + timestamp = datetime.fromisoformat( + + timestamp_text + + ) + + if timestamp.tzinfo is None: + + timestamp = timestamp.replace( + + tzinfo=timezone.utc + + ) + + + gps = { + + "timestamp": + timestamp, + + "latitude": + msg.latitude, + + "longitude": + msg.longitude, + + "speed": + float( + msg.spd_over_grnd or 0 + ) + + } + + + self.gps_track.append( + gps + ) + + self.gps_times.append( + timestamp + ) + + # + # Сохраняем точку маршрута + # в базу данных. + # + class GPSPoint: + + pass + + + point = GPSPoint() + + point.latitude = gps["latitude"] + + point.longitude = gps["longitude"] + + point.speed = gps["speed"] + + point.timestamp = gps["timestamp"] + + + self.db.add_gps_point( + + session_id, + + point + + ) + + except Exception: + + continue + + + self.log.info( + + "Loaded GPS positions: %s", + + len( + self.gps_track + ) + + ) + + def load_handshake_index( + self, + session + ): + + """ + Загружает все EAPOL кадры. + + Для каждой пары + + (AP, CLIENT) + + сохраняется список всех времен. + """ + + self.handshake_index.clear() + + count = 0 + + with PcapNgReader( + str(session.capture_file) + ) as pcap: + + for packet in pcap: + + try: + + if not packet.haslayer(EAPOL): + continue + + if not packet.haslayer(Dot11): + continue + + dot11 = packet[Dot11] + + addresses = [ + + dot11.addr1, + dot11.addr2, + dot11.addr3 + + ] + + addresses = [ + + x.lower() + + for x in addresses + + if x + ] + + if len(addresses) < 3: + continue + + ap = None + client = None + + if addresses[0] == addresses[1]: + + ap = addresses[0] + client = addresses[2] + + elif addresses[0] == addresses[2]: + + ap = addresses[0] + client = addresses[1] + + elif addresses[1] == addresses[2]: + + ap = addresses[1] + client = addresses[0] + + if ap is None: + continue + + timestamp = datetime.fromtimestamp( + + float(packet.time), + + timezone.utc + + ) + + key = ( + ap, + client + ) + + if key not in self.handshake_index: + + self.handshake_index[key] = [] + + self.handshake_index[key].append( + timestamp + ) + + count += 1 + + except Exception: + + continue + + # + # На всякий случай сортируем + # + + for timestamps in self.handshake_index.values(): + + timestamps.sort() + + self.log.info( + + "Indexed EAPOL frames: %s", + + count + + ) + + def find_handshake_time( + self, + ap, + client + ): + + """ + Возвращает наиболее подходящее + время handshake. + """ + + timestamps = self.handshake_index.get( + + ( + ap.lower(), + client.lower() + ) + + ) + + if not timestamps: + + return None + + # + # Пока используем первое время. + # + + return timestamps[0] + + + def find_closest_gps( + self, + timestamp + ): + + """ + Возвращает ближайшую GPS запись + по времени. + + Если разница превышает 2 секунды, + считается, что подходящей координаты нет. + """ + + if not self.gps_track: + + return None + + + index = bisect_left( + self.gps_times, + timestamp + ) + + + if index == 0: + + gps = self.gps_track[0] + + elif index >= len(self.gps_track): + + gps = self.gps_track[-1] + + else: + + before = self.gps_track[index - 1] + after = self.gps_track[index] + + if ( + timestamp - before["timestamp"] + <= + after["timestamp"] - timestamp + ): + + gps = before + + else: + + gps = after + + + if ( + abs( + gps["timestamp"] - timestamp + ) + > + timedelta(seconds=2) + ): + + return None + + + return gps + + def gps_from_timestamp( + self, + timestamp + ): + + """ + Возвращает словарь GPS + для указанного времени. + """ + + if timestamp is None: + + return { + + "latitude": None, + + "longitude": None, + + "speed": None + + } + + + gps = self.find_closest_gps( + timestamp + ) + + + if gps is None: + + return { + + "latitude": None, + + "longitude": None, + + "speed": None + + } + + + return { + + "latitude": + gps["latitude"], + + "longitude": + gps["longitude"], + + "speed": + gps["speed"] + + } + + # ========================================================= + # Restore session time for rebuild + # ========================================================= + + def restore_session_times( + self, + session_id + ): + + timestamps = [] + + # + # Времена GPS. + # + + timestamps.extend( + self.gps_times + ) + + # + # Времена EAPOL. + # + + for values in self.handshake_index.values(): + + timestamps.extend( + values + ) + + # + # Если есть времена AP observations, + # берём их непосредственно из БД. + # + + cursor = self.db.conn.execute( + """ + SELECT observed_at + FROM access_point_observations + WHERE session_id=? + """, + ( + session_id, + ) + ) + + for row in cursor: + + value = row["observed_at"] + + if not value: + continue + + try: + + timestamp = datetime.fromisoformat( + value + ) + + if timestamp.tzinfo is None: + + timestamp = timestamp.replace( + tzinfo=timezone.utc + ) + + timestamps.append( + timestamp + ) + + except Exception: + + continue + + if not timestamps: + + self.log.warning( + "Cannot restore session time: no timestamps" + ) + + return + + start_time = min( + timestamps + ) + + end_time = max( + timestamps + ) + + self.db.conn.execute( + """ + UPDATE capture_sessions + + SET + start_time=?, + end_time=? + + WHERE id=? + """, + ( + start_time.isoformat().replace( + "+00:00", + "Z" + ), + end_time.isoformat().replace( + "+00:00", + "Z" + ), + session_id + ) + ) + + self.log.info( + "Restored session time: %s -> %s", + start_time.isoformat().replace( + "+00:00", + "Z" + ), + end_time.isoformat().replace( + "+00:00", + "Z" + ) + ) + + + # ========================================================= + # Close + # ========================================================= + + def close( + self + ): + + """ + Освобождение ресурсов парсера. + """ + + if self.vendor: + self.vendor.close() \ No newline at end of file diff --git a/src/session.py b/src/session.py new file mode 100644 index 0000000..8780247 --- /dev/null +++ b/src/session.py @@ -0,0 +1,278 @@ +from datetime import datetime, timezone +from pathlib import Path + + + +class Session: + """ + Управление текущей сессией захвата. + + Одна сессия содержит: + + - pcapng захват + - GPS трек + - результаты парсинга + - hashcat файлы + + Все данные одной поездки находятся + внутри одного каталога. + """ + + + + def __init__( + self, + directory + ): + + + # + # Время запуска + # + self.start_time = datetime.now( + timezone.utc + ) + + + + # + # Каталог сессии + # + name = self.start_time.strftime( + "%Y%m%d_%H%M%S" + ) + + + self.path = ( + Path(directory) / name + ) + + + self.path.mkdir( + parents=True, + exist_ok=True + ) + + + + # ===================================================== + # Основной захват + # ===================================================== + + + self.capture_file = ( + self.path / + "capture.pcapng" + ) + + + + # ===================================================== + # GPS + # ===================================================== + + + self.gps_file = ( + self.path / + "gps_track.nmea" + ) + + + + # ===================================================== + # Результаты hcxpcapngtool + # ===================================================== + + + # + # Список точек доступа + # + self.access_points_file = ( + self.path / + "access_points.csv" + ) + + + + # + # Hashcat формат + # + # WPA-PBKDF2-PMKID+EAPOL + # + self.handshakes_file = ( + self.path / + "handshakes.22000" + ) + + + + # + # ESSID список + # + self.essid_file = ( + self.path / + "essid.txt" + ) + + + + # + # Identity список + # + self.identity_file = ( + self.path / + "identities.txt" + ) + + + + # + # Лог работы парсера + # + self.parser_log = ( + self.path / + "parser.log" + ) + + + + # ===================================================== + # Статистика текущей сессии + # ===================================================== + + + # + # Все NMEA сообщения + # + self.nmea_messages = 0 + + + + # + # Валидные GPS позиции + # + self.gps_positions = 0 + + + + # + # Последняя координата + # + self.current_gps = None + + @classmethod + def from_existing( + cls, + path + ): + + """ + Открывает уже существующую + сессию из каталога captures. + """ + + obj = cls.__new__(cls) + + obj.start_time = datetime.now( + timezone.utc + ) + + obj.path = Path(path) + + obj.capture_file = ( + obj.path / + "capture.pcapng" + ) + + obj.gps_file = ( + obj.path / + "gps_track.nmea" + ) + + obj.access_points_file = ( + obj.path / + "access_points.csv" + ) + + obj.handshakes_file = ( + obj.path / + "handshakes.22000" + ) + + obj.essid_file = ( + obj.path / + "essid.txt" + ) + + obj.identity_file = ( + obj.path / + "identities.txt" + ) + + obj.parser_log = ( + obj.path / + "parser.log" + ) + + obj.nmea_messages = 0 + + obj.gps_positions = 0 + + obj.current_gps = None + + return obj + + # ========================================================= + # Время работы + # ========================================================= + + + def elapsed( + self + ): + + + return int( + ( + datetime.now( + timezone.utc + ) + - + self.start_time + ).total_seconds() + ) + + + + # ========================================================= + # GPS статистика + # ========================================================= + + + def add_nmea(self): + + """ + Увеличить счетчик + полученных NMEA сообщений. + """ + + + self.nmea_messages += 1 + + + + def update_gps( + self, + gps + ): + + """ + Обновить последнюю GPS координату. + """ + + + self.current_gps = gps + + + self.gps_positions += 1 + diff --git a/src/sudo.py b/src/sudo.py new file mode 100644 index 0000000..45bbeae --- /dev/null +++ b/src/sudo.py @@ -0,0 +1,77 @@ +import logging +import subprocess +import sys + + +class SudoChecker: + + + def __init__(self): + + self.log = logging.getLogger( + "sudo" + ) + + + def check(self): + + self.log.info( + "Checking sudo..." + ) + + try: + result = subprocess.run( + [ + "sudo", + "-n", + "-v" + ] + ) + + if result.returncode != 0: + result = subprocess.run( + [ + "sudo", + "-v" + ] + ) + + except KeyboardInterrupt: + + self.log.error( + "Sudo authentication cancelled." + ) + + raise SystemExit(1) + + if result.returncode != 0: + + self.log.error( + "Sudo authentication is not available." + ) + + raise SystemExit(1) + + self.log.info( + "Sudo: OK" + ) + + + def refresh(self): + + try: + result = subprocess.run( + [ + "sudo", + "-n", + "-v" + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + + except Exception: + + return False + + return result.returncode == 0 \ No newline at end of file diff --git a/src/vendor.py b/src/vendor.py new file mode 100644 index 0000000..e3d5e7f --- /dev/null +++ b/src/vendor.py @@ -0,0 +1,704 @@ +import sqlite3 + +from pathlib import Path + + +class VendorResolver: + + + def __init__( + self, + database + ): + + self.db_path = Path(database) + + + self.db_path.parent.mkdir( + parents=True, + exist_ok=True + ) + + + self.conn = sqlite3.connect( + self.db_path + ) + + + self.create_tables() + + + + # ===================================================== + # Создание структуры + # ===================================================== + + def create_tables(self): + + + self.conn.execute( + """ + CREATE TABLE IF NOT EXISTS oui + ( + + prefix TEXT PRIMARY KEY, + + vendor TEXT NOT NULL, + + confidence TEXT NOT NULL, + + prefix_length INTEGER NOT NULL + + ) + """ + ) + + self.conn.execute( + """ + CREATE TABLE IF NOT EXISTS metadata + ( + + key TEXT PRIMARY KEY, + + value TEXT NOT NULL + + ) + """ + ) + + self.conn.execute( + """ + CREATE TABLE IF NOT EXISTS metadata + ( + + key TEXT PRIMARY KEY, + + value TEXT + + ) + """ + ) + + self.conn.execute( + """ + CREATE INDEX IF NOT EXISTS idx_prefix + + ON oui(prefix) + """ + ) + + self.conn.execute( + """ + CREATE TABLE IF NOT EXISTS metadata + ( + + key TEXT PRIMARY KEY, + + value TEXT + + ) + """ + ) + + self.conn.commit() + + + # ===================================================== + # Определение производителя + # ===================================================== + + def lookup( + self, + mac + ): + + if not mac: + + return None + + + mac = self.normalize( + mac + ) + + + for length in ( + 9, + 7, + 6 + ): + + prefix = mac[:length] + + + cursor = self.conn.execute( + """ + SELECT vendor + + FROM oui + + WHERE prefix=? + + """, + ( + prefix, + ) + ) + + + row = cursor.fetchone() + + + if row: + + return row[0] + + + return "Unknown" + + + # ===================================================== + # Добавление производителя + # ===================================================== + + def add_vendor( + self, + prefix, + vendor, + confidence="IEEE" + ): + + prefix = self.normalize(prefix) + + + if not prefix: + + return False + + + prefix_length = len(prefix) + + + if prefix_length not in (6,7,9): + + return False + + + + self.conn.execute( + """ + INSERT OR REPLACE INTO oui + ( + prefix, + vendor, + confidence, + prefix_length + ) + + VALUES (?,?,?,?) + + """, + + ( + prefix, + vendor, + confidence, + prefix_length + ) + ) + + return True + + + + # ===================================================== + # Сохранение изменений + # ===================================================== + + def commit(self): + + self.conn.commit() + + + # ===================================================== + # Количество записей + # ===================================================== + + def count(self): + + cursor = self.conn.execute( + "SELECT COUNT(*) FROM oui" + ) + + return cursor.fetchone()[0] + + # ===================================================== + # Metadata + # ===================================================== + + def get_metadata( + self, + key, + default=None + ): + + cursor = self.conn.execute( + + """ + SELECT value + + FROM metadata + + WHERE key=? + + """, + + ( + key, + ) + + ) + + + row = cursor.fetchone() + + + if row: + + return row[0] + + + return default + + + + def set_metadata( + self, + key, + value + ): + + self.conn.execute( + + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + + VALUES (?,?) + + """, + + ( + key, + str(value) + ) + + ) + + # ===================================================== + # Получить значение metadata + # ===================================================== + + def get_metadata( + self, + key + ): + + cursor = self.conn.execute( + """ + SELECT value + + FROM metadata + + WHERE key=? + + """, + ( + key, + ) + ) + + row = cursor.fetchone() + + if row: + + return row[0] + + return None + + # ===================================================== + # Сохранение metadata + # ===================================================== + + def set_metadata( + self, + key, + value + ): + + self.conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + + VALUES (?,?) + """, + ( + key, + str(value) + ) + ) + + # ===================================================== + # Записать значение metadata + # ===================================================== + + def set_metadata( + self, + key, + value + ): + + self.conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + + VALUES + ( + ?, + ? + ) + """, + ( + key, + str(value) + ) + ) + + # ===================================================== + # Удаление metadata + # ===================================================== + + def delete_metadata( + self, + key + ): + + self.conn.execute( + """ + DELETE + + FROM metadata + + WHERE key=? + """, + ( + key, + ) + ) + + # ===================================================== + # Есть ли база производителей + # ===================================================== + + def has_database(self): + + cursor = self.conn.execute( + """ + SELECT COUNT(*) + + FROM oui + """ + ) + + return cursor.fetchone()[0] > 0 + + + # ===================================================== + # Требуется обновление + # ===================================================== + + def update_available(self): + + value = self.get_metadata( + "update_available" + ) + + return value == "1" + + # ===================================================== + # Получение параметра metadata + # ===================================================== + + def get_metadata( + + self, + + key + + ): + + + cursor = self.conn.execute( + + """ + SELECT value + + FROM metadata + + WHERE key=? + + """, + + ( + key, + ) + + ) + + + row = cursor.fetchone() + + + if row: + + return row[0] + + + return None + + + + # ===================================================== + # Запись параметра metadata + # ===================================================== + + def set_metadata( + + self, + + key, + + value + + ): + + + self.conn.execute( + + """ + INSERT OR REPLACE INTO metadata + + ( + + key, + + value + + ) + + VALUES + + ( + + ?, + + ? + + ) + + """, + + ( + + key, + + str(value) + + ) + + ) + + + + # ===================================================== + # Получение всех параметров metadata + # ===================================================== + + def get_all_metadata( + + self + + ): + + + cursor = self.conn.execute( + + """ + SELECT + + key, + + value + + FROM metadata + + """ + ) + + + result = {} + + + for row in cursor.fetchall(): + + result[ + row[0] + ] = row[1] + + + return result + + + + # ===================================================== + # Удаление параметра metadata + # ===================================================== + + def delete_metadata( + + self, + + key + + ): + + + self.conn.execute( + + """ + DELETE + + FROM metadata + + WHERE key=? + + """, + + ( + + key, + + ) + + ) + + # ===================================================== + # Проверка metadata + # ===================================================== + + def has_metadata( + self, + key + ): + + cursor = self.conn.execute( + """ + SELECT 1 + + FROM metadata + + WHERE key=? + + LIMIT 1 + """, + ( + key, + ) + ) + + return cursor.fetchone() is not None + + # ===================================================== + # Приведение MAC + # ===================================================== + + def normalize( + self, + mac + ): + + if not mac: + + return None + + + mac = mac.replace( + ":", + "" + ) + + mac = mac.replace( + "-", + "" + ) + + mac = mac.replace( + ".", + "" + ) + + + mac = mac.upper() + + + return mac + + # ===================================================== + # Получение metadata + # ===================================================== + + def get_metadata( + self, + key, + default=None + ): + + cursor = self.conn.execute( + """ + SELECT value + + FROM metadata + + WHERE key=? + """, + ( + key, + ) + ) + + row = cursor.fetchone() + + if row: + + return row[0] + + return default + + # ===================================================== + # Закрытие + # ===================================================== + + def close(self): + + self.conn.close() \ No newline at end of file diff --git a/src/vendor_import.py b/src/vendor_import.py new file mode 100644 index 0000000..3b4f206 --- /dev/null +++ b/src/vendor_import.py @@ -0,0 +1,314 @@ +import logging +import urllib.request +import datetime +import time + +from pathlib import Path + +from vendor import VendorResolver +from oui_import import OUIImporter + + +PROJECT_ROOT = ( + Path(__file__).resolve().parent.parent +) + + +DATABASE_DIR = ( + PROJECT_ROOT + / + "database" +) + + +OUI_DATABASE = ( + DATABASE_DIR + / + "oui.sqlite" +) + + +HTTP_HEADERS = { + + "User-Agent": + + "Mozilla/5.0 (X11; Linux x86_64) " + + "AppleWebKit/537.36 " + + "(KHTML, like Gecko) " + + "Chrome/138.0 Safari/537.36" + +} + + +DOWNLOAD_RETRIES = 3 + +DOWNLOAD_TIMEOUT = 60 + +CSV_FILES = { + + "oui.csv": "oui", + + "mam.csv": "mam", + + "oui36.csv": "oui36", + +} + + +class VendorImporter: + + + def __init__( + self, + config + ): + + self.config = config + + self.log = logging.getLogger( + "vendor_import" + ) + + DATABASE_DIR.mkdir( + parents=True, + exist_ok=True + ) + + # --------------------------------------------------------- + # Загрузка IEEE CSV + # --------------------------------------------------------- + + def download_csv_files(self): + + for filename, key in CSV_FILES.items(): + + url = self.config.vendor_sources[key] + + destination = ( + DATABASE_DIR + / + filename + ) + + success = False + + for attempt in range( + 1, + DOWNLOAD_RETRIES + 1 + ): + + self.log.info( + + f"Downloading {filename} " + + f"(attempt {attempt}/{DOWNLOAD_RETRIES})" + + ) + + try: + + request = urllib.request.Request( + url, + headers=HTTP_HEADERS + ) + + with urllib.request.urlopen( + request, + timeout=DOWNLOAD_TIMEOUT + ) as response: + + if response.status != 200: + + raise RuntimeError( + f"HTTP {response.status}" + ) + + data = response.read() + + if len(data) < 1000: + + raise RuntimeError( + "Downloaded file is too small" + ) + + text = data.decode( + "utf-8", + errors="ignore" + ) + + if "Assignment" not in text: + + raise RuntimeError( + "Invalid IEEE CSV" + ) + + destination.write_bytes( + data + ) + + size = ( + destination.stat().st_size + / 1024 + / 1024 + ) + + self.log.info( + + f"{filename} downloaded " + + f"({size:.2f} MB)" + + ) + + success = True + + break + + except KeyboardInterrupt: + + self.log.info( + "CSV download cancelled" + ) + + raise + + except Exception as error: + + self.log.warning( + f"{filename}: {error}" + ) + + if destination.exists(): + + destination.unlink() + + if attempt < DOWNLOAD_RETRIES: + + time.sleep(2) + + if not success: + + raise RuntimeError( + f"Unable to download {filename}" + ) + + # --------------------------------------------------------- + # Полное создание IEEE базы + # --------------------------------------------------------- + + def bootstrap(self): + + OUI_DATABASE.unlink( + missing_ok=True + ) + + self.download_csv_files() + + resolver = VendorResolver( + OUI_DATABASE + ) + + importer = OUIImporter( + + resolver, + + [ + DATABASE_DIR + / + filename + + for filename + + in CSV_FILES + ] + + ) + + result = importer.import_database() + + total = result["total"] + + stats = result["stats"] + + if ( + + stats["MA-L"] < 35000 + + or + + stats["MA-M"] < 5000 + + or + + stats["MA-S"] < 5000 + + ): + + resolver.close() + + OUI_DATABASE.unlink( + missing_ok=True + ) + + raise RuntimeError( + + "IEEE database verification failed.\n\n" + + f"MA-L: {stats['MA-L']}\n" + + f"MA-M: {stats['MA-M']}\n" + + f"MA-S: {stats['MA-S']}" + + ) + + resolver.set_metadata( + + "last_import", + datetime.datetime.now( + datetime.timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ) + + ) + + resolver.set_metadata( + + "records", + + total + + ) + + resolver.set_metadata( + + "schema_version", + + 1 + + ) + + resolver.set_metadata( + + "import_status", + + "ok" + + ) + + resolver.commit() + + resolver.close() + + self.log.info( + + "IEEE database created: " + + f"{total} records" + + ) \ No newline at end of file diff --git a/src/vendor_service.py b/src/vendor_service.py new file mode 100644 index 0000000..18074df --- /dev/null +++ b/src/vendor_service.py @@ -0,0 +1,1696 @@ +from datetime import datetime, timezone +import csv +import os +import shutil +import sqlite3 +import tempfile +import urllib.error +import urllib.request +import urllib.parse + +from pathlib import Path + +class VendorService: + + REGISTRIES = ( + "MA-L", + "MA-M", + "MA-S", + ) + + PREFIX_LENGTHS = ( + 6, + 7, + 9, + ) + + BACKUP_LIMIT = 3 + + def __init__( + self, + vendor_database, + wifi_database, + sources, + mirrors=None + ): + self.vendor_database = Path(vendor_database) + self.wifi_database = Path(wifi_database) + self.sources = dict(sources) + self.mirrors = dict( + mirrors or {} + ) + self.vendor_database.parent.mkdir( + parents=True, + exist_ok=True + ) + self.backup_directory = ( + self.vendor_database.parent + / + "backups" + ) + + # ============================================================ + # Current database status + # ============================================================ + + def status(self): + + exists = self.vendor_database.exists() + + result = { + "database": str( + self.vendor_database + ), + "exists": exists, + "healthy": False, + "total": 0, + "ma_l": 0, + "ma_m": 0, + "ma_s": 0, + "schema_version": None, + "last_import": None, + "import_status": None, + "size": ( + self.vendor_database.stat().st_size + if exists + else 0 + ) + } + + if not exists: + return result + + conn = None + + try: + conn = sqlite3.connect( + self.vendor_database + ) + + self._validate_schema( + conn + ) + + result["total"] = conn.execute( + "SELECT COUNT(*) FROM oui" + ).fetchone()[0] + + rows = conn.execute( + """ + SELECT + confidence, + COUNT(*) + FROM oui + GROUP BY confidence + """ + ).fetchall() + + for confidence, count in rows: + + if confidence == "MA-L": + result["ma_l"] = count + + elif confidence == "MA-M": + result["ma_m"] = count + + elif confidence == "MA-S": + result["ma_s"] = count + + result["schema_version"] = self._get_metadata( + conn, + "schema_version" + ) + + result["last_import"] = self._get_metadata( + conn, + "last_import" + ) + + result["import_status"] = self._get_metadata( + conn, + "import_status" + ) + + result["healthy"] = True + + except ( + OSError, + sqlite3.Error, + ValueError + ): + result["healthy"] = False + + finally: + + if conn is not None: + conn.close() + + return result + + # ============================================================ + # Prepare update + # ============================================================ + + def prepare_update( + self, + progress_callback=None + ): + + def progress( + stage, + source=None, + message=None + ): + + if progress_callback is not None: + + progress_callback( + stage, + source, + message + ) + + work_directory = Path( + tempfile.mkdtemp( + prefix="wifi-gps-mapper-vendor-" + ) + ) + + try: + + progress( + "starting", + message="Подготовка обновления" + ) + + downloaded = self._download_sources( + work_directory, + progress_callback=progress_callback + ) + + candidate = ( + work_directory + / + "oui.sqlite3" + ) + + progress( + "building", + message="Построение базы OUI" + ) + + build_stats = self._build_candidate( + downloaded, + candidate + ) + + progress( + "analyzing", + message="Анализ изменений" + ) + + oui_diff = self._compare_databases( + self.vendor_database, + candidate + ) + + ap_impact = self._calculate_ap_impact( + candidate + ) + + progress( + "ready", + message="Обновление готово к применению" + ) + + return { + "directory": str( + work_directory + ), + "candidate": str( + candidate + ), + "sources": downloaded, + "build": build_stats, + "oui": oui_diff, + "ap": ap_impact + } + + except Exception: + + shutil.rmtree( + work_directory, + ignore_errors=True + ) + + raise + + # ============================================================ + # Download + # ============================================================ + + def _download_sources( + self, + work_directory, + progress_callback=None + ): + + downloaded = {} + + for name, url in self.sources.items(): + + if not isinstance( + url, + str + ) or not url.strip(): + + raise ValueError( + f"Invalid source URL for {name}" + ) + + mirror = self.mirrors.get( + name + ) + + urls = [ + ( + "primary", + url + ) + ] + + if ( + isinstance( + mirror, + str + ) + and mirror.strip() + ): + + urls.append( + ( + "mirror", + mirror + ) + ) + + last_error = None + + for source_type, source_url in urls: + + parsed = urllib.parse.urlparse( + source_url + ) + + if parsed.scheme not in ( + "http", + "https" + ): + + last_error = ValueError( + f"Unsupported source URL " + f"for {name}: {source_url}" + ) + + continue + + if progress_callback is not None: + + progress_callback( + "downloading", + name, + ( + "Загрузка " + f"{'зеркала' if source_type == 'mirror' else 'IEEE'}" + ) + ) + + target = ( + work_directory + / + f"{name}.csv" + ) + + request = urllib.request.Request( + source_url, + headers={ + "User-Agent": + "WiFi-GPS-Mapper/" + "vendor-service" + } + ) + + try: + + with urllib.request.urlopen( + request, + timeout=60 + ) as response: + + with open( + target, + "wb" + ) as file: + + shutil.copyfileobj( + response, + file + ) + + if progress_callback is not None: + + progress_callback( + "validating", + name, + "Проверка загруженного источника" + ) + + self._validate_csv( + target, + name + ) + + downloaded[name] = str( + target + ) + + if progress_callback is not None: + + progress_callback( + "validating", + name, + ( + "Источник принят" + if source_type == "primary" + else + "Резервное зеркало принято" + ) + ) + + break + + except ( + urllib.error.URLError, + OSError, + ValueError + ) as exc: + + last_error = exc + + if ( + source_type == "primary" + and len(urls) > 1 + ): + + if progress_callback is not None: + + progress_callback( + "fallback", + name, + ( + "Основной источник недоступен, " + "переход на зеркало" + ) + ) + + continue + + else: + + raise RuntimeError( + f"Failed to download and validate " + f"source {name}: {last_error}" + ) from last_error + + return downloaded + + # ============================================================ + # CSV validation + # ============================================================ + + def _validate_csv( + self, + filename, + source_name + ): + + required = { + "Registry", + "Assignment", + "Organization Name" + } + + try: + + with open( + filename, + "r", + encoding="utf-8", + errors="ignore", + newline="" + ) as file: + + reader = csv.DictReader( + file + ) + + if reader.fieldnames is None: + + raise ValueError( + "CSV has no header" + ) + + fields = { + field.strip() + for field in reader.fieldnames + if field is not None + } + + missing = required - fields + + if missing: + + raise ValueError( + f"missing columns: " + f"{', '.join(sorted(missing))}" + ) + + first_valid = False + + for row in reader: + + registry = row.get( + "Registry" + ) + + assignment = row.get( + "Assignment" + ) + + organization = row.get( + "Organization Name" + ) + + if ( + registry + and registry in self.REGISTRIES + and assignment + and organization + ): + + first_valid = True + break + + if not first_valid: + + raise ValueError( + "CSV contains no valid IEEE records" + ) + + except ( + OSError, + UnicodeError, + csv.Error + ) as exc: + + raise ValueError( + f"Invalid CSV source {source_name}: {exc}" + ) from exc + + + # ============================================================ + # CSV validation + # ============================================================ + + def _validate_csv( + self, + filename, + source_name + ): + + required = { + "Registry", + "Assignment", + "Organization Name" + } + + try: + + with open( + filename, + "r", + encoding="utf-8", + errors="ignore", + newline="" + ) as file: + + reader = csv.DictReader( + file + ) + + if reader.fieldnames is None: + + raise ValueError( + "CSV has no header" + ) + + fields = { + field.strip() + for field in reader.fieldnames + if field is not None + } + + missing = required - fields + + if missing: + + raise ValueError( + f"missing columns: " + f"{', '.join(sorted(missing))}" + ) + + first_valid = False + + for row in reader: + + registry = row.get( + "Registry" + ) + + assignment = row.get( + "Assignment" + ) + + organization = row.get( + "Organization Name" + ) + + if ( + registry + and registry in self.REGISTRIES + and assignment + and organization + ): + + first_valid = True + break + + if not first_valid: + + raise ValueError( + "CSV contains no valid IEEE records" + ) + + except ( + OSError, + UnicodeError, + csv.Error + ) as exc: + + raise ValueError( + f"Invalid CSV source {source_name}: {exc}" + ) from exc + + # ============================================================ + # Candidate database + # ============================================================ + + def _build_candidate( + self, + files, + candidate + ): + + conn = sqlite3.connect( + candidate + ) + + imported = 0 + skipped = 0 + stats = { + "MA-L": 0, + "MA-M": 0, + "MA-S": 0 + } + + try: + + self._create_schema( + conn + ) + + for source_name, filename in files.items(): + + with open( + filename, + "r", + encoding="utf-8", + errors="ignore", + newline="" + ) as file: + + reader = csv.DictReader( + file + ) + + for row in reader: + + registry = row.get( + "Registry" + ) + + assignment = row.get( + "Assignment" + ) + + organization = row.get( + "Organization Name" + ) + + if not registry: + continue + + if registry not in self.REGISTRIES: + continue + + if not assignment: + skipped += 1 + continue + + if not organization: + skipped += 1 + continue + + assignment = ( + assignment + .replace("-", "") + .replace(":", "") + .replace(".", "") + .strip() + .upper() + ) + + if not assignment: + skipped += 1 + continue + + if not all( + char in "0123456789ABCDEF" + for char in assignment + ): + + skipped += 1 + continue + + if len( + assignment + ) not in self.PREFIX_LENGTHS: + + skipped += 1 + continue + + try: + + conn.execute( + """ + INSERT OR REPLACE INTO oui + ( + prefix, + vendor, + confidence, + prefix_length + ) + VALUES (?, ?, ?, ?) + """, + ( + assignment, + organization.strip(), + registry, + len(assignment) + ) + ) + + except sqlite3.Error: + + skipped += 1 + continue + + imported += 1 + stats[registry] += 1 + + conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + VALUES (?, ?) + """, + ( + "schema_version", + "1" + ) + ) + + conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + VALUES (?, ?) + """, + ( + "import_status", + "ok" + ) + ) + + conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + VALUES (?, ?) + """, + ( + "source_count", + str( + len(files) + ) + ) + ) + + conn.execute( + """ + INSERT OR REPLACE INTO metadata + ( + key, + value + ) + VALUES (?, ?) + """, + ( + "last_import", + datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ) + ) + ) + + conn.commit() + + return { + "imported": imported, + "skipped": skipped, + "ma_l": stats["MA-L"], + "ma_m": stats["MA-M"], + "ma_s": stats["MA-S"] + } + + except Exception: + + conn.rollback() + raise + + finally: + + conn.close() + + # ============================================================ + # Database schema + # ============================================================ + + @staticmethod + def _create_schema(conn): + + conn.execute( + """ + CREATE TABLE IF NOT EXISTS oui + ( + prefix TEXT PRIMARY KEY, + vendor TEXT NOT NULL, + confidence TEXT NOT NULL, + prefix_length INTEGER NOT NULL + ) + """ + ) + + conn.execute( + """ + CREATE TABLE IF NOT EXISTS metadata + ( + key TEXT PRIMARY KEY, + value TEXT + ) + """ + ) + + conn.execute( + """ + CREATE INDEX IF NOT EXISTS idx_prefix + ON oui(prefix) + """ + ) + + @staticmethod + def _validate_schema(conn): + + rows = conn.execute( + """ + SELECT name + FROM sqlite_master + WHERE type='table' + """ + ).fetchall() + + tables = { + row[0] + for row in rows + } + + if "oui" not in tables: + raise ValueError( + "OUI table is missing" + ) + + columns = { + row[1] + for row in conn.execute( + "PRAGMA table_info(oui)" + ).fetchall() + } + + required = { + "prefix", + "vendor", + "confidence", + "prefix_length" + } + + if not required.issubset( + columns + ): + + raise ValueError( + "Invalid OUI database schema" + ) + + # ============================================================ + # OUI comparison + # ============================================================ + + def _compare_databases( + self, + current, + candidate + ): + + current_rows = self._load_oui( + current + ) + + candidate_rows = self._load_oui( + candidate + ) + + current_keys = set( + current_rows + ) + + candidate_keys = set( + candidate_rows + ) + + added = ( + candidate_keys + - + current_keys + ) + + removed = ( + current_keys + - + candidate_keys + ) + + common = ( + current_keys + & + candidate_keys + ) + + changed = { + prefix + for prefix in common + if current_rows[prefix] + != candidate_rows[prefix] + } + + unchanged = ( + len(common) + - + len(changed) + ) + + return { + "current": len( + current_rows + ), + "candidate": len( + candidate_rows + ), + "added": len( + added + ), + "changed": len( + changed + ), + "removed": len( + removed + ), + "unchanged": unchanged, + "identical": ( + not added + and not changed + and not removed + ) + } + + @staticmethod + def _load_oui(filename): + + if not Path( + filename + ).exists(): + + return {} + + conn = sqlite3.connect( + filename + ) + + try: + + rows = conn.execute( + """ + SELECT + prefix, + vendor, + confidence, + prefix_length + FROM oui + """ + ).fetchall() + + return { + row[0]: ( + row[1], + row[2], + row[3] + ) + for row in rows + } + + finally: + + conn.close() + + # ============================================================ + # AP impact + # ============================================================ + + def _calculate_ap_impact( + self, + candidate + ): + + result = { + "total": 0, + "unchanged": 0, + "unknown_to_vendor": 0, + "vendor_to_vendor": 0, + "vendor_to_unknown": 0 + } + + if not self.wifi_database.exists(): + return result + + vendor_conn = sqlite3.connect( + candidate + ) + + wifi_conn = sqlite3.connect( + self.wifi_database + ) + + try: + + self._validate_wifi_schema( + wifi_conn + ) + + rows = wifi_conn.execute( + """ + SELECT + bssid, + vendor + FROM access_points + """ + ).fetchall() + + result["total"] = len( + rows + ) + + for bssid, current_vendor in rows: + + candidate_vendor = self._lookup_vendor( + vendor_conn, + bssid + ) + + current_unknown = ( + current_vendor is None + or current_vendor == "" + or current_vendor == "Unknown" + ) + + candidate_unknown = ( + candidate_vendor is None + or candidate_vendor == "" + ) + + if ( + current_unknown + and candidate_unknown + ): + + result["unchanged"] += 1 + continue + + if ( + not current_unknown + and not candidate_unknown + and current_vendor == candidate_vendor + ): + + result["unchanged"] += 1 + continue + + if ( + current_unknown + and not candidate_unknown + ): + + result[ + "unknown_to_vendor" + ] += 1 + + elif ( + not current_unknown + and not candidate_unknown + ): + + result[ + "vendor_to_vendor" + ] += 1 + + elif ( + not current_unknown + and candidate_unknown + ): + + result[ + "vendor_to_unknown" + ] += 1 + + finally: + + vendor_conn.close() + wifi_conn.close() + + return result + + @staticmethod + def _lookup_vendor( + conn, + bssid + ): + + if not bssid: + return None + + normalized = ( + str(bssid) + .replace(":", "") + .replace("-", "") + .replace(".", "") + .strip() + .upper() + ) + + for length in ( + 9, + 7, + 6 + ): + + prefix = normalized[ + :length + ] + + if len(prefix) != length: + continue + + row = conn.execute( + """ + SELECT vendor + FROM oui + WHERE prefix=? + """, + ( + prefix, + ) + ).fetchone() + + if row is not None: + return row[0] + + return None + + @staticmethod + def _validate_wifi_schema(conn): + + tables = { + row[0] + for row in conn.execute( + """ + SELECT name + FROM sqlite_master + WHERE type='table' + """ + ).fetchall() + } + + if "access_points" not in tables: + raise ValueError( + "access_points table is missing" + ) + + columns = { + row[1] + for row in conn.execute( + "PRAGMA table_info(access_points)" + ).fetchall() + } + + required = { + "bssid", + "vendor" + } + + if not required.issubset( + columns + ): + + raise ValueError( + "Invalid WiFi database schema" + ) + + # ============================================================ + # Apply + # ============================================================ + + def apply( + self, + preview, + unknown_to_vendor=True, + vendor_to_vendor=False, + vendor_to_unknown=False + ): + + candidate = Path( + preview["candidate"] + ) + + if not candidate.exists(): + raise ValueError( + "Vendor preview candidate does not exist" + ) + + if not self._is_preview_candidate( + preview + ): + + raise ValueError( + "Invalid vendor preview" + ) + + oui_changed = not preview[ + "oui" + ][ + "identical" + ] + + selected = { + "unknown_to_vendor": + bool( + unknown_to_vendor + ), + "vendor_to_vendor": + bool( + vendor_to_vendor + ), + "vendor_to_unknown": + bool( + vendor_to_unknown + ) + } + + selected_count = 0 + + if selected[ + "unknown_to_vendor" + ]: + + selected_count += preview[ + "ap" + ][ + "unknown_to_vendor" + ] + + if selected[ + "vendor_to_vendor" + ]: + + selected_count += preview[ + "ap" + ][ + "vendor_to_vendor" + ] + + if selected[ + "vendor_to_unknown" + ]: + + selected_count += preview[ + "ap" + ][ + "vendor_to_unknown" + ] + + result = { + "oui_updated": False, + "wifi_updated": 0, + "selected": selected, + "selected_count": selected_count + } + + try: + + if oui_changed: + + self._backup_database( + self.vendor_database, + "oui" + ) + + self._atomic_replace( + candidate, + self.vendor_database + ) + + result[ + "oui_updated" + ] = True + + if selected_count: + + result[ + "wifi_updated" + ] = self._apply_wifi_changes( + preview, + selected + ) + + return result + + finally: + + self._cleanup_preview( + preview + ) + + # ============================================================ + # WiFi vendor synchronization + # ============================================================ + + def _apply_wifi_changes( + self, + preview, + selected + ): + + candidate = Path( + preview["candidate"] + ) + + vendor_conn = sqlite3.connect( + candidate + ) + + wifi_conn = None + + try: + + wifi_conn = sqlite3.connect( + self.wifi_database, + timeout=30 + ) + + self._validate_wifi_schema( + wifi_conn + ) + + changes = [] + + rows = wifi_conn.execute( + """ + SELECT + id, + bssid, + vendor + FROM access_points + """ + ).fetchall() + + for ap_id, bssid, current_vendor in rows: + + new_vendor = self._lookup_vendor( + vendor_conn, + bssid + ) + + current_unknown = ( + current_vendor is None + or current_vendor == "" + or current_vendor == "Unknown" + ) + + new_unknown = ( + new_vendor is None + or new_vendor == "" + ) + + category = None + + if ( + current_unknown + and not new_unknown + ): + + category = ( + "unknown_to_vendor" + ) + + elif ( + not current_unknown + and not new_unknown + and current_vendor != new_vendor + ): + + category = ( + "vendor_to_vendor" + ) + + elif ( + not current_unknown + and new_unknown + ): + + category = ( + "vendor_to_unknown" + ) + + if ( + category is not None + and selected[category] + ): + + changes.append( + ( + new_vendor, + ap_id + ) + ) + + if not changes: + return 0 + + self._backup_database( + self.wifi_database, + "wifi" + ) + + wifi_conn.execute( + "BEGIN" + ) + + for vendor, ap_id in changes: + + wifi_conn.execute( + """ + UPDATE access_points + SET vendor=? + WHERE id=? + """, + ( + vendor, + ap_id + ) + ) + + wifi_conn.commit() + + return len( + changes + ) + + except Exception: + + if wifi_conn is not None: + wifi_conn.rollback() + + raise + + finally: + + vendor_conn.close() + + if wifi_conn is not None: + wifi_conn.close() + + # ============================================================ + # Backup + # ============================================================ + + def _backup_database( + self, + database, + database_type + ): + + database = Path( + database + ) + + if not database.exists(): + return None + + self.backup_directory.mkdir( + parents=True, + exist_ok=True + ) + + prefix = ( + f"{database_type}-" + ) + + backups = sorted( + self.backup_directory.glob( + f"{prefix}*.sqlite*" + ), + key=lambda path: path.stat().st_mtime, + reverse=True + ) + + while len( + backups + ) >= self.BACKUP_LIMIT: + + oldest = backups.pop() + + try: + oldest.unlink() + except OSError: + pass + + backup = ( + self.backup_directory + / + ( + f"{prefix}" + f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}" + f".sqlite3" + ) + ) + + shutil.copy2( + database, + backup + ) + + return backup + + # ============================================================ + # Atomic replacement + # ============================================================ + + @staticmethod + def _atomic_replace( + source, + destination + ): + + source = Path( + source + ) + + destination = Path( + destination + ) + + destination.parent.mkdir( + parents=True, + exist_ok=True + ) + + temporary = destination.with_name( + f".{destination.name}.tmp" + ) + + try: + + shutil.copy2( + source, + temporary + ) + + os.replace( + temporary, + destination + ) + + finally: + + if temporary.exists(): + + try: + temporary.unlink() + except OSError: + pass + + # ============================================================ + # Preview validation / cleanup + # ============================================================ + + def _is_preview_candidate( + self, + preview + ): + + candidate = Path( + preview.get( + "candidate", + "" + ) + ) + + directory = Path( + preview.get( + "directory", + "" + ) + ) + + try: + + candidate.relative_to( + directory + ) + + except ValueError: + + return False + + return ( + candidate.exists() + and directory.exists() + ) + + @staticmethod + def _cleanup_preview( + preview + ): + + directory = Path( + preview.get( + "directory", + "" + ) + ) + + if directory.exists(): + shutil.rmtree( + directory, + ignore_errors=True + ) + + # ============================================================ + # Metadata + # ============================================================ + + @staticmethod + def _get_metadata( + conn, + key + ): + + try: + + row = conn.execute( + """ + SELECT value + FROM metadata + WHERE key=? + """, + ( + key, + ) + ).fetchone() + + except sqlite3.Error: + return None + + if row is None: + return None + + return row[0] \ No newline at end of file diff --git a/src/vendor_update.py b/src/vendor_update.py new file mode 100644 index 0000000..53133ba --- /dev/null +++ b/src/vendor_update.py @@ -0,0 +1,373 @@ +import logging +import urllib.request + +from pathlib import Path + +from vendor import VendorResolver +from vendor_import import ( + VendorImporter, + CSV_FILES +) + + +logger = logging.getLogger( + "vendor-update" +) + + +class VendorUpdater: + + + def __init__( + self, + cfg + ): + + self.cfg = cfg + + + self.project_root = ( + + Path(__file__) + + .resolve() + + .parent + + .parent + + ) + + + self.database = ( + + self.project_root + + / "database" + + / "oui.sqlite" + + ) + + + self.csv_files = [ + + self.project_root + / "database" + / filename + + for filename + + in CSV_FILES + + ] + + # ===================================================== + # Проверка CSV + # ===================================================== + + def csv_exists( + self + ): + + for file in self.csv_files: + + if not file.exists(): + + return False + + return True + + # ===================================================== + # Проверка базы + # ===================================================== + + def database_exists( + self + ): + + return self.database.exists() + + # ===================================================== + # Проверка metadata + # ===================================================== + + def metadata_exists( + self + ): + + resolver = VendorResolver( + self.database + ) + + + result = resolver.has_metadata( + "last_import" + ) + + + resolver.close() + + return result + + # ===================================================== + # Создание базы IEEE + # ===================================================== + + def create_database( + self + ): + + logger.info( + "Creating IEEE OUI database..." + ) + + + importer = VendorImporter( + + self.cfg + + ) + + + importer.import_database() + + + logger.info( + "IEEE database created" + ) + + # ===================================================== + # Проверка IEEE базы + # ===================================================== + + def check( + self + ): + + logger.info( + "Checking IEEE vendor database..." + ) + + + # + # База уже существует + # + + if self.database_exists(): + + if self.database.stat().st_size < 10000: + + logger.warning( + "IEEE database corrupted" + ) + + self.database.unlink() + + self.check() + + return + + logger.info( + "IEEE database found" + ) + + + if self.metadata_exists(): + + logger.info( + "IEEE metadata found" + ) + + return + + + logger.warning( + "IEEE metadata missing" + ) + + + resolver = VendorResolver( + self.database + ) + + if resolver.count() == 0: + + resolver.close() + + logger.warning( + "IEEE database is empty" + ) + + self.database.unlink() + + self.check() + + return + + resolver.set_metadata( + "last_import", + "unknown" + ) + + + resolver.commit() + + resolver.close() + + + logger.info( + "IEEE metadata restored" + ) + + return + + + # + # Базы нет + # + + logger.warning( + "IEEE database not found" + ) + + + # + # Проверяем CSV + # + + if not self.csv_exists(): + + logger.warning( + "IEEE CSV files not found" + ) + + self.download_csv() + + + logger.info( + "IEEE CSV files found" + ) + + + # + # Создаем базу + # + + self.create_database() + + # ===================================================== + # Загрузка IEEE CSV + # ===================================================== + + def download_csv( + self + ): + + + logger.info( + "Downloading IEEE CSV files..." + ) + + self.database.parent.mkdir( + + parents=True, + + exist_ok=True + + ) + + downloads = [ + + ( + self.cfg.vendor_sources[key], + + self.project_root + / + "database" + / + filename + ) + + for filename, key + + in CSV_FILES.items() + + ] + + + for url, filename in downloads: + + + logger.info( + f"Downloading {filename.name}" + ) + + + try: + + urllib.request.urlretrieve( + + url, + + filename + + ) + + except Exception as error: + + logger.error( + + f"Download failed: {filename.name}" + + ) + + raise RuntimeError( + + str(error) + + ) + + + if not filename.exists(): + + raise RuntimeError( + + f"{filename.name} download failed" + + ) + + + if filename.stat().st_size < 1000: + + raise RuntimeError( + + f"{filename.name} is too small" + + ) + + + size = ( + + filename.stat().st_size + + / 1024 + + / 1024 + + ) + + + logger.info( + + f"{filename.name} downloaded " + + f"({size:.2f} MB)" + + ) + + + logger.info( + "IEEE CSV download finished" + ) + diff --git a/src/wifi.py b/src/wifi.py new file mode 100644 index 0000000..ae132a9 --- /dev/null +++ b/src/wifi.py @@ -0,0 +1,194 @@ +import logging +import subprocess +import signal +import shlex + + +class WiFiManager: + + + def __init__( + self, + config, + session, + interface + ): + + self.config = config + + self.session = session + + self.interface = interface + + self.process = None + + self.log = logging.getLogger( + "wifi" + ) + + + cmd = [ + "sudo", + "-n", + str(self.config.hcxdumptool), + "-i", + self.interface, + "-w", + str(self.session.capture_file), + ] + + + + # + # Каналы WiFi + # + # Каналы собираются отдельно для каждого + # включённого диапазона. + # + # a - диапазон 2.4 GHz + # b - диапазон 5 GHz + # c - диапазон 6 GHz + # + + channels = [] + + + if self.config.wifi_enable_2_4ghz: + + if self.config.wifi_channels_2_4ghz: + + channels.append( + self.config.wifi_channels_2_4ghz + ) + + + if self.config.wifi_enable_5ghz: + + if self.config.wifi_channels_5ghz: + + channels.append( + self.config.wifi_channels_5ghz + ) + + + if self.config.wifi_enable_6ghz: + + if self.config.wifi_channels_6ghz: + + channels.append( + self.config.wifi_channels_6ghz + ) + + + if channels: + + cmd.extend( + [ + "-c", + ",".join(channels) + ] + ) + + + + # + # Дополнительные параметры + # + # Берутся из config.yaml + # + # Позволяют добавлять новые ключи + # без изменения программы + # + + if self.config.wifi_extra_args: + + + cmd.extend( + shlex.split( + self.config.wifi_extra_args + ) + ) + + + + self.cmd = cmd + + + def start(self): + + if self.process is not None: + + return + + self.log.info( + "Starting hcxdumptool" + ) + + self.log.debug( + "Command: %s", + " ".join(self.cmd) + ) + + self.process = subprocess.Popen( + self.cmd + ) + + self.log.info( + "hcxdumptool started, pid=%s", + self.process.pid + ) + + + def stop(self): + + + if not self.process: + + return + + + + self.log.info( + "Stopping hcxdumptool" + ) + + + + self.process.send_signal( + signal.SIGTERM + ) + + + + try: + + self.process.wait( + timeout=10 + ) + + + self.log.info( + + "hcxdumptool stopped with code %s", + + self.process.returncode + + ) + + + except subprocess.TimeoutExpired: + + + self.log.warning( + "hcxdumptool did not stop, killing..." + ) + + + self.process.kill() + + self.process.wait( + timeout=5 + ) + + + self.process = None \ No newline at end of file diff --git a/src/wifi_interface.py b/src/wifi_interface.py new file mode 100644 index 0000000..e555192 --- /dev/null +++ b/src/wifi_interface.py @@ -0,0 +1,94 @@ +from pathlib import Path + + +class WiFiInterfaceDetector: + + + def detect(self): + + interfaces = [] + + network_directory = Path( + "/sys/class/net" + ) + + + for interface in sorted( + network_directory.iterdir() + ): + + wireless_directory = ( + interface + / + "wireless" + ) + + if wireless_directory.exists(): + + interfaces.append( + interface.name + ) + + + if not interfaces: + + raise RuntimeError( + "No WiFi interfaces found." + ) + + + if len(interfaces) == 1: + + return interfaces[0] + + + print() + + print( + "Available WiFi interfaces:" + ) + + print() + + + for index, interface in enumerate( + interfaces, + start=1 + ): + + print( + f"{index}. {interface}" + ) + + + print() + + + while True: + + answer = input( + "Select interface: " + ) + + try: + + number = int( + answer + ) + + except ValueError: + + continue + + + if ( + 1 + <= + number + <= + len(interfaces) + ): + + return interfaces[ + number - 1 + ] \ No newline at end of file diff --git a/src/wifitrip.py b/src/wifitrip.py new file mode 100644 index 0000000..26aaba8 --- /dev/null +++ b/src/wifitrip.py @@ -0,0 +1,2732 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +WiFi GPS Mapper — .wifitrip import/export service. + +Формат .wifitrip представляет собой ZIP-контейнер с логическим +содержимым одной или нескольких capture sessions. + +Модуль не открывает SQLite самостоятельно. +Соединение передаётся вызывающим коду. + +Используется одновременно: + • CLI; + • server-side Reports. + +Локальные SQLite IDs никогда не являются идентификаторами обмена. +""" + +import hashlib +import json +import logging +import os +import tempfile +import zipfile + +from datetime import datetime, timezone +from pathlib import Path + + +# ============================================================ +# Constants +# ============================================================ + +WIFITRIP_FORMAT = "wifitrip" +WIFITRIP_VERSION = 1 +SESSION_HASH_VERSION = 1 + +REQUIRED_FILES = ( + "manifest.json", + "sessions.json", + "access_points.json", + "gps_tracks.json", + "observations.json", + "handshakes.json", + "credentials.json", +) + +MAX_JSON_SIZE = 512 * 1024 * 1024 + + +logger = logging.getLogger( + "wifi-gps-mapper.wifitrip" +) + + +# ============================================================ +# Exceptions +# ============================================================ + +class WifitripError(Exception): + """Base exception for .wifitrip errors.""" + + +class WifitripValidationError(WifitripError): + """Archive validation failed.""" + + +class WifitripHashMismatchError(WifitripError): + """Imported session hash does not match restored data.""" + + +# ============================================================ +# Result helpers +# ============================================================ + +def _new_session_result( + session_hash, +): + return { + "session_hash": session_hash, + "status": "FAILED", + "error": None, + "access_points": 0, + "gps_points": 0, + "observations": 0, + "handshakes": 0, + "credentials": 0, + } + + +# ============================================================ +# JSON helpers +# ============================================================ + +def _json_dump( + value, +): + return json.dumps( + value, + ensure_ascii=False, + indent=2, + sort_keys=True, + allow_nan=False, + ) + + +def _read_json( + archive, + filename, +): + try: + info = archive.getinfo( + filename + ) + except KeyError as error: + raise WifitripValidationError( + f"Required file is missing: {filename}" + ) from error + + if info.file_size > MAX_JSON_SIZE: + raise WifitripValidationError( + f"File is too large: {filename}" + ) + + try: + content = archive.read( + filename + ).decode( + "utf-8" + ) + except UnicodeDecodeError as error: + raise WifitripValidationError( + f"File is not valid UTF-8: {filename}" + ) from error + + try: + return json.loads( + content + ) + except json.JSONDecodeError as error: + raise WifitripValidationError( + f"Invalid JSON in {filename}: " + f"{error}" + ) from error + + +def _ensure_list( + value, + filename, +): + if not isinstance( + value, + list, + ): + raise WifitripValidationError( + f"{filename} must contain a JSON array." + ) + + return value + + +def _ensure_dict( + value, + filename, +): + if not isinstance( + value, + dict, + ): + raise WifitripValidationError( + f"{filename} must contain a JSON object." + ) + + return value + + +# ============================================================ +# General helpers +# ============================================================ + +def _utc_now(): + return datetime.now( + timezone.utc + ).isoformat().replace( + "+00:00", + "Z" + ) + + +def _normalise_bssid( + value, +): + if value is None: + return "" + + return str( + value + ).strip().lower() + + +def _require_string( + record, + field, + context, +): + value = record.get( + field + ) + + if not isinstance( + value, + str, + ): + raise WifitripValidationError( + f"{context}: {field} must be a string." + ) + + if not value.strip(): + raise WifitripValidationError( + f"{context}: {field} must not be empty." + ) + + return value + + +def _optional_number( + value, + field, + context, +): + if value is None: + return None + + if isinstance( + value, + bool, + ): + raise WifitripValidationError( + f"{context}: {field} must be numeric or null." + ) + + if not isinstance( + value, + (int, float), + ): + raise WifitripValidationError( + f"{context}: {field} must be numeric or null." + ) + + return value + + +def _optional_integer( + value, + field, + context, +): + if value is None: + return None + + if isinstance( + value, + bool, + ): + raise WifitripValidationError( + f"{context}: {field} must be an integer or null." + ) + + if not isinstance( + value, + int, + ): + raise WifitripValidationError( + f"{context}: {field} must be an integer or null." + ) + + return value + + +def _validate_bssid( + value, + context, +): + bssid = _normalise_bssid( + value + ) + + compact = bssid.replace( + ":", + "" + ).replace( + "-", + "" + ) + + if len(compact) != 12: + raise WifitripValidationError( + f"{context}: invalid BSSID: {value}" + ) + + try: + int( + compact, + 16, + ) + except ValueError as error: + raise WifitripValidationError( + f"{context}: invalid BSSID: {value}" + ) from error + + return bssid + + +# ============================================================ +# Session hash +# ============================================================ + +def _canonical_json( + value, +): + return json.dumps( + value, + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ) + + +def _calculate_session_hash( + conn, + session_id, +): + session = conn.execute( + """ + SELECT + start_time, + end_time + FROM capture_sessions + WHERE id=? + """, + ( + session_id, + ) + ).fetchone() + + if session is None: + raise WifitripError( + f"Session not found: {session_id}" + ) + + gps_rows = conn.execute( + """ + SELECT + timestamp, + latitude, + longitude + FROM gps_track + WHERE session_id=? + ORDER BY sequence_no + """, + ( + session_id, + ) + ).fetchall() + + handshake_rows = conn.execute( + """ + SELECT + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + FROM handshakes + JOIN access_points + ON access_points.id = + handshakes.access_point_id + WHERE handshakes.session_id=? + ORDER BY + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at + """, + ( + session_id, + ) + ).fetchall() + + handshake_data = [ + [ + row["bssid"], + row["type"], + row["hash22000"], + row["message_pair"], + row["captured_at"], + ] + for row in handshake_rows + ] + + if gps_rows: + gps_data = [ + [ + row["timestamp"], + row["latitude"], + row["longitude"], + ] + for row in gps_rows + ] + + canonical = [ + "GPS_SESSION_V1", + gps_data, + handshake_data, + ] + + else: + observation_rows = conn.execute( + """ + SELECT + observations.observed_at, + access_points.bssid + FROM access_point_observations AS observations + JOIN access_points + ON access_points.id = + observations.access_point_id + WHERE observations.session_id=? + ORDER BY + observations.observed_at, + access_points.bssid + """, + ( + session_id, + ) + ).fetchall() + + observation_data = [ + [ + row["observed_at"], + row["bssid"], + ] + for row in observation_rows + ] + + canonical = [ + "NON_GPS_SESSION_V1", + session["start_time"], + session["end_time"], + observation_data, + handshake_data, + ] + + payload = _canonical_json( + canonical + ).encode( + "utf-8" + ) + + return hashlib.sha256( + payload + ).hexdigest() + + +# ============================================================ +# Export queries +# ============================================================ + +def _get_sessions_for_export( + conn, + session_ids=None, +): + if session_ids is None: + return conn.execute( + """ + SELECT + id, + start_time, + end_time, + session_hash, + session_hash_version + FROM capture_sessions + WHERE + session_hash IS NOT NULL + AND TRIM(session_hash) != '' + AND session_hash_version IS NOT NULL + ORDER BY id + """ + ).fetchall() + + ids = list( + session_ids + ) + + if not ids: + return [] + + placeholders = ",".join( + "?" + for _ in ids + ) + + return conn.execute( + f""" + SELECT + id, + start_time, + end_time, + session_hash, + session_hash_version + FROM capture_sessions + WHERE + id IN ({placeholders}) + AND session_hash IS NOT NULL + AND TRIM(session_hash) != '' + AND session_hash_version IS NOT NULL + ORDER BY id + """, + ids, + ).fetchall() + + +def _get_session_type( + conn, + session_id, +): + gps_count = conn.execute( + """ + SELECT COUNT(*) + FROM gps_track + WHERE session_id=? + """, + ( + session_id, + ) + ).fetchone()[0] + + if gps_count: + return "gps" + + return "non_gps" + + +def _get_access_points( + conn, + session_ids, +): + if not session_ids: + return [] + + placeholders = ",".join( + "?" + for _ in session_ids + ) + + rows = conn.execute( + f""" + SELECT DISTINCT + access_points.bssid + FROM access_points + WHERE access_points.id IN ( + SELECT access_point_id + FROM access_point_observations + WHERE session_id IN ({placeholders}) + + UNION + + SELECT access_point_id + FROM handshakes + WHERE session_id IN ({placeholders}) + + UNION + + SELECT access_point_id + FROM credentials + WHERE access_point_id IN ( + SELECT access_point_id + FROM handshakes + WHERE session_id IN ({placeholders}) + ) + ) + ORDER BY access_points.bssid + """, + ( + *session_ids, + *session_ids, + *session_ids, + ), + ).fetchall() + + return [ + { + "bssid": row["bssid"], + } + for row in rows + ] + + +def _get_gps_tracks( + conn, + sessions, +): + records = [] + + for session in sessions: + rows = conn.execute( + """ + SELECT + sequence_no, + latitude, + longitude, + speed, + timestamp + FROM gps_track + WHERE session_id=? + ORDER BY sequence_no + """, + ( + session["id"], + ) + ).fetchall() + + for row in rows: + records.append( + { + "session_hash": + session["session_hash"], + "sequence_no": + row["sequence_no"], + "latitude": + row["latitude"], + "longitude": + row["longitude"], + "speed": + row["speed"], + "timestamp": + row["timestamp"], + } + ) + + return records + + +def _get_observations( + conn, + sessions, +): + records = [] + + for session in sessions: + rows = conn.execute( + """ + SELECT + access_points.bssid, + observations.observed_at, + observations.latitude, + observations.longitude, + observations.speed, + observations.rssi, + observations.channel, + observations.frequency, + observations.essid, + observations.encryption, + observations.cipher, + observations.akm, + observations.country + FROM access_point_observations AS observations + JOIN access_points + ON access_points.id = + observations.access_point_id + WHERE observations.session_id=? + ORDER BY + observations.observed_at, + access_points.bssid, + observations.id + """, + ( + session["id"], + ) + ).fetchall() + + for row in rows: + records.append( + { + "session_hash": + session["session_hash"], + "bssid": + row["bssid"], + "observed_at": + row["observed_at"], + "latitude": + row["latitude"], + "longitude": + row["longitude"], + "speed": + row["speed"], + "rssi": + row["rssi"], + "channel": + row["channel"], + "frequency": + row["frequency"], + "essid": + row["essid"], + "encryption": + row["encryption"], + "cipher": + row["cipher"], + "akm": + row["akm"], + "country": + row["country"], + } + ) + + return records + + +def _get_handshakes( + conn, + sessions, +): + records = [] + handshake_maps = {} + + for session in sessions: + rows = conn.execute( + """ + SELECT + handshakes.id, + access_points.bssid, + handshakes.type, + handshakes.hash22000, + handshakes.message_pair, + handshakes.captured_at, + handshakes.latitude, + handshakes.longitude, + handshakes.speed + FROM handshakes + JOIN access_points + ON access_points.id = + handshakes.access_point_id + WHERE handshakes.session_id=? + ORDER BY handshakes.id + """, + ( + session["id"], + ) + ).fetchall() + + session_map = {} + + for index, row in enumerate( + rows, + start=1, + ): + handshake_key = ( + f"h{index:06d}" + ) + + session_map[ + row["id"] + ] = handshake_key + + records.append( + { + "session_hash": + session["session_hash"], + "handshake_key": + handshake_key, + "bssid": + row["bssid"], + "type": + row["type"], + "hash22000": + row["hash22000"], + "message_pair": + row["message_pair"], + "captured_at": + row["captured_at"], + "latitude": + row["latitude"], + "longitude": + row["longitude"], + "speed": + row["speed"], + } + ) + + handshake_maps[ + session["id"] + ] = session_map + + return records, handshake_maps + + +def _get_credentials( + conn, + sessions, + handshake_maps, +): + records = [] + + for session in sessions: + rows = conn.execute( + """ + SELECT + credentials.id, + access_points.bssid, + credentials.handshake_id, + credentials.password, + credentials.source, + credentials.created_at, + credentials.verified + FROM credentials + JOIN access_points + ON access_points.id = + credentials.access_point_id + WHERE + credentials.handshake_id IN ( + SELECT id + FROM handshakes + WHERE session_id=? + ) + OR ( + credentials.handshake_id IS NULL + AND credentials.access_point_id IN ( + SELECT access_point_id + FROM access_point_observations + WHERE session_id=? + ) + ) + ORDER BY credentials.id + """, + ( + session["id"], + session["id"], + ) + ).fetchall() + + session_map = handshake_maps.get( + session["id"], + {}, + ) + + for row in rows: + handshake_key = None + + if row["handshake_id"] is not None: + handshake_key = session_map.get( + row["handshake_id"] + ) + + if handshake_key is None: + raise WifitripError( + "Credential references a handshake " + "outside the exported session." + ) + + records.append( + { + "session_hash": + session["session_hash"], + "bssid": + row["bssid"], + "handshake_key": + handshake_key, + "password": + row["password"], + "source": + row["source"], + "created_at": + row["created_at"], + "verified": + row["verified"], + } + ) + + return records + + +# ============================================================ +# Export +# ============================================================ + +def _build_export_package( + conn, + session_ids=None, +): + sessions = _get_sessions_for_export( + conn, + session_ids, + ) + + session_records = [] + session_hashes = set() + + for session in sessions: + session_hash = str( + session["session_hash"] + ).strip() + + if session_hash in session_hashes: + raise WifitripError( + f"Duplicate session hash in database: " + f"{session_hash}" + ) + + session_hashes.add( + session_hash + ) + + calculated_hash = _calculate_session_hash( + conn, + session["id"], + ) + + if calculated_hash != session_hash: + raise WifitripHashMismatchError( + "Stored session hash does not match " + f"session {session['id']}: " + f"{session_hash}" + ) + + session_records.append( + { + "session_hash": + session_hash, + "session_hash_version": + session["session_hash_version"], + "start_time": + session["start_time"], + "end_time": + session["end_time"], + "session_type": + _get_session_type( + conn, + session["id"], + ), + } + ) + + access_points = _get_access_points( + conn, + [ + session["id"] + for session in sessions + ], + ) + + gps_tracks = _get_gps_tracks( + conn, + sessions, + ) + + observations = _get_observations( + conn, + sessions, + ) + + handshakes, handshake_maps = _get_handshakes( + conn, + sessions, + ) + + credentials = _get_credentials( + conn, + sessions, + handshake_maps, + ) + + manifest = { + "format": WIFITRIP_FORMAT, + "format_version": WIFITRIP_VERSION, + "created_at": _utc_now(), + "sessions": len( + session_records + ), + "session_hash_versions": sorted( + { + record["session_hash_version"] + for record in session_records + } + ), + } + + return { + "manifest": manifest, + "sessions": session_records, + "access_points": access_points, + "gps_tracks": gps_tracks, + "observations": observations, + "handshakes": handshakes, + "credentials": credentials, + } + + +def export_wifitrip( + conn, + output_path, + session_ids=None, +): + started_at = datetime.now( + timezone.utc + ) + + output_path = Path( + output_path + ) + + output_path.parent.mkdir( + parents=True, + exist_ok=True, + ) + + package = _build_export_package( + conn, + session_ids, + ) + + output_fd = None + temporary_path = None + + try: + output_fd, temporary_path = tempfile.mkstemp( + prefix=".wifitrip-", + suffix=".tmp", + dir=str( + output_path.parent + ), + ) + + os.close( + output_fd + ) + output_fd = None + + with zipfile.ZipFile( + temporary_path, + "w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=6, + ) as archive: + + for filename in REQUIRED_FILES: + key = filename[:-5] + + archive.writestr( + filename, + _json_dump( + package[key] + ).encode( + "utf-8" + ), + ) + + os.replace( + temporary_path, + output_path, + ) + + temporary_path = None + + finally: + if output_fd is not None: + os.close( + output_fd + ) + + if temporary_path is not None: + try: + os.unlink( + temporary_path + ) + except FileNotFoundError: + pass + + size = output_path.stat().st_size + + duration = ( + datetime.now( + timezone.utc + ) - started_at + ).total_seconds() + + result = { + "output": str( + output_path + ), + "size": size, + "duration": duration, + "sessions": len( + package["sessions"] + ), + "access_points": len( + package["access_points"] + ), + "gps_points": len( + package["gps_tracks"] + ), + "observations": len( + package["observations"] + ), + "handshakes": len( + package["handshakes"] + ), + "credentials": len( + package["credentials"] + ), + } + + logger.info( + "wifitrip export completed: " + "file=%s size=%d sessions=%d " + "access_points=%d gps_points=%d " + "observations=%d handshakes=%d " + "credentials=%d duration=%.3fs", + output_path, + size, + result["sessions"], + result["access_points"], + result["gps_points"], + result["observations"], + result["handshakes"], + result["credentials"], + duration, + ) + + return result + + +# ============================================================ +# Package validation +# ============================================================ + +def _validate_manifest( + manifest, +): + _ensure_dict( + manifest, + "manifest.json", + ) + + if manifest.get( + "format" + ) != WIFITRIP_FORMAT: + raise WifitripValidationError( + "Unsupported package format." + ) + + if manifest.get( + "format_version" + ) != WIFITRIP_VERSION: + raise WifitripValidationError( + "Unsupported .wifitrip format version: " + f"{manifest.get('format_version')}" + ) + + sessions = manifest.get( + "sessions" + ) + + if not isinstance( + sessions, + int, + ) or isinstance( + sessions, + bool, + ): + raise WifitripValidationError( + "manifest.sessions must be an integer." + ) + + if sessions < 0: + raise WifitripValidationError( + "manifest.sessions must not be negative." + ) + + versions = manifest.get( + "session_hash_versions" + ) + + if not isinstance( + versions, + list, + ): + raise WifitripValidationError( + "manifest.session_hash_versions " + "must be an array." + ) + + for version in versions: + if version != SESSION_HASH_VERSION: + raise WifitripValidationError( + "Unsupported session hash version: " + f"{version}" + ) + + +def _validate_sessions( + records, +): + sessions = {} + versions = set() + + for index, record in enumerate( + records + ): + context = ( + f"sessions.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + session_hash = _require_string( + record, + "session_hash", + context, + ) + + session_hash_version = _optional_integer( + record.get( + "session_hash_version" + ), + "session_hash_version", + context, + ) + + if session_hash_version != SESSION_HASH_VERSION: + raise WifitripValidationError( + f"{context}: unsupported " + "session_hash_version." + ) + + if session_hash in sessions: + raise WifitripValidationError( + f"{context}: duplicate session_hash." + ) + + start_time = _require_string( + record, + "start_time", + context, + ) + + end_time = record.get( + "end_time" + ) + + if end_time is not None and not isinstance( + end_time, + str, + ): + raise WifitripValidationError( + f"{context}: end_time must be " + "a string or null." + ) + + session_type = record.get( + "session_type" + ) + + if session_type not in ( + "gps", + "non_gps", + ): + raise WifitripValidationError( + f"{context}: invalid session_type." + ) + + sessions[ + session_hash + ] = { + "session_hash": + session_hash, + "session_hash_version": + session_hash_version, + "start_time": + start_time, + "end_time": + end_time, + "session_type": + session_type, + } + + versions.add( + session_hash_version + ) + + return sessions, versions + + +def _validate_access_points( + records, +): + access_points = {} + + for index, record in enumerate( + records + ): + context = ( + f"access_points.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + bssid = _validate_bssid( + record.get( + "bssid" + ), + context, + ) + + if bssid in access_points: + raise WifitripValidationError( + f"{context}: duplicate BSSID." + ) + + access_points[ + bssid + ] = { + "bssid": bssid, + } + + return access_points + + +def _validate_gps_tracks( + records, + sessions, +): + sequence_numbers = {} + + for index, record in enumerate( + records + ): + context = ( + f"gps_tracks.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + session_hash = _require_string( + record, + "session_hash", + context, + ) + + if session_hash not in sessions: + raise WifitripValidationError( + f"{context}: unknown session_hash." + ) + + sequence_no = _optional_integer( + record.get( + "sequence_no" + ), + "sequence_no", + context, + ) + + if sequence_no is None or sequence_no < 0: + raise WifitripValidationError( + f"{context}: invalid sequence_no." + ) + + key = ( + session_hash, + sequence_no, + ) + + if key in sequence_numbers: + raise WifitripValidationError( + f"{context}: duplicate sequence_no." + ) + + sequence_numbers[key] = True + + for field in ( + "latitude", + "longitude", + "speed", + ): + _optional_number( + record.get( + field + ), + field, + context, + ) + + timestamp = record.get( + "timestamp" + ) + + if timestamp is not None and not isinstance( + timestamp, + str, + ): + raise WifitripValidationError( + f"{context}: timestamp must " + "be a string or null." + ) + + +def _validate_observations( + records, + sessions, + access_points, +): + for index, record in enumerate( + records + ): + context = ( + f"observations.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + session_hash = _require_string( + record, + "session_hash", + context, + ) + + if session_hash not in sessions: + raise WifitripValidationError( + f"{context}: unknown session_hash." + ) + + bssid = _validate_bssid( + record.get( + "bssid" + ), + context, + ) + + if bssid not in access_points: + raise WifitripValidationError( + f"{context}: unknown BSSID." + ) + + _require_string( + record, + "observed_at", + context, + ) + + for field in ( + "latitude", + "longitude", + "speed", + ): + _optional_number( + record.get( + field + ), + field, + context, + ) + + for field in ( + "rssi", + "channel", + "frequency", + ): + _optional_integer( + record.get( + field + ), + field, + context, + ) + + for field in ( + "essid", + "encryption", + "cipher", + "akm", + "country", + ): + value = record.get( + field + ) + + if value is not None and not isinstance( + value, + str, + ): + raise WifitripValidationError( + f"{context}: {field} must " + "be a string or null." + ) + + +def _validate_handshakes( + records, + sessions, + access_points, +): + handshake_keys = {} + + for index, record in enumerate( + records + ): + context = ( + f"handshakes.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + session_hash = _require_string( + record, + "session_hash", + context, + ) + + if session_hash not in sessions: + raise WifitripValidationError( + f"{context}: unknown session_hash." + ) + + handshake_key = _require_string( + record, + "handshake_key", + context, + ) + + key = ( + session_hash, + handshake_key, + ) + + if key in handshake_keys: + raise WifitripValidationError( + f"{context}: duplicate handshake_key." + ) + + handshake_keys[key] = True + + bssid = _validate_bssid( + record.get( + "bssid" + ), + context, + ) + + if bssid not in access_points: + raise WifitripValidationError( + f"{context}: unknown BSSID." + ) + + _require_string( + record, + "type", + context, + ) + + for field in ( + "hash22000", + "message_pair", + "captured_at", + ): + value = record.get( + field + ) + + if value is not None and not isinstance( + value, + str, + ): + raise WifitripValidationError( + f"{context}: {field} must " + "be a string or null." + ) + + for field in ( + "latitude", + "longitude", + "speed", + ): + _optional_number( + record.get( + field + ), + field, + context, + ) + + return handshake_keys + + +def _validate_credentials( + records, + sessions, + access_points, + handshake_keys, +): + for index, record in enumerate( + records + ): + context = ( + f"credentials.json[{index}]" + ) + + _ensure_dict( + record, + context, + ) + + session_hash = _require_string( + record, + "session_hash", + context, + ) + + if session_hash not in sessions: + raise WifitripValidationError( + f"{context}: unknown session_hash." + ) + + bssid = _validate_bssid( + record.get( + "bssid" + ), + context, + ) + + if bssid not in access_points: + raise WifitripValidationError( + f"{context}: unknown BSSID." + ) + + password = _require_string( + record, + "password", + context, + ) + + handshake_key = record.get( + "handshake_key" + ) + + if handshake_key is not None: + if not isinstance( + handshake_key, + str, + ): + raise WifitripValidationError( + f"{context}: handshake_key must " + "be a string or null." + ) + + if ( + session_hash, + handshake_key, + ) not in handshake_keys: + raise WifitripValidationError( + f"{context}: unknown handshake_key." + ) + + for field in ( + "source", + "created_at", + ): + value = record.get( + field + ) + + if value is not None and not isinstance( + value, + str, + ): + raise WifitripValidationError( + f"{context}: {field} must " + "be a string or null." + ) + + verified = record.get( + "verified" + ) + + if not isinstance( + verified, + (int, bool), + ): + raise WifitripValidationError( + f"{context}: verified must be numeric." + ) + + +def _load_package( + path, +): + path = Path( + path + ) + + if not path.exists(): + raise FileNotFoundError( + f"File not found:\n{path}" + ) + + if not path.is_file(): + raise ValueError( + f"Not a regular file:\n{path}" + ) + + try: + archive = zipfile.ZipFile( + path, + "r", + ) + except zipfile.BadZipFile as error: + raise WifitripValidationError( + "Input file is not a valid ZIP archive." + ) from error + + try: + names = archive.namelist() + + if len(names) != len( + set(names) + ): + raise WifitripValidationError( + "Archive contains duplicate file names." + ) + + missing = [ + filename + for filename in REQUIRED_FILES + if filename not in names + ] + + if missing: + raise WifitripValidationError( + "Archive is missing required files: " + + ", ".join( + missing + ) + ) + + manifest = _read_json( + archive, + "manifest.json", + ) + + sessions = _read_json( + archive, + "sessions.json", + ) + + access_points = _read_json( + archive, + "access_points.json", + ) + + gps_tracks = _read_json( + archive, + "gps_tracks.json", + ) + + observations = _read_json( + archive, + "observations.json", + ) + + handshakes = _read_json( + archive, + "handshakes.json", + ) + + credentials = _read_json( + archive, + "credentials.json", + ) + + finally: + archive.close() + + _validate_manifest( + manifest + ) + + sessions = _ensure_list( + sessions, + "sessions.json", + ) + + access_points = _ensure_list( + access_points, + "access_points.json", + ) + + gps_tracks = _ensure_list( + gps_tracks, + "gps_tracks.json", + ) + + observations = _ensure_list( + observations, + "observations.json", + ) + + handshakes = _ensure_list( + handshakes, + "handshakes.json", + ) + + credentials = _ensure_list( + credentials, + "credentials.json", + ) + + session_map, versions = _validate_sessions( + sessions + ) + + if manifest["sessions"] != len( + sessions + ): + raise WifitripValidationError( + "manifest.sessions does not match sessions.json." + ) + + if set( + manifest["session_hash_versions"] + ) != versions: + raise WifitripValidationError( + "manifest.session_hash_versions " + "does not match sessions.json." + ) + + access_point_map = _validate_access_points( + access_points + ) + + _validate_gps_tracks( + gps_tracks, + session_map, + ) + + _validate_observations( + observations, + session_map, + access_point_map, + ) + + handshake_keys = _validate_handshakes( + handshakes, + session_map, + access_point_map, + ) + + _validate_credentials( + credentials, + session_map, + access_point_map, + handshake_keys, + ) + + return { + "manifest": manifest, + "sessions": sessions, + "access_points": access_points, + "gps_tracks": gps_tracks, + "observations": observations, + "handshakes": handshakes, + "credentials": credentials, + } + + +def preflight_wifitrip( + path, +): + started_at = datetime.now( + timezone.utc + ) + + package = _load_package( + path + ) + + session_hashes = { + record["session_hash"] + for record in package["sessions"] + } + + result = { + "valid": True, + "file": str( + path + ), + "format_version": + package["manifest"]["format_version"], + "sessions": len( + package["sessions"] + ), + "access_points": len( + package["access_points"] + ), + "gps_points": len( + package["gps_tracks"] + ), + "observations": len( + package["observations"] + ), + "handshakes": len( + package["handshakes"] + ), + "credentials": len( + package["credentials"] + ), + "session_hashes": len( + session_hashes + ), + "duration": ( + datetime.now( + timezone.utc + ) - started_at + ).total_seconds(), + } + + logger.info( + "wifitrip preflight successful: " + "file=%s sessions=%d access_points=%d " + "gps_points=%d observations=%d " + "handshakes=%d credentials=%d", + path, + result["sessions"], + result["access_points"], + result["gps_points"], + result["observations"], + result["handshakes"], + result["credentials"], + ) + + return result + + +# ============================================================ +# Import helpers +# ============================================================ + +def _session_exists_by_hash( + conn, + session_hash, + session_hash_version, +): + row = conn.execute( + """ + SELECT id + FROM capture_sessions + WHERE + session_hash=? + AND session_hash_version=? + LIMIT 1 + """, + ( + session_hash, + session_hash_version, + ), + ).fetchone() + + if row is None: + return None + + return row["id"] + + +def _get_or_create_import_ap( + conn, + bssid, +): + row = conn.execute( + """ + SELECT id + FROM access_points + WHERE bssid=? + """, + ( + bssid, + ), + ).fetchone() + + if row is not None: + return row["id"], False + + cursor = conn.execute( + """ + INSERT INTO access_points ( + bssid + ) + VALUES (?) + """, + ( + bssid, + ), + ) + + return cursor.lastrowid, True + + +def _import_gps_tracks( + conn, + session_id, + session_hash, + gps_tracks, +): + records = [ + record + for record in gps_tracks + if record["session_hash"] == session_hash + ] + + for record in sorted( + records, + key=lambda value: value["sequence_no"], + ): + conn.execute( + """ + INSERT INTO gps_track ( + session_id, + sequence_no, + latitude, + longitude, + speed, + timestamp + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + session_id, + record["sequence_no"], + record["latitude"], + record["longitude"], + record["speed"], + record["timestamp"], + ), + ) + + return len( + records + ) + + +def _import_observations( + conn, + session_id, + session_hash, + observations, + ap_map, +): + records = [ + record + for record in observations + if record["session_hash"] == session_hash + ] + + for record in records: + bssid = _normalise_bssid( + record["bssid"] + ) + + access_point_id = ap_map[ + bssid + ] + + conn.execute( + """ + INSERT INTO access_point_observations ( + access_point_id, + session_id, + observed_at, + latitude, + longitude, + speed, + rssi, + channel, + frequency, + essid, + encryption, + cipher, + akm, + country + ) + VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, + ?, ?, ?, ?, ?, ? + ) + """, + ( + access_point_id, + session_id, + record["observed_at"], + record["latitude"], + record["longitude"], + record["speed"], + record["rssi"], + record["channel"], + record["frequency"], + record["essid"], + record["encryption"], + record["cipher"], + record["akm"], + record["country"], + ), + ) + + return len( + records + ) + + +def _import_handshakes( + conn, + session_id, + session_hash, + handshakes, + ap_map, +): + records = [ + record + for record in handshakes + if record["session_hash"] == session_hash + ] + + handshake_map = {} + + for record in records: + bssid = _normalise_bssid( + record["bssid"] + ) + + access_point_id = ap_map[ + bssid + ] + + cursor = conn.execute( + """ + INSERT INTO handshakes ( + access_point_id, + session_id, + type, + hash22000, + message_pair, + captured_at, + latitude, + longitude, + speed + ) + VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, ? + ) + """, + ( + access_point_id, + session_id, + record["type"], + record["hash22000"], + record["message_pair"], + record["captured_at"], + record["latitude"], + record["longitude"], + record["speed"], + ), + ) + + local_id = cursor.lastrowid + + handshake_map[ + record["handshake_key"] + ] = local_id + + if record["type"] == "PMKID": + conn.execute( + """ + UPDATE access_points + SET has_pmkid=1 + WHERE id=? + """, + ( + access_point_id, + ), + ) + + if record["type"] == "EAPOL": + conn.execute( + """ + UPDATE access_points + SET has_handshake=1 + WHERE id=? + """, + ( + access_point_id, + ), + ) + + return len( + records + ), handshake_map + + +def _update_imported_ap_statistics( + conn, + ap_map, + session_id, +): + for access_point_id in ap_map.values(): + row = conn.execute( + """ + SELECT + COUNT(*) AS count, + MIN(observed_at) AS first_seen, + MAX(observed_at) AS last_seen + FROM access_point_observations + WHERE + access_point_id=? + AND session_id=? + """, + ( + access_point_id, + session_id, + ), + ).fetchone() + + if row["count"] == 0: + continue + + latest = conn.execute( + """ + SELECT + observed_at, + latitude, + longitude, + speed, + rssi, + channel, + frequency, + essid, + encryption, + cipher, + akm, + country + FROM access_point_observations + WHERE + access_point_id=? + AND session_id=? + ORDER BY + observed_at DESC, + id DESC + LIMIT 1 + """, + ( + access_point_id, + session_id, + ), + ).fetchone() + + current = conn.execute( + """ + SELECT + first_seen, + last_seen + FROM access_points + WHERE id=? + """, + ( + access_point_id, + ), + ).fetchone() + + first_seen = row["first_seen"] + + if current["first_seen"] is not None: + first_seen = min( + current["first_seen"], + first_seen, + ) + + last_seen = row["last_seen"] + + if current["last_seen"] is not None: + last_seen = max( + current["last_seen"], + last_seen, + ) + + conn.execute( + """ + UPDATE access_points + SET + first_seen=?, + last_seen=?, + times_seen= + COALESCE(times_seen, 0) + + ?, + last_rssi=?, + last_latitude=?, + last_longitude=?, + last_speed=?, + channel=?, + frequency=?, + essid=?, + encryption=?, + cipher=?, + akm=?, + country=? + WHERE id=? + """, + ( + first_seen, + last_seen, + row["count"], + latest["rssi"], + latest["latitude"], + latest["longitude"], + latest["speed"], + latest["channel"], + latest["frequency"], + latest["essid"], + latest["encryption"], + latest["cipher"], + latest["akm"], + latest["country"], + access_point_id, + ), + ) + + +def _import_credentials( + conn, + session_hash, + credentials, + ap_map, + handshake_map, +): + records = [ + record + for record in credentials + if record["session_hash"] == session_hash + ] + + imported = 0 + + for record in records: + bssid = _normalise_bssid( + record["bssid"] + ) + + access_point_id = ap_map[ + bssid + ] + + handshake_id = None + + if record["handshake_key"] is not None: + handshake_id = handshake_map[ + record["handshake_key"] + ] + + existing = conn.execute( + """ + SELECT id + FROM credentials + WHERE + access_point_id=? + AND password=? + LIMIT 1 + """, + ( + access_point_id, + record["password"], + ), + ).fetchone() + + if existing is not None: + continue + + conn.execute( + """ + INSERT INTO credentials ( + access_point_id, + handshake_id, + password, + source, + created_at, + verified + ) + VALUES ( + ?, ?, ?, ?, ?, ? + ) + """, + ( + access_point_id, + handshake_id, + record["password"], + record["source"], + record["created_at"], + record["verified"], + ), + ) + + conn.execute( + """ + UPDATE access_points + SET is_cracked=1 + WHERE id=? + """, + ( + access_point_id, + ), + ) + + imported += 1 + + return imported + + +def _import_session( + conn, + package, + session_record, +): + session_hash = session_record[ + "session_hash" + ] + + session_hash_version = session_record[ + "session_hash_version" + ] + + result = _new_session_result( + session_hash + ) + + existing_id = _session_exists_by_hash( + conn, + session_hash, + session_hash_version, + ) + + if existing_id is not None: + result["status"] = "DUPLICATE" + return result + + try: + conn.execute( + "BEGIN" + ) + + cursor = conn.execute( + """ + INSERT INTO capture_sessions ( + start_time, + end_time, + capture_file, + session_hash, + session_hash_version + ) + VALUES (?, ?, ?, ?, ?) + """, + ( + session_record["start_time"], + session_record["end_time"], + "imported.wifitrip", + session_hash, + session_hash_version, + ), + ) + + session_id = cursor.lastrowid + + ap_records = package[ + "access_points" + ] + + referenced_bssids = set() + + for record in package[ + "observations" + ]: + if record["session_hash"] == session_hash: + referenced_bssids.add( + _normalise_bssid( + record["bssid"] + ) + ) + + for record in package[ + "handshakes" + ]: + if record["session_hash"] == session_hash: + referenced_bssids.add( + _normalise_bssid( + record["bssid"] + ) + ) + + for record in package[ + "credentials" + ]: + if record["session_hash"] == session_hash: + referenced_bssids.add( + _normalise_bssid( + record["bssid"] + ) + ) + + package_bssids = { + _normalise_bssid( + record["bssid"] + ) + for record in ap_records + } + + ap_map = {} + + for bssid in sorted( + referenced_bssids + ): + if bssid not in package_bssids: + raise WifitripValidationError( + "Session references an AP not present " + "in access_points.json: " + f"{bssid}" + ) + + access_point_id, _ = ( + _get_or_create_import_ap( + conn, + bssid, + ) + ) + + ap_map[ + bssid + ] = access_point_id + + result["access_points"] = len( + ap_map + ) + + result["gps_points"] = _import_gps_tracks( + conn, + session_id, + session_hash, + package["gps_tracks"], + ) + + result["observations"] = _import_observations( + conn, + session_id, + session_hash, + package["observations"], + ap_map, + ) + + ( + result["handshakes"], + handshake_map, + ) = _import_handshakes( + conn, + session_id, + session_hash, + package["handshakes"], + ap_map, + ) + + calculated_hash = _calculate_session_hash( + conn, + session_id, + ) + + if calculated_hash != session_hash: + raise WifitripHashMismatchError( + "Session hash mismatch: " + f"expected {session_hash}, " + f"calculated {calculated_hash}" + ) + + _update_imported_ap_statistics( + conn, + ap_map, + session_id, + ) + + result["credentials"] = _import_credentials( + conn, + session_hash, + package["credentials"], + ap_map, + handshake_map, + ) + + conn.commit() + + result["status"] = "NEW" + + logger.info( + "wifitrip session imported: " + "hash=%s access_points=%d " + "gps_points=%d observations=%d " + "handshakes=%d credentials=%d", + session_hash, + result["access_points"], + result["gps_points"], + result["observations"], + result["handshakes"], + result["credentials"], + ) + + return result + + except Exception as error: + conn.rollback() + + result["status"] = "FAILED" + result["error"] = str( + error + ) + + logger.error( + "wifitrip session import failed: " + "hash=%s error=%s", + session_hash, + error, + ) + + return result + + +# ============================================================ +# Import +# ============================================================ + +def import_wifitrip( + conn, + path, +): + started_at = datetime.now( + timezone.utc + ) + + package = _load_package( + path + ) + + results = [] + + for session_record in package[ + "sessions" + ]: + result = _import_session( + conn, + package, + session_record, + ) + + results.append( + result + ) + + imported = sum( + 1 + for result in results + if result["status"] == "NEW" + ) + + duplicates = sum( + 1 + for result in results + if result["status"] == "DUPLICATE" + ) + + failed = sum( + 1 + for result in results + if result["status"] == "FAILED" + ) + + duration = ( + datetime.now( + timezone.utc + ) - started_at + ).total_seconds() + + result = { + "file": str( + path + ), + "valid": True, + "sessions": len( + results + ), + "imported": imported, + "duplicates": duplicates, + "failed": failed, + "results": results, + "duration": duration, + } + + logger.info( + "wifitrip import completed: " + "file=%s sessions=%d imported=%d " + "duplicates=%d failed=%d duration=%.3fs", + path, + result["sessions"], + imported, + duplicates, + failed, + duration, + ) + + return result + \ No newline at end of file