UNPKG

@alvarosilva/hex-address

Version:

Convert GPS coordinates to memorable hex addresses using H3

608 lines (602 loc) 19 kB
/** * Configuration metadata */ interface ConfigMetadata { alphabet: string; base26_identifier: string; binary_array: number[]; selected_letters: string[]; auto_generated: boolean; generation_method: string; total_syllables: number; total_combinations: number; h3_target_space: number; coverage_ratio: number; coverage_multiple: string; } /** * Configuration for syllable system */ interface SyllableConfig { name: string; description: string; consonants: string[]; vowels: string[]; address_length: number; h3_resolution: number; metadata?: ConfigMetadata; } /** * GPS coordinates (latitude, longitude) */ type Coordinates = [number, number]; /** * Result from round-trip testing */ interface RoundTripResult { success: boolean; originalCoordinates: Coordinates; syllableAddress: string; resultCoordinates: Coordinates; distanceErrorMeters: number; precise: boolean; } /** * System information and statistics */ interface SystemInfo { h3Resolution: number; totalH3Cells: number; consonants: string[]; vowels: string[]; totalSyllables: number; addressLength: number; addressSpace: number; coveragePercentage: number; precisionMeters: number; } /** * Geographic bounds */ interface GeographicBounds { north: number; south: number; east: number; west: number; } /** * Result from partial address location estimation */ interface PartialLocationEstimate { centerCoordinate: Coordinates; bounds: GeographicBounds; confidence: number; estimatedAreaKm2: number; completenessLevel: number; suggestedRefinements?: string[]; samplePoints?: Coordinates[]; comprehensiveMode?: boolean; } /** * Custom error class for H3 syllable system errors */ declare class H3SyllableError extends Error { constructor(message: string); } /** * Error thrown when coordinate/syllable conversion fails */ declare class ConversionError extends H3SyllableError { constructor(message: string); } /** * A single character change in a phonetic alternative */ interface PhoneticChange { position: number; from: string; to: string; } /** * A phonetic alternative to the original address */ interface PhoneticAlternative { address: string; coordinates: Coordinates; distanceKm: number; change: PhoneticChange; } /** * Types of validation errors */ type ValidationErrorType = 'format' | 'syllable' | 'geographic' | 'config' | 'length'; /** * Detailed validation error information */ interface ValidationError { type: ValidationErrorType; message: string; position?: number; suggestions?: string[]; received?: string; expected?: string[]; } /** * Comprehensive validation result */ interface ValidationResult { isValid: boolean; errors: ValidationError[]; validParts: string[]; suggestions?: string[]; } /** * Result from address analysis including phonetic alternatives */ interface AddressAnalysis { isValid: boolean; address: string; coordinates?: Coordinates; phoneticAlternatives: PhoneticAlternative[]; validation?: ValidationResult; } /** * H3 Syllable Address System * * Converts GPS coordinates to memorable syllable addresses using H3 Level 15 cells. * * Standard Process: * 1. GPS Coordinates → H3 Cell ID (H3 hexagonal identifier) * 2. H3 Cell ID → Hierarchical Array (path through H3 tree structure) * 3. Hierarchical Array → Integer Index (unique mathematical index) * 4. Integer Index → Syllable Address (human-readable syllables) */ declare class H3SyllableSystem { private config; private configName; private syllableToIndex; private indexToSyllable; private hamiltonianPath; private readonly consonantCount; private readonly vowelCount; private readonly totalSyllables; constructor(configName?: string); /** * Initialize syllable lookup tables for fast conversion */ private initializeSyllableTables; /** * Initialize Hamiltonian path for level 0 cells (optimized array-based approach) */ private initializeHamiltonianPath; /** * Convert geographic coordinates to syllable address */ coordinateToAddress(latitude: number, longitude: number): string; /** * Convert syllable address to geographic coordinates */ addressToCoordinate(syllableAddress: string): Coordinates; /** * Check if a syllable address maps to a real H3 location * * @param syllableAddress - The address to validate * @param detailed - If true, returns ValidationResult with detailed errors and phonetic suggestions * @returns boolean or ValidationResult based on detailed parameter * * @example * ```typescript * // Simple validation * system.isValidAddress("dinenunukiwufeme") // → true * system.isValidAddress("invalid") // → false * * // Detailed validation with phonetic suggestions * const result = system.isValidAddress("helloworld", true); * console.log(result.errors[0].suggestions); // → ['fello', 'jello', 'mello'] * ``` */ isValidAddress(syllableAddress: string): boolean; isValidAddress(syllableAddress: string, detailed: true): ValidationResult; isValidAddress(syllableAddress: string, detailed: false): boolean; /** * Comprehensive validation with detailed error reporting * @internal */ private validateAddress; /** * Validate address format (length, structure) */ private validateFormat; /** * Validate individual syllables */ private validateSyllables; /** * Validate geographic existence */ private validateGeographic; /** * Find similar valid addresses by modifying the last few syllables */ private findSimilarValidAddresses; /** * Get valid phonetic substitutions for a character based on current config */ private getValidPhoneticSubstitutions; /** * Get phonetic suggestions for an invalid character */ private getCharacterSuggestions; /** * Calculate distance between two coordinates in kilometers */ private calculateDistanceKm; /** * Analyze a syllable address and provide phonetic alternatives */ analyzeAddress(syllableAddress: string): AddressAnalysis; /** * Reconstruct address format (with separators) from clean character string */ private reconstructAddressFormat; /** * Estimate location and bounds from a partial syllable address */ estimateLocationFromPartial(partialAddress: string, comprehensive?: boolean): PartialLocationEstimate; /** * Test round-trip conversion accuracy */ testRoundTrip(latitude: number, longitude: number): RoundTripResult; /** * Get system information and statistics */ getSystemInfo(): SystemInfo; /** * Clear internal cache (no-op - cache removed for performance) */ clearCache(): void; /** * Get current configuration */ getConfig(): SyllableConfig; /** * Get current configuration name */ getConfigName(): string; /** * Create H3 system from a list of letters */ static fromLetters(_letters: string[]): H3SyllableSystem; /** * Create H3 system with language-optimized configuration */ static suggestForLanguage(language?: string, _precisionMeters?: number): H3SyllableSystem; /** * Validate coordinates are within valid ranges */ private validateCoordinates; /** * Convert H3 Cell ID to Hierarchical Array */ private h3CellIdToHierarchicalArray; /** * Convert Hierarchical Array to H3 Cell ID */ private hierarchicalArrayToH3CellId; /** * Convert Hierarchical Array to Integer Index using mixed-radix encoding */ private hierarchicalArrayToIntegerIndex; /** * Convert Integer Index to Hierarchical Array */ private integerIndexToHierarchicalArray; /** * Convert Integer Index to Syllable Address * Orders syllables from coarse to fine geography (most significant first) */ private integerIndexToSyllableAddress; /** * Format syllable address as concatenated string */ private formatSyllableAddress; /** * Convert Syllable Address to Integer Index * Processes syllables from coarse to fine geography (most significant first) */ private syllableAddressToIntegerIndex; /** * Parse partial address into syllables array */ private parsePartialAddress; /** * Calculate the range of complete addresses for a partial address */ private calculateAddressRange; /** * Get the minimum and maximum syllables for the current config */ private getMinMaxSyllables; /** * Calculate geographic bounds from min and max coordinates */ private calculateGeographicBounds; /** * Calculate center point from min and max coordinates */ private calculateCenter; /** * Calculate area in square kilometers from geographic bounds */ private calculateAreaKm2; /** * Calculate confidence score based on completeness level */ private calculateConfidence; /** * Get suggested refinements (next possible syllables or vowels) */ private getSuggestedRefinements; /** * Find valid address range with smart fallback when min/max addresses are invalid */ private findValidAddressRange; /** * Increment address intelligently from left to right with carry-over */ private incrementAddress; /** * Decrement address intelligently from left to right with borrow */ private decrementAddress; /** * Generate sample addresses using comprehensive sampling for all possible syllables at the next level */ private generateComprehensiveSamples; /** * Helper method to add sample addresses for a given prefix using comprehensive sampling */ private addComprehensiveSamplesForPrefix; /** * Calculate geographic bounds from multiple coordinate points */ private calculateBoundsFromPoints; /** * Calculate center coordinate from multiple points */ private calculateCenterFromPoints; } /** * Browser-compatible configuration loader * Configurations are bundled at build time for universal compatibility */ declare class ConfigLoader { private configs; constructor(); /** * Load bundled configurations */ private loadBundledConfigs; /** * Get a configuration by name */ getConfig(configName: string): SyllableConfig; /** * Get all configurations */ getAllConfigs(): Map<string, SyllableConfig>; /** * List all configuration names */ listConfigs(): string[]; /** * Get configuration metadata */ getConfigInfo(configName: string): { name: string; description: string; consonantsCount: number; vowelsCount: number; addressLength: number; totalCombinations?: number; coverageRatio?: number; }; } /** * Get a configuration by name using the global loader */ declare function getConfig(configName: string): SyllableConfig; /** * Get all configurations using the global loader */ declare function getAllConfigs(): Map<string, SyllableConfig>; /** * List all configuration names using the global loader */ declare function listConfigs(): string[]; /** * Hex Address System - JavaScript/TypeScript Package * * Convert GPS coordinates to memorable hex addresses using H3. * * @example * ```typescript * import { H3SyllableSystem, isValidSyllableAddress } from 'hex-address'; * * // Initialize system * const system = new H3SyllableSystem('ascii-elomr'); * * // Convert coordinates to syllable address * const address = system.coordinateToAddress(48.8566, 2.3522); * console.log(address); // "dinenunukiwufeme" * * // Convert back to coordinates * const [lat, lon] = system.addressToCoordinate(address); * console.log(`${lat.toFixed(6)}, ${lon.toFixed(6)}`); // 48.856602, 2.352198 * * // Validate addresses * const isValid = system.isValidAddress(address); * console.log(isValid); // true * ``` */ /** * Convert coordinates to syllable address using specified configuration */ declare function coordinateToAddress(latitude: number, longitude: number, configName?: string): string; /** * Convert syllable address to coordinates using specified configuration */ declare function addressToCoordinate(syllableAddress: string, configName?: string): [number, number]; /** * Check if syllable address corresponds to a real location * * Some syllable combinations don't map to actual H3 locations, just like * how "999999 Main Street" might not exist in the real world. * * @param syllableAddress - The address to validate * @param configName - Configuration to use * @param detailed - If true, returns detailed ValidationResult with phonetic suggestions * * @example * ```typescript * // Simple validation * isValidAddress("dinenunukiwufeme") // → true * isValidAddress("invalid") // → false * * // Detailed validation with phonetic suggestions * const result = isValidAddress("helloworld", "ascii-elomr", true); * console.log(result.errors[0].suggestions); // → ['fello', 'jello', 'mello'] * ``` */ declare function isValidAddress(syllableAddress: string, configName?: string): boolean; declare function isValidAddress(syllableAddress: string, configName: string, detailed: true): ValidationResult; /** * Estimate location and bounds from a partial syllable address * * This function calculates the geographic area that could be represented by * a partial syllable address by determining the minimum and maximum complete * addresses that start with the given partial address. */ declare function estimateLocationFromPartial(partialAddress: string, configName?: string, comprehensive?: boolean): PartialLocationEstimate; /** * Analyze a syllable address and provide phonetic alternatives * * This function validates the address and generates alternative addresses * for characters that could have been misheard due to phonetic similarity. * Useful for confirming addresses received verbally. * * @example * ```typescript * const analysis = analyzeAddress("de-ma-su-cu|du-ve-gu-ba"); * console.log(analysis.isValid); // true * console.log(analysis.phoneticAlternatives.length); // Number of valid alternatives * analysis.phoneticAlternatives.forEach(alt => { * console.log(`${alt.address} (${alt.distanceKm}km away, ${alt.change.from}→${alt.change.to})`); * }); * ``` */ declare function analyzeAddress(syllableAddress: string, configName?: string): AddressAnalysis; /** * Get detailed information about a configuration */ declare function getConfigInfo(configName: string): any; /** * List all available configuration names */ declare function listAvailableConfigs(): string[]; /** * Create H3 system from a list of letters */ declare function createSystemFromLetters(letters: string[]): H3SyllableSystem; /** * Create H3 system with language-optimized configuration */ declare function suggestSystemForLanguage(language?: string, precisionMeters?: number): H3SyllableSystem; /** * List all auto-generated configuration names */ declare function listAutoGeneratedConfigs(): string[]; /** * Find configurations that use exactly these letters */ declare function findConfigsByLetters(letters: string[]): string[]; /** * Calculate distance between two hex addresses in kilometers * * @param address1 - First hex address * @param address2 - Second hex address * @param configName - Configuration to use * @returns Distance in kilometers * * @example * ```typescript * const distance = calculateDistance( * "dinenunukiwufeme", * "dinenunukiwufene", * "ascii-elomr" * ); * console.log(`Distance: ${distance.toFixed(2)} km`); * ``` */ declare function calculateDistance(address1: string, address2: string, configName?: string): number; /** * Find hex addresses within a radius of a center address * * @param centerAddress - Center hex address * @param radiusKm - Radius in kilometers * @param configName - Configuration to use * @returns Array of nearby addresses with distances * * @example * ```typescript * const nearby = findNearbyAddresses("dinenunukiwufeme", 1.0); * nearby.forEach(item => { * console.log(`${item.address}: ${item.distance.toFixed(3)}km`); * }); * ``` */ declare function findNearbyAddresses(centerAddress: string, radiusKm: number, configName?: string): Array<{ address: string; distance: number; coordinates: [number, number]; }>; /** * Get geographic bounds (bounding box) for a hex address * * @param address - Hex address * @param configName - Configuration to use * @returns Geographic bounds object * * @example * ```typescript * const bounds = getAddressBounds("dinenunukiwufeme"); * console.log(`SW: ${bounds.south}, ${bounds.west}`); * console.log(`NE: ${bounds.north}, ${bounds.east}`); * ``` */ declare function getAddressBounds(address: string, configName?: string): GeographicBounds; /** * Cluster nearby hex addresses into groups * * @param addresses - Array of hex addresses to cluster * @param maxDistanceKm - Maximum distance between addresses in same cluster * @param configName - Configuration to use * @returns Array of clusters, each containing grouped addresses * * @example * ```typescript * const addresses = ["addr1", "addr2", "addr3", "addr4"]; * const clusters = clusterAddresses(addresses, 0.5); * console.log(`Found ${clusters.length} clusters`); * ``` */ declare function clusterAddresses(addresses: string[], maxDistanceKm: number, configName?: string): Array<{ addresses: string[]; center: [number, number]; bounds: GeographicBounds; }>; declare const version = "1.3.1"; declare const author = "\u00C1lvaro Silva"; declare const license = "MIT"; declare const description = "Convert GPS coordinates to memorable hex addresses"; export { type AddressAnalysis, ConfigLoader, ConversionError, type Coordinates, type GeographicBounds, H3SyllableError, H3SyllableSystem, type PartialLocationEstimate, type PhoneticAlternative, type PhoneticChange, type RoundTripResult, type SyllableConfig, type SystemInfo, type ValidationError, type ValidationErrorType, type ValidationResult, addressToCoordinate, analyzeAddress, author, calculateDistance, clusterAddresses, coordinateToAddress, createSystemFromLetters, description, estimateLocationFromPartial, findConfigsByLetters, findNearbyAddresses, getAddressBounds, getAllConfigs, getConfig, getConfigInfo, isValidAddress, license, listAutoGeneratedConfigs, listAvailableConfigs, listConfigs, suggestSystemForLanguage, version };