NebulaNebula
Reference

@nebula-rn/host-apis

Nebula official host feature implementation package API reference, providing out-of-the-box host API registration and detailed parameter descriptions for each API.

@nebula-rn/host-apis provides official host API feature implementations. Host apps can directly use these pre-built features and register them with the runtime via NebulaAPI.wrap().

Version: 0.0.1


Quick Start

Register All Default APIs

import { NebulaAPI } from '@nebula-rn/sdk';
import { defaultHostApis } from '@nebula-rn/host-apis';

export default NebulaAPI.wrap({
  serverBaseURL: 'https://api.example.com',
  hostApis: defaultHostApis,
})(App);

Register on Demand

import { scanCodeHostApi, previewImageHostApi } from '@nebula-rn/host-apis';

NebulaAPI.wrap({
  hostApis: [scanCodeHostApi, previewImageHostApi],
})(App);

Exports

ExportTypeDescription
defaultHostApisNebulaHostFeature[]Array containing all default APIs.
scanCodeHostApiNebulaHostFeatureScan code Modal API.
previewImageHostApiNebulaHostFeatureImage preview Modal API.
coreHostApisNebulaHostFeature[]Core functionality API array.
downloadFileHostApiNebulaHostFeatureFile download (Task API).
downloadFileHostfunctionFile download (pure function).
uploadFileHostApiNebulaHostFeatureFile upload (Task API).
uploadFileHostfunctionFile upload (pure function).
saveMediaHostfunctionSave media to system photo album.

defaultHostApis = [scanCodeHostApi, previewImageHostApi, ...coreHostApis]


scanCode

Opens the host-managed scanning UI, supporting QR codes and barcodes.

PlatformSupport
iOS✅
Android✅

API Name: scanCode

Version: 1.0

Payload:

ParameterTypeRequiredDefaultDescription
scanTypestring[]No['qr', 'ean-13', 'code-128']Types of codes to recognize.
onlyFromCamerabooleanNo—Use camera only for scanning.

Return Value:

FieldTypeDescription
resultstring | undefinedScanned content.
scanTypestring | 'unknown'Recognized code type.
rawDataunknownRaw scan data.

Permission Required: Camera permission.

Platform Differences:

iOSAndroid
Permission checkProactively checks in onBeforeOpen; returns PERMISSION_DENIED if not authorizedHandled automatically by system

Error Codes:

Error codeDescription
PERMISSION_DENIEDCamera permission not authorized (iOS only).
USER_CANCELLEDUser closed the scan interface.
UNSUPPORTED_SOURCEDevice does not support scanning.
SCAN_FAILEDScanning failed.

previewImage

Opens a full-screen image preview interface, supporting browsing multiple images and saving.

PlatformSupport
iOS✅
Android✅

API Name: previewImage

Version: 1.0

Payload:

ParameterTypeRequiredDefaultDescription
urlsstring[]Yes—List of image URLs.
currentstringNo—Initially displayed image URL.
showMenubooleanNo—Whether to show save/menu options.
saveMediaTextstringNo—Custom text for the save button.
cancelTextstringNo—Custom text for the cancel button.

Return Value: Same as Payload structure.

Permission Required: None.


Device and App

getAppBaseInfo

Gets basic information about the host application.

PlatformSupport
iOS✅
Android✅

API Name: getAppBaseInfo

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
versionstringApp version number.
languagestringDevice language.
enableDebugbooleanWhether debug mode is enabled.
themestringCurrent theme ('light' or 'dark').

getSystemInfo

Gets device, screen, and safe area information.

PlatformSupport
iOS✅
Android✅

API Name: getSystemInfo

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
brandstringDevice brand.
modelstringDevice model.
pixelRationumberScreen pixel ratio.
screenWidthnumberScreen width in pixels.
screenHeightnumberScreen height in pixels.
windowWidthnumberWindow width.
windowHeightnumberWindow height.
statusBarHeightnumberStatus bar height.
platformstring'ios' or 'android'.
systemstringOS name + version, e.g., "iOS 17.0".
versionstringSystem version number.
fontSizeSettingnumberFont scale factor.
deviceOrientationstringDevice orientation ('portrait' or 'landscape').
safeAreaSafeAreaSafe area.
languagenullReserved field.
SDKVersionnullReserved field.

SafeArea Fields:

FieldTypeDescription
leftnumberLeft safe distance.
rightnumberRight safe distance.
topnumberTop safe distance.
bottomnumberBottom safe distance.
widthnumberSafe area width.
heightnumberSafe area height.

