onnxRuntime.ts

Lazy-loads and caches the ONNX React Native runtime with descriptive availability errors

Purpose

This module provides safe, lazy access to the onnxruntime-react-native native module. Because the ONNX runtime requires a native build and is unavailable in Expo Go or stale builds, this module isolates the require() call, caches the result, and surfaces actionable error messages when the runtime cannot be loaded.

Its responsibilities include:

  • Performing a lazy require("onnxruntime-react-native") on first access
  • Caching the loaded module for all subsequent calls (avoiding repeated require overhead)
  • Caching any load failure so that repeated calls immediately re-throw without retrying
  • Wrapping all unavailability conditions in a typed OnnxRuntimeUnavailableError
  • Exposing a non-throwing availability probe for conditional feature gating

Invariants

Load-Once Semantics

The require call is executed at most once per process lifetime.

  • On success: the module reference is cached; all subsequent calls return it directly.
  • On failure: the error is cached as an OnnxRuntimeUnavailableError; all subsequent calls re-throw it without retrying.

Error Type Preservation

All errors surfaced by getOnnxRuntime() are guaranteed to be instances of OnnxRuntimeUnavailableError.

Foreign errors thrown during load are wrapped before propagation.


Non-Throwing Probe

isOnnxRuntimeAvailable() never throws.

It returns false for any load failure, including cached failures, making it safe to call in render paths or feature flags.


Variants

Cached Unavailability

If the runtime has already failed to load, getOnnxRuntime() re-throws the cached OnnxRuntimeUnavailableError immediately without calling require() again. This prevents repeated native module resolution attempts that would fail identically.


Exports

OnnxRuntimeUnavailableError

class OnnxRuntimeUnavailableError extends Error {
	name: "OnnxRuntimeUnavailableError";
}

Thrown when the ONNX native runtime cannot be loaded. Includes a cause field with the underlying error when available.

Typical causes:

  • Running inside Expo Go (no native module present)
  • Native build is stale (pods/native deps not reinstalled after expo prebuild)

isOnnxRuntimeAvailable()

function isOnnxRuntimeAvailable(): boolean

Returns true if the ONNX runtime can be loaded in the current build; false otherwise.

Never throws.


getOnnxRuntime()

function getOnnxRuntime(): OnnxRuntimeModule

Returns the loaded onnxruntime-react-native module.

Throws

Throws OnnxRuntimeUnavailableError when:

  • the native module is not present in the current build
  • the require() call fails for any reason

The error message includes a remediation hint (expo prebuild + reinstall native dependencies).