@molecule/api-geolocation-molecule
Provider bond · geolocation · API (Node) · v1.1.1 · Apache-2.0
molecule.dev hosted geocoding provider — address lookups billed to your molecule project, no vendor account
npm install @molecule/api-geolocation-moleculenpm · Source on GitHub · Implements @molecule/api-geolocation
How it works
@molecule/api-geolocation-molecule is a provider bond on the API (Node) side: it implements the geolocation core interface (@molecule/api-geolocation) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
Works with: @molecule/api-geolocation, @molecule/api-secrets
Secrets: MOLECULE_API_KEY
Reference
molecule.dev hosted geocoding provider — address lookups billed to your molecule project, no vendor account
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Type
provider
Installation
npm install @molecule/api-geolocation-molecule @molecule/api-geolocation @molecule/api-secrets
API
Interfaces
MoleculeGeolocationConfig
Options for createProvider. Every field falls back to an env var,
so the zero-argument provider export works from .env alone.
interface MoleculeGeolocationConfig {
/**
* The molecule project API key (`mk_…`), or the sandbox token molecule.dev
* writes for in-IDE apps (`mbk_…`). Defaults to `MOLECULE_API_KEY`.
*/
apiKey?: string
/**
* The hosted services base URL, without a trailing slash. Defaults to
* `MOLECULE_SERVICES_URL`, then `https://api.molecule.dev/api/v1/services`.
*/
servicesUrl?: string
/** Per-request timeout in milliseconds. Default 15000. */
timeoutMs?: number
}
ProcessEnv
Environment variables this provider reads.
interface ProcessEnv {
MOLECULE_API_KEY?: string
MOLECULE_SERVICES_URL?: string
}
Classes
MoleculeServiceError
Error thrown for a refused or failed hosted-service call.
class MoleculeServiceError extends Error {
/** HTTP status from molecule.dev. */
readonly status: number
/** Stable error key from molecule.dev, e.g. `broker.error.budgetExceeded`. */
readonly errorKey: string | undefined
/**
* Create the error.
*
* @param message - Human-readable message.
* @param status - HTTP status.
* @param errorKey - Stable error key, when the service sent one.
* @param cause - The underlying error, if any.
*/
constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause })
this.name = 'MoleculeServiceError'
this.status = status
this.errorKey = errorKey
}
}
MoleculeGeolocationProvider
Geocoding provider backed by molecule.dev's hosted service.
class MoleculeGeolocationProvider implements GeolocationProvider {
readonly name = 'molecule'
private readonly apiKey: string
private readonly servicesUrl: string
private readonly timeoutMs: number
/**
* Create the provider.
*
* @param config - Options; each falls back to its env var.
*/
constructor(config: MoleculeGeolocationConfig = {}) {
this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
this.servicesUrl = resolveServicesUrl(
config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
)
this.timeoutMs = config.timeoutMs ?? 15_000
}
/**
* Geocode an address.
*
* @param address - The address or place name (at most 300 characters).
* @returns Results in the provider's relevance order; `[]` when nothing
* matched or the point is outside the loaded coverage.
*/
async geocode(address: string): Promise<GeoResult[]> {
if (typeof address !== 'string' || address.trim().length === 0) {
throw new MoleculeServiceError(
'The address must be non-empty text.',
400,
'hostedServices.error.invalidInput',
)
}
if (address.length > GEOCODING_SERVICE_LIMITS.maxAddressChars) {
throw new MoleculeServiceError(
`The address is ${address.length} characters. ${HINTS[413]}`,
413,
'hostedServices.error.inputTooLarge',
)
}
return this.request('geocode', { address })
}
/**
* Reverse geocode a coordinate.
*
* @param lat - Latitude in decimal degrees (-90..90).
* @param lng - Longitude in decimal degrees (-180..180).
* @returns Results in specificity order; `[]` when nothing matched.
*/
async reverseGeocode(lat: number, lng: number): Promise<GeoResult[]> {
if (!Number.isFinite(lat) || Math.abs(lat) > GEOCODING_SERVICE_LIMITS.maxLat) {
throw new MoleculeServiceError(
`"lat" must be a number between -${GEOCODING_SERVICE_LIMITS.maxLat} and ${GEOCODING_SERVICE_LIMITS.maxLat}.`,
400,
'hostedServices.error.invalidInput',
)
}
if (!Number.isFinite(lng) || Math.abs(lng) > GEOCODING_SERVICE_LIMITS.maxLng) {
throw new MoleculeServiceError(
`"lng" must be a number between -${GEOCODING_SERVICE_LIMITS.maxLng} and ${GEOCODING_SERVICE_LIMITS.maxLng}.`,
400,
'hostedServices.error.invalidInput',
)
}
return this.request('reverse', { lat, lng })
}
/**
* Calculates the great-circle distance between two points (Haversine, local
* math — no API call, not metered).
*
* @param from - The starting coordinate.
* @param to - The ending coordinate.
* @param unit - `'km'` (default) or `'mi'`.
* @returns The distance.
*/
distance(
from: { lat: number; lng: number },
to: { lat: number; lng: number },
unit?: 'km' | 'mi',
): number {
const EARTH_RADIUS_KM = 6371
const toRadians = (deg: number): number => (deg * Math.PI) / 180
const dLat = toRadians(to.lat - from.lat)
const dLng = toRadians(to.lng - from.lng)
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(from.lat)) *
Math.cos(toRadians(to.lat)) *
Math.sin(dLng / 2) *
Math.sin(dLng / 2)
const km = EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return unit === 'mi' ? km * 0.621371 : km
}
/** One POST to the hosted service. */
private async request(
operation: 'geocode' | 'reverse',
body: Record<string, unknown>,
): Promise<GeoResult[]> {
if (!this.apiKey) {
throw new MoleculeServiceError(
'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
401,
'hostedServices.error.tokenInvalid',
)
}
const response = await fetch(`${this.servicesUrl}/geocoding/${operation}`, {
method: 'POST',
headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(this.timeoutMs),
})
const text = await response.text()
let data: unknown
try {
data = text ? JSON.parse(text) : {}
} catch (error) {
// A proxy/gateway error page, not the service: report the status only.
throw new MoleculeServiceError(
`molecule.dev returned ${response.status} with a non-JSON body.`,
response.status,
undefined,
error,
)
}
if (!response.ok) {
const err = data as { error?: string; errorKey?: string }
const hint = HINTS[response.status]
throw new MoleculeServiceError(
`molecule.dev geocoding/${operation} failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
response.status,
err.errorKey,
)
}
return data as GeoResult[]
}
}
Functions
createProvider(config)
Create a hosted geocoding provider.
function createProvider(config?: MoleculeGeolocationConfig): GeolocationProvider
config— Options; each falls back to its env var.
Returns: A GeolocationProvider backed by molecule.dev.
Constants
provider
The provider implementation (wire with setProvider).
const provider: GeolocationProvider
DEFAULT_SERVICES_URL
Default hosted services base URL.
const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
GEOCODING_SERVICE_LIMITS
Per-request limits of the hosted service.
const GEOCODING_SERVICE_LIMITS: {
readonly maxAddressChars: 300
readonly maxLat: 90
readonly maxLng: 180
}
geolocationMoleculeSecretDefinitions
Secret definitions required by the molecule.dev hosted geocoding bond.
const geolocationMoleculeSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-geolocation interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-geolocation'
import { provider } from '@molecule/api-geolocation-molecule'
export function setupGeolocationMolecule(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-geolocation>=1.0.2@molecule/api-secrets^1.0.1
Environment Variables
MOLECULE_API_KEY(required) — molecule.dev project API key- Setup: Create one for your project with
mlcl apikey create --project <id> --name <name>(keys start with mk_). - Get it here: https://www.molecule.dev
- Example:
mk_...
- Setup: Create one for your project with
Runtime Dependencies
@molecule/api-geolocation@molecule/api-secrets
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- A known input resolves to plausibly-correct results: a real address
passed to
geocode()returns coordinates in roughly the right place (a famous landmark lands inside its own city, not the middle of the ocean), and a known lat/lng passed toreverseGeocode()names the right city — never an empty array,null,0,0, or a hardcoded placeholder. - The app actually CONSUMES the result downstream, verified on screen:
the map recenters on the geocoded point, a "near me" list is sorted or
filtered by
distance()(closest first), or the address form marks a real address valid and a bogus one invalid — a coordinate that comes back but changes nothing in the UI is a broken integration, not a pass. - If the app relies on the BROWSER geolocation permission, denying it (or letting it time out) falls back gracefully to manual entry — type or autocomplete an address — never a blank map, a spinner that never resolves, or a crash.
- An unresolvable input (gibberish address, empty
geocode()/reverseGeocode()result) surfaces a clear "location not found" message, not a crash, a silent blank screen, or a default location shown as if real. - PRIVACY: a user's precise coordinates are not exposed to other users or written to logs beyond what the feature needs (persist/show only the granularity required — e.g. city, not raw lat/lng), and the geocoding provider key stays SERVER-SIDE (app screens call YOUR API, never the geocoding service directly).