Platform Differences:

AndroidiOS
statusBarHeightStatusBar.currentHeightSafe area top value

getScreenBrightness

Gets the current screen brightness.

PlatformSupport
iOS✅
Android✅

API Name: getScreenBrightness

Payload: {} (no parameters)

Return Value: number (brightness value 0-1).


makePhoneCall

Opens the system dialer with the specified number.

PlatformSupport
iOS✅
Android✅

API Name: makePhoneCall

Payload:

ParameterTypeRequiredDescription
phoneNumberstringYesPhone number.

Return Value: boolean (true if dialer was successfully invoked, false if number is empty or failed).


Clipboard

getClipboardData

Reads text content from the clipboard.

PlatformSupport
iOS✅
Android✅

API Name: getClipboardData

Payload: {} (no parameters)

Return Value: string (clipboard text).


setClipboardData

Writes text to the clipboard.

PlatformSupport
iOS✅
Android✅

API Name: setClipboardData

Payload:

ParameterTypeRequiredDescription
datastringYesText to copy.

Return Value: null


Location

getLocation

Gets the current device location (one-time).

PlatformSupport
iOS✅
Android✅

API Name: getLocation

Payload:

ParameterTypeRequiredDefaultDescription
isHighAccuracybooleanNo—Whether to enable high accuracy.
highAccuracyExpireTimenumberNo10000High accuracy timeout (ms).
altitudebooleanNo—Whether to request altitude data.

Return Value:

FieldTypeDescription
latitudenumberLatitude.
longitudenumberLongitude.
speednumberSpeed (m/s).
accuracynumberAccuracy in meters.
altitudenumberAltitude in meters.
verticalAccuracynumberVertical accuracy.
horizontalAccuracynumberHorizontal accuracy.

Permission Required (Android): ACCESS_FINE_LOCATION, falls back to ACCESS_COARSE_LOCATION.

Error Codes:

Error codeDescription
LOCATION_FAILEDLocation request failed.

locationChange.subscribe

Starts continuously listening for location changes.

PlatformSupport
iOS✅
Android✅

API Name: locationChange.subscribe

Payload:

ParameterTypeRequiredDefaultDescription
enableHighAccuracybooleanNotrueWhether to enable high accuracy.

Return Value:

FieldTypeDescription
subscriptionIdstringSubscription ID for unsubscribing.

Subscription Event Data:

FieldTypeDescription
latitudenumberLatitude.
longitudenumberLongitude.
speednumberSpeed.
accuracynumberAccuracy.
altitudenumberAltitude.
timestampnumberTimestamp.

Timeout: 10000ms.

distanceFilter: 0 (any movement triggers callback).


locationChange.unsubscribe

Stops listening for location changes.

PlatformSupport
iOS✅
Android✅

API Name: locationChange.unsubscribe

Payload:

ParameterTypeRequiredDescription
subscriptionIdstringYesSubscription ID to cancel.

Return Value: null


Media

chooseMedia

Opens the media picker to get images/videos from the album or camera.

PlatformSupport
iOS✅
Android✅

API Name: chooseMedia

Timeout: 120000ms

Payload:

ParameterTypeRequiredDefaultDescription
countnumberNo9Maximum number of items to select.
mediaType('image' | 'video' | 'mix')[]No['image', 'video']Media type filter.
sourceType('album' | 'camera')[]No['album', 'camera']Source filter.
maxDurationnumberNo10Maximum recording duration (seconds).
sizeType('original' | 'compressed')[]No['original', 'compressed']Compression options.
camera'back' | 'front'No'back'Default camera.

Return Value:

FieldTypeDescription
type'image' | 'video' | 'mix'Selected media type.
tempFilesTempFile[]List of files.

TempFile Fields:

FieldTypeDescription
tempFilePathstringTemporary file path.
sizenumberFile size in bytes.
durationnumber | undefinedVideo duration in seconds.
heightnumber | undefinedHeight.
widthnumber | undefinedWidth.
thumbTempFilePathstring | undefinedThumbnail path (for videos).
fileType'image' | 'video'File type.

Compression Quality: compressed = 0.8, original = 1.0.

Error Codes:

Error codeDescription
chooseMedia:fail cancelUser cancelled.
chooseMedia:fail {code}Picker error.

getImageInfo

Gets image dimension information.

PlatformSupport
iOS✅
Android✅

API Name: getImageInfo

Payload:

ParameterTypeRequiredDescription
srcstringYesImage URL or local path.

Return Value:

