hylid-bridge-ts
v1.0.0
Published
Type-safe TypeScript library for hylid-bridge Mini Program JSAPI
Downloads
13
Maintainers
Readme
hylid-bridge-ts
Type-safe TypeScript library for the hylid-bridge Mini Program JSAPI (hylid-bridge 2.10.0).
Wraps every my.* API and AlipayJSBridge.call() method with full TypeScript types, autocomplete, and async/await support — no more guessing parameter names or callback shapes.
Table of Contents
- Installation
- Quick Start
- Architecture
- Core Concepts
- API Reference
- Auth
- Payment
- Device Info
- Mini Program Navigation
- UI — Navigation Bar
- UI — Pickers
- UI — Dialogs
- UI — Action Sheet
- UI — Loading
- UI — Toast
- UI — Contacts
- Media — Images
- Media — Video
- Storage
- File
- Location
- Network — HTTP Request
- Network — Download
- Device — System Info
- Device — Network Type
- Device — Clipboard
- Device — Battery
- Device — Screen Brightness
- Device — Add Contact
- Device — Phone Call
- Device — Scanner
- Device — Vibrate
- Bridge — Device Info (H5+)
- Bridge — Ready Helper
- Types Reference
- Error Handling
- License
Installation
npm
npm install hylid-bridge-tsyarn
yarn add hylid-bridge-tspnpm
pnpm add hylid-bridge-tsPrerequisites
Your HTML page must load the hylid-bridge runtime before your app code:
<script src="https://cdn.marmot-cloud.com/npm/hylid-bridge/2.10.0/index.js"></script>This library provides TypeScript types and promisified wrappers over the global my and AlipayJSBridge objects that hylid-bridge injects at runtime.
Quick Start
import {
getAuthCode,
getDeviceInfo,
showToast,
request,
getStorageTyped,
} from "hylid-bridge-ts";
// Auth — get a user authorization code
const { authCode } = await getAuthCode(["auth_user"]);
// Device info
const { currentRole, isProdEnv } = await getDeviceInfo();
// Show a toast
await showToast("Hello!", "success", 2000);
// Typed HTTP request
const { promise } = request<{ items: string[] }>({
url: "https://api.example.com/items",
method: "GET",
});
const { data, status } = await promise;
// data.items is string[]
// Typed storage
interface UserProfile {
name: string;
age: number;
}
const profile = await getStorageTyped<UserProfile>("user_profile");
// profile.name is stringArchitecture
src/
├── types.ts — All interfaces, enums, and the MyApiMap type map
├── my.ts — Promisified wrappers for every my.* method
├── bridge.ts — Promisified wrapper for AlipayJSBridge.call()
└── index.ts — Barrel re-export| File | Purpose |
|------|---------|
| types.ts | Every interface, enum, and union type. Also defines MyApiMap — a single map that links each API method name to its params/result types. |
| my.ts | The generic callMy() function plus 40+ convenience wrappers. Each wraps callbacks in a Promise. |
| bridge.ts | The generic callBridge() function, bridgeReady(), and bridge convenience wrappers. |
| index.ts | Re-exports everything from one entry point. |
Core Concepts
callMy() — Generic API Caller
The foundation of the library. Call any my.* method by name with full type inference:
import { callMy } from "hylid-bridge-ts";
// TypeScript knows the return type automatically
const result = await callMy("getAuthCode", { scopes: ["auth_user"] });
// ^ GetAuthCodeResult { authCode: string; authErrorScopes: ...; authSuccessScopes: ... }
const { date } = await callMy("datePicker", { format: "yyyy-MM-dd" });
// ^ string
// Type error — 'invalid' is not a valid method name
await callMy("invalid", {});Signature:
function callMy<K extends MyApiMethod>(
method: K,
params: StripCallbacks<MyApiMap[K]["params"]>,
): Promise<MyApiMap[K]["result"]>;- You never pass
success,fail, orcomplete— they are handled internally. - The Promise rejects on
failand resolves onsuccess.
callBridge() — Bridge Caller
Same pattern for AlipayJSBridge.call():
import { callBridge } from "hylid-bridge-ts";
const info = await callBridge("getDeviceInfo", {});Signature:
function callBridge<K extends BridgeApiMethod>(
method: K,
params: BridgeApiMap[K]["params"],
): Promise<BridgeApiMap[K]["result"]>;Convenience Wrappers
Every API also has a dedicated function with a more ergonomic signature. These are thin wrappers around callMy():
// Instead of:
await callMy("showToast", { content: "Done", type: "success", duration: 2000 });
// You can write:
await showToast("Done", "success", 2000);API Reference
Auth
getAuthCode(scopes)
Get an authorization code for token exchange.
import { getAuthCode } from "hylid-bridge-ts";
const { authCode, authErrorScopes, authSuccessScopes } = await getAuthCode([
"auth_user",
]);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| scopes | string[] | Yes | Authorization scopes (e.g. "auth_base", "auth_user", "auth_zhima") |
Returns: GetAuthCodeResult
| Field | Type | Description |
|-------|------|-------------|
| authCode | string | Authorization code for server-side token exchange |
| authErrorScopes | Record<string, number> | Scopes that failed with error codes |
| authSuccessScopes | string[] | Scopes that were successfully authorized |
Error codes: 3, 1000, 1001, 1002, 1003, 2001
Payment
tradePay(paymentUrl)
Initiate a wallet payment.
import { tradePay } from "hylid-bridge-ts";
const { resultCode } = await tradePay("https://payment.example.com/pay");
if (resultCode === "9000") {
console.log("Payment successful");
}| Param | Type | Required | Description |
|-------|------|----------|-------------|
| paymentUrl | string | Yes | Payment URL from your server |
Returns: TradePayResult
| Field | Type | Description |
|-------|------|-------------|
| resultCode | TradePayResultCode | Payment result |
Result codes:
| Code | Meaning |
|------|---------|
| "9000" | Success |
| "8000" | Processing |
| "4000" | Failed |
| "6001" | User cancelled |
| "6002" | Network error |
| "6004" | Unknown |
Device Info
getDeviceInfo()
Get device information and the current user role.
import { getDeviceInfo } from "hylid-bridge-ts";
const { currentRole, isProdEnv, language, systemInfo, loginTime } =
await getDeviceInfo();
if (currentRole === "business") {
// Business user flow
}Returns: GetDeviceInfoResult
| Field | Type | Description |
|-------|------|-------------|
| language | string | Device language |
| isProdEnv | boolean | Whether this is the production environment |
| currentRole | "customer" \| "business" | Current user role |
| systemInfo | SystemInfoObject | OS, screen, and app metadata |
| hardwareInfo | HardwareInfoObject | Hardware details |
| loginTime | string | Login timestamp |
Mini Program Navigation
navigateToMiniProgram(appId, path?, extraData?)
Navigate to another Mini Program.
import { navigateToMiniProgram } from "hylid-bridge-ts";
await navigateToMiniProgram("2021001234567890", "/pages/index/index", {
orderId: "12345",
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| appId | string | Yes | Target Mini Program App ID |
| path | string | No | Target page path |
| extraData | Record<string, unknown> | No | Data to pass to target |
navigateBackMiniProgram(extraData?)
Return to the previous Mini Program.
import { navigateBackMiniProgram } from "hylid-bridge-ts";
await navigateBackMiniProgram({ status: "completed" });| Param | Type | Required | Description |
|-------|------|----------|-------------|
| extraData | Record<string, unknown> | No | Data to pass back |
UI — Navigation Bar
setNavigationBar(params)
Customize the navigation bar appearance.
import { setNavigationBar } from "hylid-bridge-ts";
await setNavigationBar({
title: "My Page",
backgroundColor: "#ffffff",
borderBottomColor: "#eeeeee",
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| title | string | No | Title text |
| image | string | No | Image URL (replaces title) |
| backgroundColor | string | No | Background color (hex) |
| borderBottomColor | string | No | Bottom border color |
| reset | boolean | No | Reset to default values |
UI — Pickers
multiLevelSelect(list, title?)
Show a cascading multi-level picker.
import { multiLevelSelect } from "hylid-bridge-ts";
const { success, result } = await multiLevelSelect(
[
{
name: "Electronics",
subList: [
{ name: "Phones" },
{ name: "Laptops" },
],
},
{
name: "Clothing",
subList: [
{ name: "Shirts" },
{ name: "Pants" },
],
},
],
"Select Category",
);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| list | MultiLevelSelectItem[] | Yes | Hierarchical items ({ name, subList? }) |
| title | string | No | Picker title |
Returns: MultiLevelSelectResult
| Field | Type | Description |
|-------|------|-------------|
| success | boolean | Whether the user confirmed |
| result | MultiLevelSelectItem[] | Selected items at each level |
datePicker(params)
Show a date/time picker.
import { datePicker } from "hylid-bridge-ts";
const { date } = await datePicker({
format: "yyyy-MM-dd",
currentDate: "2024-01-01",
startDate: "2020-01-01",
endDate: "2030-12-31",
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| format | DatePickerFormat | No | "yyyy-MM-dd" | "HH:mm" | "yyyy-MM-dd HH:mm" | "yyyy-MM" | "yyyy" |
| currentDate | string | No | Initially selected date |
| startDate | string | No | Earliest selectable date |
| endDate | string | No | Latest selectable date |
Returns: DatePickerResult — { date: string }
Error codes: 11 (user cancelled)
UI — Dialogs
alert(params)
Show an alert dialog.
import { alert } from "hylid-bridge-ts";
await alert({
title: "Notice",
content: "Operation completed successfully",
buttonText: "Got it",
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| title | string | No | Dialog title |
| content | string | No | Dialog message |
| buttonText | string | No | Button text (default: "OK") |
confirm(params)
Show a confirmation dialog.
import { confirm } from "hylid-bridge-ts";
const { confirm: confirmed } = await confirm({
title: "Delete",
content: "Are you sure?",
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
});
if (confirmed) {
// proceed
}| Param | Type | Required | Description |
|-------|------|----------|-------------|
| title | string | No | Dialog title |
| content | string | No | Dialog message |
| confirmButtonText | string | No | Confirm button text |
| cancelButtonText | string | No | Cancel button text |
Returns: ConfirmResult — { confirm: boolean }
prompt(params)
Show an input dialog.
import { prompt } from "hylid-bridge-ts";
const { ok, inputValue } = await prompt({
message: "Enter your name:",
placeholder: "John Doe",
align: "left",
});
if (ok) {
console.log("User entered:", inputValue);
}| Param | Type | Required | Description |
|-------|------|----------|-------------|
| message | string | Yes | Dialog message |
| title | string | No | Dialog title |
| placeholder | string | No | Input placeholder |
| align | "left" \| "center" \| "right" | No | Text alignment |
| okButtonText | string | No | OK button text |
| cancelButtonText | string | No | Cancel button text |
Returns: PromptResult — { ok: boolean; inputValue: string }
UI — Action Sheet
showActionSheet(params)
Show a bottom action sheet menu.
import { showActionSheet } from "hylid-bridge-ts";
const { index } = await showActionSheet({
title: "Choose action",
items: ["Edit", "Share", "Delete"],
destructiveButtonIndex: 2,
badges: [{ index: 1, type: "num", text: "3" }],
});
if (index === -1) {
console.log("Cancelled");
} else {
console.log("Selected:", index);
}| Param | Type | Required | Description |
|-------|------|----------|-------------|
| title | string | No | Sheet title |
| items | string[] | Yes | Menu item labels |
| cancelButtonText | string | No | Cancel button text |
| destructiveButtonIndex | number | No | Index of the destructive (red) item |
| badges | ActionSheetBadge[] | No | Badge indicators on items |
ActionSheetBadge:
| Field | Type | Description |
|-------|------|-------------|
| index | number | Item index to badge |
| type | "none" \| "point" \| "num" \| "text" \| "more" | Badge style |
| text | string | Badge text (for "num" or "text" types) |
Returns: ShowActionSheetResult — { index: number } (-1 if cancelled)
UI — Loading
showLoading(content?, delay?)
Show a loading spinner overlay.
import { showLoading, hideLoading } from "hylid-bridge-ts";
await showLoading("Loading...", 500);
// ... do work ...
await hideLoading();| Param | Type | Required | Description |
|-------|------|----------|-------------|
| content | string | No | Loading text |
| delay | number | No | Delay in ms before showing |
hideLoading(page?)
Hide the loading spinner.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| page | object | No | Page context |
UI — Toast
showToast(content?, type?, duration?)
Show a brief toast notification.
import { showToast } from "hylid-bridge-ts";
await showToast("Saved!", "success");
await showToast("Something went wrong", "fail", 3000);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| content | string | No | Toast message |
| type | "success" \| "fail" \| "exception" \| "none" | No | Toast icon type |
| duration | number | No | Duration in ms (default: 2000) |
hideToast()
Manually hide the current toast.
import { hideToast } from "hylid-bridge-ts";
await hideToast();UI — Contacts
choosePhoneContact()
Open the device contact picker.
import { choosePhoneContact } from "hylid-bridge-ts";
const { name, mobile } = await choosePhoneContact();Returns: ChoosePhoneContactResult
| Field | Type | Description |
|-------|------|-------------|
| name | string | Contact name |
| mobile | string | Phone number |
Error codes: 10 (no permission), 11 (user cancelled)
Media — Images
chooseImage(params?)
Pick images from camera or album.
import { chooseImage } from "hylid-bridge-ts";
const { apFilePaths } = await chooseImage({
sourceType: ["camera", "album"],
sizeType: ["compressed"],
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| sourceType | ("camera" \| "album")[] | No | Source (default: ["camera", "album"]) |
| sizeType | ("original" \| "compressed")[] | No | Image size type |
Returns: ChooseImageResult — { apFilePaths: string[] }
Error codes: 11 (user cancelled)
previewImage(urls, current?)
Show full-screen image previewer.
import { previewImage } from "hylid-bridge-ts";
await previewImage(
["https://example.com/1.jpg", "https://example.com/2.jpg"],
0, // start at first image
);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| urls | string[] | Yes | Image URLs (remote only, no local paths) |
| current | number | No | Starting index (default: 0) |
saveImage(url, showActionSheet?)
Save an image to the device gallery.
import { saveImage } from "hylid-bridge-ts";
await saveImage("https://example.com/photo.jpg");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| url | string | Yes | Image URL |
| showActionSheet | boolean | No | Show save options sheet |
Error codes: 2 (invalid param), 15 (album permission, iOS), 16 (insufficient storage, iOS), 17 (other)
getImageInfo(src)
Get image dimensions and metadata.
import { getImageInfo } from "hylid-bridge-ts";
const { width, height, orientation, type } = await getImageInfo(
"https://example.com/photo.jpg",
);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| src | string | Yes | Image path or URL |
Returns: GetImageInfoResult
| Field | Type | Description |
|-------|------|-------------|
| width | number | Width in pixels |
| height | number | Height in pixels |
| path | string | Local file path |
| orientation | ImageOrientation | "up" | "down" | "left" | "right" | "up-mirrored" | etc. |
| type | string | Image format (e.g. "jpeg", "png") |
compressImage(apFilePaths, compressLevel?)
Compress one or more images.
import { compressImage } from "hylid-bridge-ts";
const { apFilePaths: compressed } = await compressImage(
["/local/path/image.jpg"],
2, // high compression
);| Param | Type | Required | Description |
|-------|------|----------|-------------|
| apFilePaths | string[] | Yes | Local file paths |
| compressLevel | 0 \| 1 \| 2 \| 4 | No | 0=low, 1=medium, 2=high, 4=auto (default) |
Returns: CompressImageResult — { apFilePaths: string[] }
Media — Video
chooseVideo(params?)
Pick or record a video.
import { chooseVideo } from "hylid-bridge-ts";
const { tempFilePath, duration, size, width, height } = await chooseVideo({
sourceType: ["camera"],
maxDuration: 30,
camera: "back",
compressed: true,
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| sourceType | ("album" \| "camera")[] | No | Source (default: ["album", "camera"]) |
| compressed | boolean | No | Compress video (default: true) |
| maxDuration | number | No | Max duration in seconds (default: 60) |
| camera | "back" \| "front" | No | Camera direction (default: "back") |
Returns: ChooseVideoResult
| Field | Type | Description |
|-------|------|-------------|
| tempFilePath | string | Temporary file path |
| duration | number | Duration in seconds |
| size | number | File size in bytes |
| width | number | Video width |
| height | number | Video height |
Storage
Storage limit: 10 MB per user per Mini Program. Single value max: 200 * 1024 characters.
getStorage(key)
Read a value from local storage.
import { getStorage } from "hylid-bridge-ts";
const { data } = await getStorage("token");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| key | string | Yes | Storage key |
Returns: GetStorageResult — { data: unknown }
getStorageTyped<T>(key)
Type-safe version that casts the result.
import { getStorageTyped } from "hylid-bridge-ts";
interface Settings {
theme: "light" | "dark";
notifications: boolean;
}
const settings = await getStorageTyped<Settings>("app_settings");
// settings.theme is "light" | "dark"| Param | Type | Required | Description |
|-------|------|----------|-------------|
| key | string | Yes | Storage key |
Returns: Promise<T>
setStorage(key, data)
Write a value to local storage.
import { setStorage } from "hylid-bridge-ts";
await setStorage("user", { name: "Ahmed", role: "admin" });| Param | Type | Required | Description |
|-------|------|----------|-------------|
| key | string | Yes | Storage key |
| data | unknown | Yes | Value to store (object or string) |
removeStorage(key)
Remove a value from storage.
import { removeStorage } from "hylid-bridge-ts";
await removeStorage("token");clearStorage()
Clear all stored data for this Mini Program.
import { clearStorage } from "hylid-bridge-ts";
await clearStorage();File
File storage limit: 10 MB total.
saveFile(apFilePath)
Save a temporary file to persistent local storage.
import { saveFile } from "hylid-bridge-ts";
const { apFilePath: savedPath } = await saveFile("/tmp/download.pdf");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| apFilePath | string | Yes | Temporary file path |
Returns: SaveFileResult — { apFilePath: string } (new persistent path)
getFileInfo(apFilePath, digestAlgorithm?)
Get file size and hash digest.
import { getFileInfo } from "hylid-bridge-ts";
const { size, digest } = await getFileInfo("/local/file.pdf", "sha1");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| apFilePath | string | Yes | File path |
| digestAlgorithm | "md5" \| "sha1" | No | Hash algorithm (default: "md5") |
Returns: GetFileInfoResult — { size: number; digest: string }
getSavedFileInfo(apFilePath)
Get metadata for a previously saved file.
import { getSavedFileInfo } from "hylid-bridge-ts";
const { size, createTime } = await getSavedFileInfo("/local/saved.pdf");Returns: GetSavedFileInfoResult — { size: number; createTime: number }
getSavedFileList()
List all files saved by this Mini Program.
import { getSavedFileList } from "hylid-bridge-ts";
const { fileList } = await getSavedFileList();
for (const file of fileList) {
console.log(file.apFilePath, file.size, file.createTime);
}Returns: GetSavedFileListResult — { fileList: SavedFileItem[] }
Each SavedFileItem: { size: number; createTime: number; apFilePath: string }
removeSavedFile(apFilePath)
Delete a saved file.
import { removeSavedFile } from "hylid-bridge-ts";
await removeSavedFile("/local/old-file.pdf");openDocument(filePath, fileType?)
Preview a document (PDF).
import { downloadFile, openDocument } from "hylid-bridge-ts";
const { apFilePath } = await downloadFile("https://example.com/doc.pdf");
await openDocument(apFilePath, "pdf");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| filePath | string | Yes | Local file path (from downloadFile) |
| fileType | "pdf" | No | File type (default: "pdf") |
Error codes: 4011, 4012, 4013
Location
getLocation(params?)
Get the user's GPS coordinates.
import { getLocation } from "hylid-bridge-ts";
const { longitude, latitude, accuracy } = await getLocation({
cacheTimeout: 30,
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| cacheTimeout | number | No | Cache timeout in seconds (default: 30) |
| type | number | No | Location type (0 = default) |
Returns: GetLocationResult
| Field | Type | Description |
|-------|------|-------------|
| longitude | string | Longitude |
| latitude | string | Latitude |
| accuracy | string | Accuracy in meters |
Error codes: 11 (user denied), 12 (network failure), 13 (timeout), 14 (service unavailable)
Network — HTTP Request
request<T>(params)
Make a type-safe HTTP request. Returns both a Promise and a RequestTask with abort().
import { request } from "hylid-bridge-ts";
interface ApiResponse {
users: { id: number; name: string }[];
total: number;
}
const { promise, task } = request<ApiResponse>({
url: "https://api.example.com/users",
method: "GET",
headers: { Authorization: "Bearer token123" },
timeout: 10000,
dataType: "json",
});
// Abort if needed
// task.abort();
const { data, status, headers } = await promise;
// data.users is { id: number; name: string }[]
// data.total is number| Param | Type | Required | Description |
|-------|------|----------|-------------|
| url | string | Yes | Request URL |
| method | "GET" \| "POST" | No | HTTP method (default: "GET") |
| headers | Record<string, string> | No | Request headers (default: { "content-type": "application/json" }) |
| data | Record<string, unknown> | No | Request body (POST) or query params (GET) |
| timeout | number | No | Timeout in ms (default: 30000) |
| dataType | "json" \| "text" \| "base64" | No | Response data type |
Returns: { promise: Promise<RequestResult<T>>; task: RequestTask }
RequestResult<T>:
| Field | Type | Description |
|-------|------|-------------|
| data | T | Response body (typed by generic) |
| status | number | HTTP status code |
| headers | Record<string, string> | Response headers |
RequestTask:
| Method | Description |
|--------|-------------|
| abort() | Cancel the request |
Error codes: 2, 4, 12, 13, 14, 19, 20
Note: Requires domain whitelist configuration in your Mini Program settings.
Network — Download
downloadFile(url, header?)
Download a file to a temporary local path.
import { downloadFile } from "hylid-bridge-ts";
const { apFilePath } = await downloadFile("https://example.com/file.pdf", {
Authorization: "Bearer token",
});| Param | Type | Required | Description |
|-------|------|----------|-------------|
| url | string | Yes | File URL |
| header | Record<string, string> | No | Request headers |
Returns: DownloadFileResult — { apFilePath: string }
Error codes: 12, 13
Device — System Info
getSystemInfo()
Get comprehensive system information.
import { getSystemInfo } from "hylid-bridge-ts";
const info = await getSystemInfo();
console.log(info.platform); // "iOS" or "Android"
console.log(info.windowWidth, info.windowHeight);
console.log(info.safeArea);Returns: GetSystemInfoResult
| Field | Type | Description |
|-------|------|-------------|
| model | string | Device model |
| pixelRatio | number | Device pixel ratio |
| windowWidth | number | Usable window width |
| windowHeight | number | Usable window height |
| screenWidth | number | Screen width |
| screenHeight | number | Screen height |
| statusBarHeight | number | Status bar height |
| titleBarHeight | number | Title bar height |
| language | string | System language |
| version | string | App version |
| platform | string | "iOS" or "Android" |
| system | string | OS version string |
| brand | string | Device brand |
| fontSizeSetting | number | User font size setting |
| storage | string | Available storage |
| currentBattery | string | Battery level |
| app | string | Host app identifier |
| safeArea | SafeArea | { left, right, top, bottom, width, height } |
Device — Network Type
getNetworkType()
Get the current network connection type.
import { getNetworkType } from "hylid-bridge-ts";
const { networkAvailable, networkType } = await getNetworkType();
if (!networkAvailable) {
await showToast("No network connection", "fail");
}Returns: GetNetworkTypeResult
| Field | Type | Description |
|-------|------|-------------|
| networkAvailable | boolean | Whether network is available |
| networkType | NetworkType | "WIFI" | "2G" | "3G" | "4G" | "UNKNOWN" | "NOTREACHABLE" | "NONE" |
Device — Clipboard
getClipboard()
Read text from the clipboard.
import { getClipboard } from "hylid-bridge-ts";
const { text } = await getClipboard();Returns: GetClipboardResult — { text: string }
setClipboard(text)
Write text to the clipboard.
import { setClipboard } from "hylid-bridge-ts";
await setClipboard("Copied text!");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| text | string | Yes | Text to copy |
Device — Battery
getBatteryInfo()
Get battery level and charging status.
import { getBatteryInfo } from "hylid-bridge-ts";
const { level, isCharging } = await getBatteryInfo();
console.log(`Battery: ${level}% ${isCharging ? "(charging)" : ""}`);Returns: GetBatteryInfoResult
| Field | Type | Description |
|-------|------|-------------|
| level | number | Battery percentage (0–100) |
| isCharging | boolean | Whether the device is charging |
Device — Screen Brightness
getScreenBrightness()
Get current screen brightness.
import { getScreenBrightness } from "hylid-bridge-ts";
const { brightness } = await getScreenBrightness();
// brightness is 0–1Returns: GetScreenBrightnessResult — { brightness: number }
setScreenBrightness(brightness)
Set screen brightness.
import { setScreenBrightness } from "hylid-bridge-ts";
await setScreenBrightness(0.8); // 80% brightness| Param | Type | Required | Description |
|-------|------|----------|-------------|
| brightness | number | Yes | Brightness level (0–1) |
Device — Add Contact
addPhoneContact(params)
Add a contact to the device address book.
import { addPhoneContact } from "hylid-bridge-ts";
await addPhoneContact({
firstName: "Ahmed",
lastName: "Ali",
mobilePhoneNumber: "+1234567890",
email: "[email protected]",
organization: "SuperQi",
title: "Developer",
});All params are optional:
| Param | Type | Description |
|-------|------|-------------|
| photoFilePath | string | Contact photo path |
| nickName | string | Nickname |
| firstName | string | First name |
| middleName | string | Middle name |
| lastName | string | Last name |
| remark | string | Notes |
| mobilePhoneNumber | string | Mobile number |
| homePhoneNumber | string | Home number |
| workPhoneNumber | string | Work number |
| homeFaxNumber | string | Home fax |
| workFaxNumber | string | Work fax |
| hostNumber | string | Host number |
| homeAddressCountry | string | Home country |
| homeAddressState | string | Home state |
| homeAddressCity | string | Home city |
| homeAddressStreet | string | Home street |
| homeAddressPostalCode | string | Home postal code |
| workAddressCountry | string | Work country |
| workAddressState | string | Work state |
| workAddressCity | string | Work city |
| workAddressStreet | string | Work street |
| workAddressPostalCode | string | Work postal code |
| organization | string | Company name |
| title | string | Job title |
| email | string | Email address |
| url | string | Website URL |
Error codes: 11 (cancelled), 2 (failure)
Device — Phone Call
makePhoneCall(number)
Initiate a phone call.
import { makePhoneCall } from "hylid-bridge-ts";
await makePhoneCall("+1234567890");| Param | Type | Required | Description |
|-------|------|----------|-------------|
| number | string | Yes | Phone number to call |
Note: Not supported in simulator.
Device — Scanner
scan(params?)
Open the QR code / barcode scanner.
import { scan } from "hylid-bridge-ts";
const { code } = await scan({ type: "qr" });
console.log("Scanned:", code);
// Barcode mode, hide album button
const { barCode } = await scan({ type: "bar", hideAlbum: true });| Param | Type | Required | Description |
|-------|------|----------|-------------|
| type | "qr" \| "bar" | No | Scan mode (default: "qr") |
| hideAlbum | boolean | No | Hide the album button (default: false) |
Returns: ScanResult
| Field | Type | Description |
|-------|------|-------------|
| code | string | Scanned content |
| qrCode | string \| undefined | QR code content (if scanned) |
| barCode | string \| undefined | Barcode content (if scanned) |
Error codes: 10 (cancelled), 11 (failure)
Device — Vibrate
vibrate()
Trigger a short device vibration.
import { vibrate } from "hylid-bridge-ts";
await vibrate();Bridge — Device Info (H5+)
getDeviceInfoBridge()
Get device info via the H5+ bridge (alternative to my.getDeviceInfo).
import { bridgeReady, getDeviceInfoBridge } from "hylid-bridge-ts";
await bridgeReady();
const info = await getDeviceInfoBridge();Returns: Same as getDeviceInfo()
Bridge — Ready Helper
bridgeReady()
Wait for AlipayJSBridge to be available. Use this in H5+ pages before calling any bridge methods.
import { bridgeReady } from "hylid-bridge-ts";
await bridgeReady();
// AlipayJSBridge is now availableIf AlipayJSBridge is already defined, resolves immediately. Otherwise, listens for the AlipayJSBridgeReady DOM event.
Types Reference
All types are exported and can be imported directly:
import type {
// Common
BaseCallbackParams,
JsApiError,
// Auth
AuthScope,
GetAuthCodeResult,
// Payment
TradePayResultCode,
TradePayResult,
// Device
UserRole,
SystemInfoObject,
SafeArea,
GetDeviceInfoResult,
NetworkType,
GetSystemInfoResult,
// UI
DatePickerFormat,
ToastType,
PromptAlign,
BadgeType,
ActionSheetBadge,
MultiLevelSelectItem,
// Media
ImageSourceType,
ImageSizeType,
ImageOrientation,
CompressLevel,
VideoSourceType,
CameraDirection,
// File
DigestAlgorithm,
SavedFileItem,
// Network
HttpMethod,
DataType,
RequestResult,
RequestTask,
// Scanner
ScanType,
// Maps (for advanced usage)
MyApiMap,
MyApiMethod,
BridgeApiMap,
BridgeApiMethod,
} from "hylid-bridge-ts";Error Handling
All promisified methods reject with a JsApiError-shaped object:
interface JsApiError {
error?: number;
errorMessage?: string;
}Use standard try/catch:
import { getLocation } from "hylid-bridge-ts";
import type { JsApiError } from "hylid-bridge-ts";
try {
const location = await getLocation();
} catch (err) {
const { error, errorMessage } = err as JsApiError;
switch (error) {
case 11:
console.log("User denied location permission");
break;
case 12:
console.log("Network failure");
break;
case 13:
console.log("Timeout");
break;
case 14:
console.log("Location service unavailable");
break;
default:
console.log("Unknown error:", errorMessage);
}
}License
MIT