FieldTypeDescription
widthnumberImage width in pixels.
heightnumberImage height in pixels.
pathstringImage path.
orientationstringOrientation (fixed to 'up').
typestringImage type.
errMsgstring'getImageInfo:ok'.

compressImage

Compresses an image, outputting in JPEG format.

PlatformSupport
iOS✅
Android✅

API Name: compressImage

Payload:

ParameterTypeRequiredDefaultDescription
srcstringYes—Source image path.
qualitynumberNo80Compression quality (0-100).
compressedWidthnumberNo—Target width in pixels.
compressedHeightnumberNo—Target height in pixels.

Return Value: string (compressed image URI).


saveMedia

Saves an image or video to the system photo album.

PlatformSupport
iOS✅
Android✅

API Name: saveMedia

Payload:

ParameterTypeRequiredDescription
urlstringYesMedia file path or URL.
type'photo' | 'video'YesMedia type.
albumstringNoTarget album name.

Return Value: string (URI/path in system photo album).

Implementation: Uses CameraRoll to save to system media library.


Storage

Based on MMKV (Memory Mapped KV Store), ID: nebula.host.api.storage.

storage.setItem

Writes a key-value pair.

PlatformSupport
iOS✅
Android✅

API Name: storage.setItem

Payload:

ParameterTypeRequiredDescription
keystringYesKey name.
datastringYesSerialized value (JSON string).

Return Value: null


storage.getItem

Reads a key-value pair.

PlatformSupport
iOS✅
Android✅

API Name: storage.getItem

Payload:

ParameterTypeRequiredDescription
keystringYesKey name.

Return Value:

FieldTypeDescription
valuestring | nullStored value, null if not found.

storage.removeItem

Deletes a key-value pair.

PlatformSupport
iOS✅
Android✅

API Name: storage.removeItem

Payload:

ParameterTypeRequiredDescription
keystringYesKey name.

Return Value: null


storage.clearItems

Clears all stored data and releases memory.

PlatformSupport
iOS✅
Android✅

API Name: storage.clearItems

Payload: {} (no parameters)

Return Value: null


storage.getKeys

Gets all stored key names.

PlatformSupport
iOS✅
Android✅

API Name: storage.getKeys

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
keysstring[]Array of all key names.

storage.getCurrentSize

Gets the current storage size.

PlatformSupport
iOS✅
Android✅

API Name: storage.getCurrentSize

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
sizenumberUsed size in KB (rounded to 2 decimal places).

File System

fileSystem.access

Checks whether a file or directory exists.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.access

Payload:

ParameterTypeRequiredDescription
pathstringYesFile or directory path.

Return Value: null

Error Codes:

Error codeDescription
FILE_NOT_FOUNDPath does not exist.

fileSystem.readFile

Reads file content.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.readFile

Payload:

ParameterTypeRequiredDefaultDescription
filePathstringYes—File path.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.

Return Value:

FieldTypeDescription
datastringFile content.

fileSystem.writeFile

Writes to a file.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.writeFile

Payload:

ParameterTypeRequiredDefaultDescription
filePathstringYes—Target file path.
datastringYes—Content to write.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.

Return Value: null


fileSystem.appendFile

Appends content to the end of a file.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.appendFile

Payload:

ParameterTypeRequiredDefaultDescription
filePathstringYes—Target file path.
datastringYes—Content to append.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.

Return Value: null


fileSystem.copyFile

Copies a file.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.copyFile

Payload:

ParameterTypeRequiredDescription
srcPathstringYesSource file path.
destPathstringYesDestination path.

Return Value: null


fileSystem.rename

Renames or moves a file/directory.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.rename

Payload:

ParameterTypeRequiredDescription
oldPathstringYesOriginal path.
newPathstringYesNew path.

Return Value: null


Deletes a file.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.unlink

Payload:

ParameterTypeRequiredDescription
filePathstringYesPath of the file to delete.

Return Value: null


fileSystem.mkdir

Creates a directory (recursively).

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.mkdir

Payload:

ParameterTypeRequiredDescription
dirPathstringYesDirectory path.

Return Value: null


fileSystem.rmdir

Deletes a directory (recursively).

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.rmdir

Payload:

ParameterTypeRequiredDescription
dirPathstringYesDirectory path.

Return Value: null


fileSystem.readdir

Lists directory contents.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.readdir

Payload:

ParameterTypeRequiredDescription
dirPathstringYesDirectory path.

Return Value:

FieldTypeDescription
filesstring[]Array of sub-file/directory names.

fileSystem.saveFile

Saves a temporary file to the miniapp sandbox.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.saveFile

Payload:

ParameterTypeRequiredDescription
tempFilePathstringYesTemporary file path.
filePathstringNoDestination path. Auto-generated if not provided.

Return Value:

FieldTypeDescription
savedFilePathstringPath after saving.

fileSystem.getFileInfo

Gets file information and digest.

PlatformSupport
iOS✅
Android✅

API Name: fileSystem.getFileInfo

Payload:

ParameterTypeRequiredDefaultDescription
filePathstringYes—File path.
digestAlgorithm'md5' | 'sha1' | 'sha256'No'md5'Digest algorithm.

Return Value:

FieldTypeDescription
sizenumberFile size in bytes.
digeststringFile digest.

removeFile

Deletes a sandbox file.

PlatformSupport
iOS✅
Android✅

API Name: removeFile

Payload:

ParameterTypeRequiredDescription
filePathstringYesPath of the file to delete.

Return Value: null

Error Codes:

Error codeDescription
FILE_NOT_FOUNDFile does not exist.

Path Resolution Rules

  • Paths starting with file:// are normalized.
  • Miniapp paths are resolved relative to /Documents/MiniApps/{appId}/.
  • Paths starting with /Documents/ are resolved to ${RNFS.DocumentDirectoryPath}.

Network

getNetworkType

Gets the current network type.

PlatformSupport
iOS✅
Android✅

API Name: getNetworkType

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
networkTypestringNetwork type, e.g., 'wifi', 'cellular', 'none'.

networkStatusChange.subscribe

Starts listening for network status changes.

PlatformSupport
iOS✅
Android✅

API Name: networkStatusChange.subscribe

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
subscriptionIdstringSubscription ID.

Subscription Event Data:

FieldTypeDescription
isConnectedbooleanWhether connected to the internet.
networkTypestringCurrent network type.

Implementation: Based on NetInfo real-time push.


networkStatusChange.unsubscribe

Stops listening for network status changes.

PlatformSupport
iOS✅
Android✅

API Name: networkStatusChange.unsubscribe

Payload:

ParameterTypeRequiredDescription
subscriptionIdstringYesSubscription ID to cancel.

Return Value: null


Sensors

All sensor subscription APIs support custom sampling intervals.

accelerometerChange.subscribe / unsubscribe

Accelerometer data listening.

PlatformSupport
iOS✅
Android✅

API Name: accelerometerChange.subscribe / accelerometerChange.unsubscribe

Subscribe Payload:

ParameterTypeRequiredDefaultDescription
intervalnumberNo100Sampling interval (ms).

Subscription Event Data:

FieldTypeDescription
xnumberX-axis acceleration.
ynumberY-axis acceleration.
znumberZ-axis acceleration.
timestampnumber | undefinedTimestamp.

Unsubscribe Payload:

ParameterTypeRequiredDescription
subscriptionIdstringYesSubscription ID.

gyroscopeChange.subscribe / unsubscribe

Gyroscope data listening.

PlatformSupport
iOS✅
Android✅

API Name: gyroscopeChange.subscribe / gyroscopeChange.unsubscribe

Subscribe Payload / Event Data: Same as accelerometer.


magnetometerChange.subscribe / unsubscribe

Magnetometer data listening.

PlatformSupport
iOS✅
Android✅

API Name: magnetometerChange.subscribe / magnetometerChange.unsubscribe

Subscribe Payload / Event Data: Same as accelerometer.


barometerChange.subscribe / unsubscribe

Barometer data listening.

PlatformSupport
iOS✅
Android✅

API Name: barometerChange.subscribe / barometerChange.unsubscribe

Subscribe Payload: {} (interval configuration not supported)

Subscription Event Data:

FieldTypeDescription
pressurenumberPressure value (Pa or hPa).

Screenshot Event

userCaptureScreen.subscribe / unsubscribe

Listens for user screenshot operations.

PlatformSupport
iOS✅
Android✅

API Name: userCaptureScreen.subscribe / userCaptureScreen.unsubscribe

Subscribe Payload: {} (no parameters)

Return Value:

FieldTypeDescription
subscriptionIdstringSubscription ID.

Subscription Event Data: null (only notifies that a screenshot occurred, no additional data).

Implementation: Based on ScreenshotAware listener.


Miniapp Update

getMiniAppUpdateInfo

Gets installation/available version information for the miniapp.

PlatformSupport
iOS✅
Android✅

API Name: getMiniAppUpdateInfo

Timeout: 15000ms

Payload: {} (no parameters)

Return Value:

FieldTypeDescription
appIdstringMiniapp ID.
currentVersionstring | nullCurrently installed version.
latestVersionstring | nullLatest remote version.
hasUpdatebooleanWhether an update is available.
updateStrategy'auto' | 'manual'Update strategy.
modestring | nullRuntime mode.
sourceUrlstring | nullBundle source URL.

applyMiniAppUpdate

Downloads and installs the latest available bundle.

PlatformSupport
iOS✅
Android✅

API Name: applyMiniAppUpdate

Timeout: 120000ms

Payload: {} (no parameters)

Return Value: Same as getMiniAppUpdateInfo.


File Transfer (Task API)

Task APIs support progress callbacks and abort operations. Calling start returns a taskId, and abort cancels the task.

downloadFile.start

Starts a file download task.

PlatformSupport
iOS✅
Android✅

API Name: downloadFile.start

Payload:

ParameterTypeRequiredDefaultDescription
urlstringYes—Download URL.
headerRecord<string, string>No—Custom HTTP request headers.
timeoutnumberNo60000Timeout (ms).
filePathstringNoAuto-generatedSave path. Saves to temporary directory if not provided.

Return Value:

FieldTypeDescription
taskIdstringTask ID.

Progress Event (channel: task.progress):

FieldTypeDescription
progressnumberProgress percentage (0-100).
totalBytesWrittennumberBytes downloaded.
totalBytesExpectedToWritenumberTotal bytes.

Header Event (channel: task.headers):

FieldTypeDescription
headerRecord<string, string>Response headers.

Completion Result:

// Success
{ ok: true, data: { tempFilePath: string, statusCode: number } }

// Failure
{ ok: false, error: { code: 'DOWNLOAD_FAILED', message: string } }

Auto Path Generation: ${TemporaryDirectoryPath}/${Date.now()}_download

Implementation: Based on RNFS.downloadFile.


downloadFile.abort

Aborts a download task.

PlatformSupport
iOS✅
Android✅

API Name: downloadFile.abort

Payload:

ParameterTypeRequiredDescription
taskIdstringYesTask ID to abort.

Return Value: { ok: true, data: null }


uploadFile.start

Starts a file upload task.

PlatformSupport
iOS✅
Android✅

API Name: uploadFile.start

Payload:

ParameterTypeRequiredDefaultDescription
urlstringYes—Upload target URL.
filePathstringYes—Path of the file to upload.
namestringYes—Form field name.
headerRecord<string, string>No—Custom HTTP request headers.
formDataRecord<string, string>No—Additional form fields.
timeoutnumberNo60000Timeout (ms).

Return Value:

FieldTypeDescription
taskIdstringTask ID.

Progress Event (channel: task.progress):

FieldTypeDescription
progressnumberProgress percentage (0-100).
totalBytesSentnumberBytes uploaded.
totalBytesExpectedToSendnumberTotal bytes.

Completion Result:

// Success
{ ok: true, data: { data: string, statusCode: number } }

// Failure
{ ok: false, error: { code: 'UPLOAD_FAILED', message: string } }

HTTP Method: POST

Implementation: Based on RNFS.uploadFiles, filename extracted automatically from filePath.


uploadFile.abort

Aborts an upload task.

PlatformSupport
iOS✅
Android✅

API Name: uploadFile.abort

Payload:

ParameterTypeRequiredDescription
taskIdstringYesTask ID to abort.

Return Value: { ok: true, data: null }


Pure Function Exports

The following functions can be called directly and do not follow the Task API flow (no progress callbacks).

downloadFileHost(options)

Simple file download.

async function downloadFileHost(options: {
  url: string;
  header?: Record<string, string>;
  timeout?: number;
  filePath?: string;
}): Promise<{ tempFilePath: string; statusCode: number }>;

uploadFileHost(options)

Simple file upload.

async function uploadFileHost(options: {
  url: string;
  filePath: string;
  name: string;
  header?: Record<string, string>;
  formData?: Record<string, string>;
  timeout?: number;
}): Promise<{ data: string; statusCode: number }>;

saveMediaHost(payload)

Directly saves media to the system photo album.

async function saveMediaHost(payload: {
  url: string;
  type: 'photo' | 'video';
  album?: string;
}): Promise<string>;

Common Error Format

All failed API calls return a unified format:

{
  ok: false,
  error: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  }
}

Default Timeouts

OperationTimeout
General APIs15000ms
Media operations (chooseMedia)120000ms
Miniapp update (applyMiniAppUpdate)120000ms
File transfer (download/upload)60000ms