This is the full developer documentation for Capgo
# Welcome to Capgo Documentation
> Master Capgo Cloud for instant app updates and explore our comprehensive collection of Capacitor plugins to enhance your mobile development
## đ Capgo Cloud - Live Updates Made Simple
[Section titled âđ Capgo Cloud - Live Updates Made Simpleâ](#-capgo-cloud---live-updates-made-simple)
Instant Updates
Deploy JavaScript, HTML, and CSS updates directly to users without app store delays. Fix bugs and ship features in minutes, not days.
3-Step Integration
Get started with just `npx @capgo/cli@latest init [APIKEY]` and start pushing updates immediately with our simple integration.
Mobile & Desktop
Same live update system for Capacitor mobile apps and Electron desktop apps. One platform, all your apps.
Complete Guide
Learn everything from [quick setup](/docs/getting-started/quickstart/) to advanced deployment strategies in our comprehensive documentation.
## đ Whatâs in This Documentation
[Section titled âđ Whatâs in This Documentationâ](#-whats-in-this-documentation)
[Capgo Cloud Setup ](/docs/getting-started/quickstart/)Complete guides for integrating live updates, managing channels, CI/CD integration, and monitoring your deployments.
[Electron Updater ](/docs/plugins/electron-updater/)Live updates for Electron desktop apps. Same powerful system, now for desktop applications.
[20+ Capacitor Plugins ](/docs/plugins/)Explore our collection of production-ready plugins for biometrics, purchases, camera, storage, and more native features.
[CLI & Public API ](/docs/cli/overview/)Automate your workflow with our CLI tools and integrate Capgo into your existing systems with our REST API.
[Enterprise Solutions ](/enterprise/)Dedicated support, SLAs, custom features, and advanced security options for teams that need more.
## đŻ Quick Links
[Section titled âđŻ Quick Linksâ](#-quick-links)
* **First time?** Start with the [5-minute quickstart](/docs/getting-started/quickstart/)
* **Need a plugin?** Browse our [plugin collection](/docs/plugins/) or request [custom development](/consulting/)
* **Having issues?** Check the [FAQ](/docs/faq/) or join our [Discord](https://discord.capgo.app)
* **Enterprise needs?** Check our [enterprise solutions](/enterprise/) or [contact us](mailto:support@capgo.app)
# What Happens When Capgo is Unavailable
> Understanding Capgo behavior when service is down, canceled, or when you exceed plan limits
# What Happens When Capgo is Unavailable
[Section titled âWhat Happens When Capgo is Unavailableâ](#what-happens-when-capgo-is-unavailable)
Capgo is designed to be resilient and non-blocking. Your app continues to work even when Capgo services are temporarily unavailable. This document explains what happens in various scenarios.
## When Capgo Service is Down
[Section titled âWhen Capgo Service is Downâ](#when-capgo-service-is-down)
If Capgoâs servers are temporarily unavailable or experiencing an outage:
* **Your app continues to work normally** â Users can still open and use your app
* **Updates are not downloaded** â The automatic update check fails silently
* **No error is shown to users** â The update process gracefully fails in the background
* **Existing updates remain** â Any previously downloaded updates stay on the device
* **Updates resume automatically** â Once service is restored, normal update behavior resumes
Capgo is designed with a âfail-safeâ approach: if update services are unavailable, your app simply ignores the update and continues functioning normally.
## When You Cancel Capgo
[Section titled âWhen You Cancel Capgoâ](#when-you-cancel-capgo)
After canceling your Capgo subscription:
* **Existing updates remain on user devices** â Users who already downloaded updates keep those versions
* **No new updates are downloaded** â The app stops checking for and downloading updates
* **App functionality is unaffected** â Your app continues to work without any changes
* **Historical data is retained** â Your dashboard and analytics data remains accessible for a period
* **You can reactivate anytime** â Resubscribing restores full update functionality immediately
The update mechanism gracefully degrades â your app becomes âstaticâ but fully functional after cancellation.
## When You Exceed Your Plan Limits
[Section titled âWhen You Exceed Your Plan Limitsâ](#when-you-exceed-your-plan-limits)
If you exceed your planâs MAU (Monthly Active Users), bandwidth, or storage limits:
### MAU Limits
[Section titled âMAU Limitsâ](#mau-limits)
* **New users may not receive updates** â The update check continues but may be throttled
* **Existing users are unaffected** â Users who already have updates continue using them
* **Analytics may be incomplete** â New user tracking might be paused
### Bandwidth Limits
[Section titled âBandwidth Limitsâ](#bandwidth-limits)
* **Update downloads stop** â Users wonât receive new updates until you add credits or upgrade
* **App remains functional** â Existing app version continues to work
* **No error to users** â Update failures are silent and non-blocking
### Storage Limits
[Section titled âStorage Limitsâ](#storage-limits)
* **New uploads may fail** â You wonât be able to upload new app versions
* **Existing versions remain available** â Previously uploaded bundles still work
* **You can upgrade or add storage** â Resolving the limit restores full functionality
## Summary Table
[Section titled âSummary Tableâ](#summary-table)
| Scenario | App Works | Updates Download | Existing Updates Stay |
| --------------------- | --------- | ------------------------------- | --------------------- |
| Capgo Down | â Yes | â No | â Yes |
| Subscription Canceled | â Yes | â No | â Yes |
| MAU Limit Exceeded | â Yes | â ď¸ May stop | â Yes |
| Bandwidth Limit | â Yes | â No | â Yes |
| Storage Limit | â Yes | â ď¸ Downloads may be unavailable | â Yes |
## Best Practices
[Section titled âBest Practicesâ](#best-practices)
1. **Always test your app offline** â Ensure core functionality works without updates
2. **Keep a fallback plan** â Have a traditional app store update process as backup
3. **Monitor your limits** â Keep track of usage to avoid unexpected behavior
4. **Test cancellation scenarios** â Verify your app behaves correctly when updates stop
## Need Help?
[Section titled âNeed Help?â](#need-help)
If you have questions about Capgoâs availability policies or need assistance, please [contact support](/docs/getting-help).
# Introduction to Capgo Build
> Build iOS and Android apps in the cloud without local setup. No local Mac required for iOS builds.
Capgo Build is a cloud-based native app compilation service for Capacitor apps. It lets you build iOS and Android apps without maintaining local development environments - no Xcode, no Android Studio, no Mac hardware required on your own machine.
## What Capgo Build Does
[Section titled âWhat Capgo Build Doesâ](#what-capgo-build-does)
Capgo Build compiles the **native parts** of your Capacitor app in the cloud:
* **iOS builds** run on dedicated Mac Mini Silicon M4 machines
* **Android builds** run on the same Mac Mini Silicon M4 build fleet with Android Studio 2025 available
* **Automatic code signing** handles certificates, provisioning profiles, and keystores
* **Direct store submission** uploads signed apps to App Store Connect and Google Play
You trigger builds with a single CLI command that works from anywhere - your local machine, GitHub Actions, GitLab CI, or any CI/CD pipeline.
## Build Machines and Toolchain
[Section titled âBuild Machines and Toolchainâ](#build-machines-and-toolchain)
Capgo Build runs native jobs on dedicated Mac Mini Silicon M4 machines:
| Component | Specification |
| ------------- | -------------------------------------------------------- |
| Machine | Mac Mini Silicon M4 |
| CPU | 10-core M4 CPU (4 performance cores, 6 efficiency cores) |
| GPU | 10-core GPU |
| Neural Engine | 16-core Neural Engine |
| Memory | 16GB of RAM |
| OS image | macOS Tahoe 26.2 |
The build image supports Xcode 26.2, Android Studio 2025, and .NET 9/.NET 10 SDK workloads for native build pipelines.
## When to Use Capgo Build vs Live Updates
[Section titled âWhen to Use Capgo Build vs Live Updatesâ](#when-to-use-capgo-build-vs-live-updates)
Capgo offers two complementary features for updating your app. Hereâs when to use each:
| Scenario | Live Updates | Capgo Build |
| --------------------------------------------------------- | :----------: | :---------: |
| Bug fix in JavaScript/TypeScript code | â | |
| UI changes (HTML, CSS, images) | â | |
| Updating web dependencies | â | |
| Adding or removing a Capacitor plugin | | â |
| Updating a native SDK version | | â |
| Changing native permissions (Info.plist, AndroidManifest) | | â |
| Updating Capacitor version | | â |
| Modifying native code (Swift, Kotlin, Java) | | â |
| Changing app icon or splash screen | | â |
| First app store submission | | â |
Note
**Live Updates** push JavaScript changes instantly without app store review. **Capgo Build** creates new native binaries when you change native code. Most teams use Live Updates daily and Capgo Build occasionally when native changes are needed.
## Why Use Capgo Build
[Section titled âWhy Use Capgo Buildâ](#why-use-capgo-build)
No Local Mac Required for iOS
Build and ship iOS apps without owning Mac hardware. Anyone on Windows, Linux, or any CI/CD system can trigger iOS builds and publish to TestFlight.
Skip Local Environment Setup
No need to install Xcode, Android Studio, or manage SDK versions. Capgo Build handles all native tooling - you just run the CLI command.
Centralized Credentials
Store your certificates and keystores in your CI/CD secrets once. Any team member can trigger builds without needing signing credentials on their local machine.
Works With Any CI/CD
A single CLI command integrates with any pipeline. GitHub Actions, GitLab CI, Jenkins - trigger builds as part of your existing workflow.
Real-Time Build Logs
Watch your build progress live in your terminal. Logs stream via Server-Sent Events so you can debug issues instantly as they happen.
Direct Store Submission
Signed apps upload directly to App Store Connect and Google Play. No manual steps between build completion and store submission.
## How It Works
[Section titled âHow It Worksâ](#how-it-works)
When you run the build command:
1. **Upload** - The CLI zips only whatâs needed (native platform folder + native dependencies) and uploads to secure cloud storage
2. **Build** - Your app compiles on dedicated infrastructure using Fastlane
3. **Sign** - Certificates and keystores are applied (they exist only in memory during the build)
4. **Submit** - Signed apps are uploaded directly to App Store Connect or Google Play
5. **Cleanup** - All build artifacts and credentials are automatically deleted
Your source code stays on your machine. Only the platform-specific native code is uploaded.
## Security Model
[Section titled âSecurity Modelâ](#security-model)
Capgo Build is designed with zero credential storage:
* **Runtime-only credentials** - Certificates and keystores are never stored in Capgo. They are uploaded and removed immediately after the build finishes.
* **Ephemeral environments** - Each build runs in isolation and is destroyed after completion
* **No log storage** - Build logs stream to your terminal only, never stored on Capgo servers
* **Minimal upload** - Only the native platform you request is uploaded, not your full codebase. [See exactly what gets uploaded](/docs/cli/cloud-build/getting-started/#what-gets-built)
## Pricing
[Section titled âPricingâ](#pricing)
Build time is the only cost:
* Build minutes are included in your Capgo plan
* Extra minutes available via credit system
* Builds run on Mac Mini Silicon M4 machines with the native toolchains already installed
* No storage fees
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
[Getting Started ](/docs/cli/cloud-build/getting-started/)Create your first build and see Capgo Build in action.
[Credentials Setup ](/docs/cli/cloud-build/credentials/)Configure certificates for iOS and keystores for Android.
[iOS Builds ](/docs/cli/cloud-build/ios/)Complete guide to building and submitting iOS apps.
[Android Builds ](/docs/cli/cloud-build/android/)Complete guide to building and submitting Android apps.
# Android Builds
> Configure and build Android apps with Capgo Cloud Build
Build and submit Android apps to Google Play Store using Capgoâs dedicated infrastructure.
## What you will learn
[Section titled âWhat you will learnâ](#what-you-will-learn)
* You will learn how to upload your app via Capgo Native build
* You will learn how to configure the credentials for Capgo Native Build
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
* You need to have an active Google Developer account
* You need to have Android Studio installed
* Your app must be able to build successfully with Android Studio
Note
I will use the following app for the tutorial:
## The first manual build
[Section titled âThe first manual buildâ](#the-first-manual-build)
Before we can start thinking about building the app with Capgo, we should first set it up, and do a first Android build by hand. There are some advantages to doing a manual build first:
* You will prepare the credentials for the later Capgo build
* You will create a record on the Play Store Console
### Building the app manually with Android Studio
[Section titled âBuilding the app manually with Android Studioâ](#building-the-app-manually-with-android-studio)
Before we can start building the app with Capgo, we need to build the app manually with Android Studio.
1. Open Android Studio
Run `bunx cap open android` to open the Android Studio project.
2. Click on `Build` -> `Generate Signed App Bundles / APKs` 
3. Select `Android App Bundle` and click on `Next` 
### Creating a Keystore
[Section titled âCreating a Keystoreâ](#creating-a-keystore)
Right now, you are missing the keystore file. This file is used to sign your app, which lets Google know that itâs you who built the app. To generate it, we will use the GUI method provided by Android Studio. There is also a way to do this with the command line, but we will not cover that in this tutorial.
1. Click on `Create new` 
2. Fill in the Key Store path 
Caution
This **IS TO BE SAVED** - it will be used later
3. Set the Key Store password 
Note
I recommend using the same password for the Key Store and the Key Alias.
Caution
This **IS TO BE SAVED** - it will be used later
4. Fill the rest of the form
1. Keep the Key Alias as is (key0)
2. Fill the certificate details. I have filled it with fake details, but you should fill it with your own details.

5. Click on `OK` 
### Finishing the manual build
[Section titled âFinishing the manual buildâ](#finishing-the-manual-build)
1. Make sure all of the details for the keystore have been filled in correctly and click on `Next` 
2. Select the `release` build variant and click on `Create` 
3. After the build succeeds, you should see the following screen 
1. This popup indicates that the build succeeded.
2. Click on the `locate` button - this will open the file explorer and you should see the build there.
4. Make sure you can see the build in the file explorer 
### Creating the app on the Play Store Console
[Section titled âCreating the app on the Play Store Consoleâ](#creating-the-app-on-the-play-store-console)
1. Go to [Google Play Console](https://play.google.com/console/)
2. Select the correct developer account 
3. Click on `Create app` 
4. Choose the app name and the language 
5. Select the app category and if the app is paid or free 
6. Accept the terms and conditions 
Caution
Make sure you read the terms and conditions before accepting them.
7. Click on `Create` 
### Creating the internal testing group
[Section titled âCreating the internal testing groupâ](#creating-the-internal-testing-group)
Now that you have created the app, you can create an internal testing group. Since I wonât actually publish the app for everyone on Play Store, I will need to create an internal testing group.
Note
Internal testing is still the fastest way to smoke-test your Play-distributed build before a real launch.
If your developer account is a personal account created after November 13, 2023, internal testing does **not** replace the closed-testing requirement for production access. You will still need a closed test with at least 12 opted-in testers for 14 consecutive days before production.
1. Go to `internal testing` Click on `Test and release` -> `Testing` -> `Internal testing`

2. Click on `Testers` 
3. Click on `Create email list` 
4. Name the email list 
5. Add the email addresses of the testers 
6. Press `Enter` and click on `Save` 
7. Click on `Create group` 
8. Make sure that the new list is selected and click on `Save` 
### Uploading the app to the internal testing group
[Section titled âUploading the app to the internal testing groupâ](#uploading-the-app-to-the-internal-testing-group)
Now that you have created the internal testing group, you can upload the app to the internal testing group.
1. Go to `Test and release` -> `Testing` -> `Internal testing` 
2. Click on the `Releases` button 
3. Click on `Create new release` 
4. Click on `Upload` 
5. Select the AAB file 
Caution
Make sure you select the AAB file that you built manually with Android Studio. If this file doesnât use the same keystore as the one you will use for the Capgo build, the Capgo Native Build will fail.
6. Wait for the AAB file to be uploaded
7. Click on `Next` 
8. Fix the errors
Personally, at this stage I see this error

This is because I havenât verified my phone number yet. I will do that and continue the tutorial.
9. Click on `Save and publish` This will publish the app to the internal testing group. 
10. Confirm the publication 
11. Make sure the app is published 
12. Get your temporary app name 
### Accept the invitation to internal testing group
[Section titled âAccept the invitation to internal testing groupâ](#accept-the-invitation-to-internal-testing-group)
Now that you have uploaded the app to the internal testing group, you can accept the invitation to the internal testing group.
1. Go to `Test and release` -> `Testing` -> `Internal testing` 
2. Click on `Testers` 
3. Click on `Copy link` 
4. Send the link to your phone, open it in the browser and click on `Accept` 
5. Confirm the invitation has been accepted and click on âdownload it on Play Storeâ 
6. Install the app
1. If you had installed the app before using Android Studio, click on the `uninstall` button 
2. Click on the `install` button 
3. Open the app and confirm it has downloaded successfully [](/native-build-assets/screen-20260215-072439-1771136671038.mp4 "App downloaded successfully from Play Store internal testing")
Caution
If you do not see the app in Play Store, make sure you have selected the correct account in Play Store.
## Configuring Capgo Native Build (Android)
[Section titled âConfiguring Capgo Native Build (Android)â](#configuring-capgo-native-build-android)
Now, you are ready to start the setup of Capgo Native Build. Congratulations đ!
| Requirement | Flag | Description | Required |
| --------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------- |
| Keystore file | `--keystore ` | Path to your `.jks`/`.keystore` file used to sign the APK/AAB. | Yes |
| Keystore alias | `--keystore-alias ` | Alias name of the key inside the keystore. | Yes |
| Keystore key password | `--keystore-key-password ` | Password for the key. If key/store passwords match, you can provide only one. | Look at the note below |
| Keystore store password | `--keystore-store-password ` | Password for the keystore. If key/store passwords match, you can provide only one. | Look at the note below |
| Google Play service account | `--play-config ` | JSON service account file for Play Store uploads. | Yes |
```bash
bunx @capgo/cli build credentials save --platform android \
--keystore ./path/to/keystore.jks \
--keystore-alias "your-alias" \
--keystore-key-password "key-password" \
--keystore-store-password "store-password" \
--play-config ./play-store-service-account.json
```
Note
If key and store passwords are identical, provide only one of `--keystore-key-password` or `--keystore-store-password`.
### Keystore, keystore password, keystore key password, keystore alias
[Section titled âKeystore, keystore password, keystore key password, keystore aliasâ](#keystore-keystore-password-keystore-key-password-keystore-alias)
If you have followed the [manual build instructions](/docs/cli/cloud-build/android/#building-the-app-manually-with-android-studio), you should have the keystore already generated. If you have not followed the instructions, please follow them to generate the keystore.
### Google Play service account
[Section titled âGoogle Play service accountâ](#google-play-service-account)
Generating the Google Play service account is a manual and complex process. Yet, it is required to upload your app to Google Play. Please keep in mind the following things:
* You **NEED** to be the [owner of the Developer Account](https://support.google.com/googleplay/android-developer/thread/238025575?hl=en\&msgid=238033420). Otherwise, you will not be able to setup the service account.
* You will need to create a new Google Cloud Project (separate from your Google Play Account)
Letâs begin.
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Click on the project selector 
3. If you already have a project, select it. Otherwise, create a new project:
Note
The screenshots below are illustrative - use a name appropriate for your project.
1. Click on `New project` 
2. Name your project and click `Create` 
3. Ensure that you are on the right project 
4. Letâs click on the search bar and search for `service accounts` and click on it  
5. Letâs click on `Create service account` 
6. Fill in the form for the service account and click on `Done`
1. I recommend setting the name to `Capgo Native Build Service Account`
2. For the Service Account ID, I recommend setting it to `capgo-native-build-service-acc`
3. As for the description, you donât have to fill it in, but I recommend filling it with `Allows Capgo Native Build to build and submit the app to the Play Store`

7. Click on the newly created service account You should now see the newly created service account in the list. Click on it. 
Note
Copy this email address as well, you will need it later.
8. Click on the `Keys` tab 
9. Click on `Add Key` and `Create new key` 
10. Click on `JSON` and `Create` 
Caution
Clicking on `Create` will create a new key and it will download the JSON file to your local machine.
You need to save the JSON file in a safe place. It **WILL** be used later.
11. Download the JSON file The JSON file should have been downloaded automatically. You can click on `close` to close the window. 
### Granting Play Store API access to the service account
[Section titled âGranting Play Store API access to the service accountâ](#granting-play-store-api-access-to-the-service-account)
The newly created service account does not yet have access to the Play Store API. To grant it, head to the Play Store Console.
1. Go to [Google Play Console](https://play.google.com/console/)
2. Select the correct developer account 
3. Click on `Users and permissions` 
4. Click on `Invite new users` 
5. Copy the email address of the service account 
6. Go to `Account permissions` and grant the minimum required permissions:
* In `App permissions`, grant access to your app.
* In `Releases`, enable `Create, edit, and roll out releases`.
* If your workflow uses Play App Signing, enable the related signing permission.
* If you are unsure, use `Admin` only during setup, then reduce permissions afterward. 
7. Click on `Invite user` 
8. Confirm the invitation 
9. Confirm that the user has been invited 
### Saving the credentials
[Section titled âSaving the credentialsâ](#saving-the-credentials)
You are now ready to save the credentials and run your first build. You can save the credentials using the following command:
```bash
bunx @capgo/cli build credentials save --platform android \
--keystore ./path/to/keystore.jks \
--keystore-alias "your-alias" \
--keystore-key-password "key-password" \
--keystore-store-password "store-password" \
--play-config ./play-store-service-account.json
```
### CI/CD setup (GitHub Actions)
[Section titled âCI/CD setup (GitHub Actions)â](#cicd-setup-github-actions)
If you already completed [Keystore, keystore password, keystore key password, keystore alias](#keystore-keystore-password-keystore-key-password-keystore-alias) and [Google Play service account](#google-play-service-account), you already have everything needed for CI/CD. This section only covers how to pass those values as GitHub Actions secrets and environment variables.
#### 1) Convert credential files to single-line base64
[Section titled â1) Convert credential files to single-line base64â](#1-convert-credential-files-to-single-line-base64)
```bash
# Android keystore (.jks or .keystore)
base64 -i ./path/to/keystore.jks | tr -d '\n' > keystore_base64.txt
# Google Play service account JSON
base64 -i ./play-store-service-account.json | tr -d '\n' > play_config_base64.txt
```
Tip
GitHub secrets should be single-line values. `tr -d '\n'` removes line breaks from base64 output.
#### 2) Create repository secrets
[Section titled â2) Create repository secretsâ](#2-create-repository-secrets)
In `GitHub > Repository > Settings > Secrets and variables > Actions`, add:
| Secret name | Value |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CAPGO_TOKEN` | Your Capgo API token |
| `APP_ID` | Your Capgo app ID (example: `com.example.app`) |
| `ANDROID_KEYSTORE_FILE` | Content of `keystore_base64.txt` |
| `KEYSTORE_KEY_ALIAS` | Keystore alias from [Keystore, keystore password, keystore key password, keystore alias](#keystore-keystore-password-keystore-key-password-keystore-alias) |
| `KEYSTORE_KEY_PASSWORD` | Keystore key password |
| `KEYSTORE_STORE_PASSWORD` | Keystore store password |
| `PLAY_CONFIG_JSON` | Content of `play_config_base64.txt` |
Note
If key and store passwords are the same, you can provide just one of `KEYSTORE_KEY_PASSWORD` or `KEYSTORE_STORE_PASSWORD`.
#### 3) Use env vars in your GitHub Actions workflow
[Section titled â3) Use env vars in your GitHub Actions workflowâ](#3-use-env-vars-in-your-github-actions-workflow)
.github/workflows/android-build.yml
```yaml
name: Android Cloud Build
on:
workflow_dispatch:
push:
branches: [main]
jobs:
android-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Request Android build with Capgo
run: bunx @capgo/cli@latest build ${{ secrets.APP_ID }} --platform android
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
ANDROID_KEYSTORE_FILE: ${{ secrets.ANDROID_KEYSTORE_FILE }}
KEYSTORE_KEY_ALIAS: ${{ secrets.KEYSTORE_KEY_ALIAS }}
KEYSTORE_KEY_PASSWORD: ${{ secrets.KEYSTORE_KEY_PASSWORD }}
KEYSTORE_STORE_PASSWORD: ${{ secrets.KEYSTORE_STORE_PASSWORD }}
PLAY_CONFIG_JSON: ${{ secrets.PLAY_CONFIG_JSON }}
```
Tip
With this setup, CI sends credentials through environment variables only. You do not need to commit signing files or upload them as workflow artifacts.
### Running the build
[Section titled âRunning the buildâ](#running-the-build)
Congratulations đ! You are now ready to run your first build.
Run:
```bash
bunx @capgo/cli build com.example.app --platform android
```
And this will start the build process đžđĽ
# Configuration Options
> Complete reference for all Cloud Build CLI flags, environment variables, and credential keys
Complete reference for every Cloud Build configuration option. Use this page to find the CLI flag, environment variable, or credential key for any build setting.
## Configuration Precedence
[Section titled âConfiguration Precedenceâ](#configuration-precedence)
Every build option can be set in multiple ways. When the same option is set in multiple places, higher-priority sources win:
```
flowchart LR
A["đ§ CLI Flag"] -->|overrides| B["đ Environment Variable"]
B -->|overrides| C["đ Local Credentials"]
C -->|overrides| D["đ Global Credentials"]
style A fill:#6366f1,color:#fff,stroke:#4f46e5
style B fill:#8b5cf6,color:#fff,stroke:#7c3aed
style C fill:#a78bfa,color:#fff,stroke:#8b5cf6
style D fill:#c4b5fd,color:#1e1b4b,stroke:#a78bfa
```
**Example:** If your saved credentials have `SKIP_BUILD_NUMBER_BUMP=true` but you pass `--no-skip-build-number-bump` on the CLI, the CLI flag wins and build numbers will be auto-incremented.
Tip
For CI/CD pipelines, environment variables are usually the most convenient. For local development, saved credentials (via `build credentials save`) avoid repeating flags every time.
***
## iOS Options
[Section titled âiOS Optionsâ](#ios-options)
### Code Signing
[Section titled âCode Signingâ](#code-signing)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| ------------------------------------------------- | ------------------------------------- | ------------------------------------- | ------- | ------------------------------------------------------------------------- |
| `--build-certificate-base64 ` | `BUILD_CERTIFICATE_BASE64` | `BUILD_CERTIFICATE_BASE64` | â | Base64-encoded `.p12` distribution certificate |
| `--build-provision-profile-base64 ` | `BUILD_PROVISION_PROFILE_BASE64` | `BUILD_PROVISION_PROFILE_BASE64` | â | Base64-encoded `.mobileprovision` provisioning profile |
| `--build-provision-profile-base64-prod ` | `BUILD_PROVISION_PROFILE_BASE64_PROD` | `BUILD_PROVISION_PROFILE_BASE64_PROD` | â | Production provisioning profile (optional, for App Store distribution) |
| `--p12-password ` | `P12_PASSWORD` | `P12_PASSWORD` | â | Password for the `.p12` certificate (omit if certificate has no password) |
### App Store Connect Authentication
[Section titled âApp Store Connect Authenticationâ](#app-store-connect-authentication)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| ---------------------------------- | --------------------------- | --------------------------- | ------- | ------------------------------------------------------------ |
| `--apple-key-id ` | `APPLE_KEY_ID` | `APPLE_KEY_ID` | â | App Store Connect API Key ID |
| `--apple-issuer-id ` | `APPLE_ISSUER_ID` | `APPLE_ISSUER_ID` | â | App Store Connect Issuer ID (UUID) |
| `--apple-key-content ` | `APPLE_KEY_CONTENT` | `APPLE_KEY_CONTENT` | â | Base64-encoded App Store Connect API key (`.p8` file) |
| `--apple-profile-name ` | `APPLE_PROFILE_NAME` | `APPLE_PROFILE_NAME` | â | Provisioning profile name as shown in Apple Developer portal |
| `--app-store-connect-team-id ` | `APP_STORE_CONNECT_TEAM_ID` | `APP_STORE_CONNECT_TEAM_ID` | â | App Store Connect Team ID |
Note
**Alternative authentication:** You can also use Apple ID + app-specific password instead of API keys. Pass `--apple-id ` and `--apple-app-specific-password ` (env vars: `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`). API keys are recommended for CI/CD.
### iOS Build Settings
[Section titled âiOS Build Settingsâ](#ios-build-settings)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| ----------------------- | ------------------ | ------------------ | ------- | --------------------------------------- |
| `--ios-scheme ` | `CAPGO_IOS_SCHEME` | `CAPGO_IOS_SCHEME` | `App` | Xcode scheme to build |
| `--ios-target ` | `CAPGO_IOS_TARGET` | `CAPGO_IOS_TARGET` | `App` | Xcode target for reading build settings |
***
## Android Options
[Section titled âAndroid Optionsâ](#android-options)
### Keystore Signing
[Section titled âKeystore Signingâ](#keystore-signing)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| -------------------------------------- | ------------------------- | ------------------------- | ------- | --------------------------------------------------------------- |
| `--android-keystore-file ` | `ANDROID_KEYSTORE_FILE` | `ANDROID_KEYSTORE_FILE` | â | Base64-encoded keystore file (`.keystore` or `.jks`) |
| `--keystore-key-alias ` | `KEYSTORE_KEY_ALIAS` | `KEYSTORE_KEY_ALIAS` | `key0` | Keystore key alias |
| `--keystore-key-password ` | `KEYSTORE_KEY_PASSWORD` | `KEYSTORE_KEY_PASSWORD` | â | Keystore key password (falls back to store password if not set) |
| `--keystore-store-password ` | `KEYSTORE_STORE_PASSWORD` | `KEYSTORE_STORE_PASSWORD` | â | Keystore store password |
### Google Play Configuration
[Section titled âGoogle Play Configurationâ](#google-play-configuration)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| --------------------------- | ------------------ | ------------------ | ------- | --------------------------------------------------- |
| `--play-config-json ` | `PLAY_CONFIG_JSON` | `PLAY_CONFIG_JSON` | â | Base64-encoded Google Play service account JSON key |
### Android Build Settings
[Section titled âAndroid Build Settingsâ](#android-build-settings)
| Env Variable | Default | Description |
| --------------------------- | ---------- | --------------------------------------------------------------------- |
| `PLAY_STORE_TRACK` | `internal` | Google Play release track (`internal`, `alpha`, `beta`, `production`) |
| `PLAY_STORE_RELEASE_STATUS` | `draft` | Release status on Google Play (`draft`, `completed`) |
***
## Build Control Options
[Section titled âBuild Control Optionsâ](#build-control-options)
These options work for both iOS and Android builds.
### Build Mode
[Section titled âBuild Modeâ](#build-mode)
| CLI Flag | Default | Description |
| ----------------------- | --------- | ----------------------------------- |
| `--platform ` | â | **Required.** `ios` or `android` |
| `--build-mode ` | `release` | `debug` or `release` |
| `--build-config ` | â | Additional JSON build configuration |
| `--path ` | `.` | Project directory |
| `--verbose` | `false` | Enable verbose build logging |
### Build Number Control
[Section titled âBuild Number Controlâ](#build-number-control)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| ----------------------------- | ------------------------ | ------------------------ | ------- | ----------------------------------------------------------------- |
| `--skip-build-number-bump` | `SKIP_BUILD_NUMBER_BUMP` | `SKIP_BUILD_NUMBER_BUMP` | `false` | Skip automatic build number / version code incrementing |
| `--no-skip-build-number-bump` | â | â | â | Explicitly re-enable auto-increment (overrides saved credentials) |
By default, Capgo Cloud Build automatically increments build numbers:
* **iOS:** Fetches latest build number from App Store Connect, increments by 1
* **Android:** Fetches max `versionCode` from Google Play, increments by 1
When `--skip-build-number-bump` is set, the build uses whatever version is already in your project files (Xcode project or `build.gradle`).
### Output Upload
[Section titled âOutput Uploadâ](#output-upload)
| CLI Flag | Env Variable | Credential Key | Default | Description |
| ------------------------------- | -------------------------------- | -------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| `--output-upload` | `BUILD_OUTPUT_UPLOAD_ENABLED` | `BUILD_OUTPUT_UPLOAD_ENABLED` | `false` | Upload build outputs (IPA/APK/AAB) to Capgo storage. When set via env var, use `BUILD_OUTPUT_UPLOAD_ENABLED=true`. |
| `--no-output-upload` | `BUILD_OUTPUT_UPLOAD_ENABLED` | â | â | Disable output upload. When set via env var, use `BUILD_OUTPUT_UPLOAD_ENABLED=false`. |
| `--output-retention ` | `BUILD_OUTPUT_RETENTION_SECONDS` | `BUILD_OUTPUT_RETENTION_SECONDS` | `1h` | How long download links remain active |
**Retention format:** Use human-readable durations like `1h`, `6h`, `2d`, `7d`. Minimum is 1 hour, maximum is 7 days. When set via env var, use seconds (e.g., `3600` for 1 hour).
### Authentication
[Section titled âAuthenticationâ](#authentication)
| CLI Flag | Env Variable | Default | Description |
| -------------------- | ------------- | ------- | -------------------------------------------- |
| `-a, --apikey ` | `CAPGO_TOKEN` | â | Capgo API key for authentication |
| `--supa-host ` | â | â | Custom Supabase host (self-hosting only) |
| `--supa-anon ` | â | â | Custom Supabase anon key (self-hosting only) |
***
## Environment Variable Quick Reference
[Section titled âEnvironment Variable Quick Referenceâ](#environment-variable-quick-reference)
Copy-paste ready for your CI/CD pipeline. All variables are optional â only set what you need.
### iOS
[Section titled âiOSâ](#ios)
```bash
# Code signing (required for iOS builds)
BUILD_CERTIFICATE_BASE64=""
BUILD_PROVISION_PROFILE_BASE64=""
P12_PASSWORD=""
# App Store Connect (required for store submission)
APPLE_KEY_ID="ABC1234567"
APPLE_ISSUER_ID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
APPLE_KEY_CONTENT=""
APPLE_PROFILE_NAME="My App Distribution Profile"
APP_STORE_CONNECT_TEAM_ID="TEAM123456"
# Optional iOS settings
CAPGO_IOS_SCHEME="App"
CAPGO_IOS_TARGET="App"
```
### Android
[Section titled âAndroidâ](#android)
```bash
# Keystore signing (required for Android builds)
ANDROID_KEYSTORE_FILE=""
KEYSTORE_KEY_ALIAS="my-key-alias"
KEYSTORE_KEY_PASSWORD=""
KEYSTORE_STORE_PASSWORD=""
# Google Play (required for store submission)
PLAY_CONFIG_JSON=""
# Optional Android settings
PLAY_STORE_TRACK="internal"
PLAY_STORE_RELEASE_STATUS="draft"
```
### Build Control
[Section titled âBuild Controlâ](#build-control)
```bash
# Build behavior
SKIP_BUILD_NUMBER_BUMP="true" # Skip auto-increment
BUILD_OUTPUT_UPLOAD_ENABLED="true" # Upload IPA/APK/AAB
BUILD_OUTPUT_RETENTION_SECONDS="3600" # 1 hour download link
# Authentication
CAPGO_TOKEN="your-api-key"
```
***
## Credential Storage
[Section titled âCredential Storageâ](#credential-storage)
### Save Credentials Locally
[Section titled âSave Credentials Locallyâ](#save-credentials-locally)
Instead of passing flags or env vars every time, save credentials once:
```bash
# Save iOS credentials
bunx @capgo/cli build credentials save \
--platform ios \
--certificate ./dist_cert.p12 \
--provisioning-profile ./profile.mobileprovision \
--p12-password "cert-password" \
--apple-key ./AuthKey.p8 \
--apple-key-id ABC1234567 \
--apple-issuer-id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \
--apple-profile-name "My App Profile" \
--apple-team-id TEAM123456
# Save Android credentials
bunx @capgo/cli build credentials save \
--platform android \
--keystore ./release.keystore \
--keystore-alias my-key \
--keystore-key-password "key-pass" \
--keystore-store-password "store-pass" \
--play-config ./play-service-account.json
```
### Storage Locations
[Section titled âStorage Locationsâ](#storage-locations)
| Flag | Location | Use Case |
| ----------- | ----------------------------------------- | --------------------------------------------------- |
| *(default)* | `~/.capgo-credentials/credentials.json` | Global â shared across all projects on your machine |
| `--local` | `.capgo-credentials.json` in project root | Per-project â overrides global when both exist |
Credentials are keyed by **app ID** (e.g. `com.example.myapp`), so a single credentials file can store settings for multiple apps without conflicts. Each appâs credentials are further split by platform (`ios` / `android`).
Caution
Add `.capgo-credentials.json` to your `.gitignore` if using local credentials. Never commit credentials to version control.
### Manage Saved Credentials
[Section titled âManage Saved Credentialsâ](#manage-saved-credentials)
```bash
# List saved credentials
bunx @capgo/cli build credentials list
# Update a specific option without re-entering everything
bunx @capgo/cli build credentials update --skip-build-number-bump
# Clear saved credentials
bunx @capgo/cli build credentials clear --platform ios
```
***
## Examples
[Section titled âExamplesâ](#examples)
### GitHub Actions
[Section titled âGitHub Actionsâ](#github-actions)
```yaml
name: Build and Submit
on:
push:
branches: [main]
jobs:
build-ios:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- run: bun install
- run: bunx cap sync ios
- run: bunx @capgo/cli build request --platform ios
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
BUILD_CERTIFICATE_BASE64: ${{ secrets.IOS_CERTIFICATE }}
BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.IOS_PROFILE }}
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
APPLE_KEY_ID: ${{ secrets.APPLE_KEY_ID }}
APPLE_ISSUER_ID: ${{ secrets.APPLE_ISSUER_ID }}
APPLE_KEY_CONTENT: ${{ secrets.APPLE_KEY_CONTENT }}
APPLE_PROFILE_NAME: ${{ secrets.APPLE_PROFILE_NAME }}
APP_STORE_CONNECT_TEAM_ID: ${{ secrets.APP_STORE_CONNECT_TEAM_ID }}
build-android:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- run: bun install
- run: bunx cap sync android
- run: bunx @capgo/cli build request --platform android
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
ANDROID_KEYSTORE_FILE: ${{ secrets.ANDROID_KEYSTORE }}
KEYSTORE_KEY_ALIAS: ${{ secrets.KEYSTORE_ALIAS }}
KEYSTORE_KEY_PASSWORD: ${{ secrets.KEYSTORE_KEY_PASSWORD }}
KEYSTORE_STORE_PASSWORD: ${{ secrets.KEYSTORE_STORE_PASSWORD }}
PLAY_CONFIG_JSON: ${{ secrets.PLAY_CONFIG_JSON }}
```
### Using CLI Flags Directly
[Section titled âUsing CLI Flags Directlyâ](#using-cli-flags-directly)
```bash
# Build iOS with all options inline
bunx @capgo/cli build request \
--platform ios \
--build-mode release \
--skip-build-number-bump \
--output-retention 6h \
--apikey YOUR_API_KEY
# Build Android, skip version bump, no output upload
bunx @capgo/cli build request \
--platform android \
--skip-build-number-bump \
--no-output-upload \
--apikey YOUR_API_KEY
```
### Mixed Configuration
[Section titled âMixed Configurationâ](#mixed-configuration)
Combine saved credentials with CLI overrides:
```bash
# Save base credentials once
bunx @capgo/cli build credentials save --platform ios \
--certificate ./cert.p12 \
--provisioning-profile ./profile.mobileprovision \
--output-upload
# Override specific options per-build
bunx @capgo/cli build request --platform ios \
--skip-build-number-bump \
--output-retention 2d
```
The saved credentials provide signing details while CLI flags override build behavior for this specific run.
# Managing Credentials
> Save and manage build credentials locally for iOS and Android builds
Manage your iOS and Android build credentials locally for convenient cloud builds.
## Overview
[Section titled âOverviewâ](#overview)
Capgo CLI allows you to save build credentials locally on your machine in the `.capgo-credentials` folder. When you run a build, these credentials are automatically used and sent securely to Capgoâs build servers.
Need Help Getting Credentials?
If you donât have your certificates and credentials yet, check these comprehensive guides:
**iOS:**
* [How to Get iOS Certificates](/docs/cli/cloud-build/ios/#how-to-get-ios-certificates-and-provisioning-profiles) - Step-by-step guide
* [iOS Certificates Guide](/docs/cli/cloud-build/ios/) - Detailed step-by-step tutorial
* [Blog: Automatic iOS Builds](https://capgo.app/blog/automatic-capacitor-ios-build-github-action/) - Complete CI/CD setup
**Android:**
* [Creating a Keystore](/docs/cli/cloud-build/android/#creating-a-keystore) - Step-by-step guide
* [Android Certificates Guide](/docs/cli/cloud-build/android/) - Detailed step-by-step tutorial
* [Blog: Automatic Android Builds](https://capgo.app/blog/automatic-capacitor-android-build-github-action/) - Complete CI/CD setup
Security Guarantee
**Your credentials are NEVER stored permanently on Capgo servers:**
* â Used ONLY during the active build process
* â Automatically deleted after build completion
* â Maximum retention: 24 hours (even if build fails)
* â Apps are sent directly to App Store/Play Store - we store NOTHING
* â Transmitted securely over HTTPS
## Commands
[Section titled âCommandsâ](#commands)
### Save Credentials
[Section titled âSave Credentialsâ](#save-credentials)
Store your build credentials locally for automatic use:
```bash
npx @capgo/cli build credentials save --platform [options]
```
### Update Credentials
[Section titled âUpdate Credentialsâ](#update-credentials)
Partially update existing credentials without re-providing everything:
```bash
npx @capgo/cli build credentials update --platform [options]
```
The `update` command uses **additive merge** for provisioning profiles â new profiles are merged with existing ones. To replace the entire provisioning map instead, add `--overwrite-ios-provisioning-map`.
Example â add an extension profile to existing credentials:
```bash
npx @capgo/cli build credentials update \
--platform ios \
--ios-provisioning-profile "com.example.app.widget=./widget_profile.mobileprovision"
```
The update command accepts the same options as `save` but all are optional â only the fields you provide are updated.
### List Credentials
[Section titled âList Credentialsâ](#list-credentials)
View currently saved credentials (passwords are masked):
```bash
npx @capgo/cli build credentials list
# List credentials for a specific app
npx @capgo/cli build credentials list --appId com.example.app
```
### Clear Credentials
[Section titled âClear Credentialsâ](#clear-credentials)
Remove saved credentials from your local machine:
```bash
# Clear all credentials
npx @capgo/cli build credentials clear
# Clear credentials for a specific app + platform
npx @capgo/cli build credentials clear --appId com.example.app --platform ios
```
### Migrate Credentials
[Section titled âMigrate Credentialsâ](#migrate-credentials)
Convert legacy single-profile format to the new multi-target format:
```bash
npx @capgo/cli build credentials migrate --platform ios
```
The migrate command detects old `BUILD_PROVISION_PROFILE_BASE64` credentials, converts them to `CAPGO_IOS_PROVISIONING_MAP`, and removes the legacy keys. See [Migration from Single Profile](/docs/cli/cloud-build/ios/#migration-from-single-profile) for details.
## Saving iOS Credentials
[Section titled âSaving iOS Credentialsâ](#saving-ios-credentials)
Note
**Donât have iOS certificates yet?** See the [iOS Builds guide](/docs/cli/cloud-build/ios/#how-to-get-ios-certificates-and-provisioning-profiles) for instructions on creating certificates and provisioning profiles.
### Complete Example
[Section titled âComplete Exampleâ](#complete-example)
```bash
npx @capgo/cli build credentials save \
--platform ios \
--certificate ./cert.p12 \
--p12-password "YourP12Password" \
--ios-provisioning-profile "com.example.app=./profile.mobileprovision" \
--apple-key ./AuthKey_ABC1234567.p8 \
--apple-key-id "ABC1234567" \
--apple-issuer-id "00000000-0000-0000-0000-000000000000" \
--apple-team-id "TEAM123456"
```
### iOS Options
[Section titled âiOS Optionsâ](#ios-options)
| Option | Description | Required |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| `--certificate ` | Path to .p12 certificate file | Yes (release) |
| `--p12-password ` | Password for the .p12 certificate | Yes (release) |
| `--ios-provisioning-profile ` | Provisioning profile mapping (`bundleId=path`). Repeatable for multi-target apps. If only one profile and no bundleId prefix, CLI auto-infers from the profile. | Yes (release) |
| `--apple-key ` | Path to App Store Connect API .p8 key | See noteš |
| `--apple-key-id ` | App Store Connect API Key ID | See noteš |
| `--apple-issuer-id ` | App Store Connect API Issuer ID (UUID) | See noteš |
| `--apple-team-id ` | App Store Connect Team ID | Yes |
| `--ios-distribution ` | Distribution mode: `app_store` (default) or `ad_hoc` | No |
| `--output-upload` | Enable a time-limited Capgo download link for the build artifact | No (default: `false`) |
| `--output-retention ` | How long to keep build outputs (e.g. `3600s`) | No (default: `3600s`) |
| `--skip-build-number-bump` | Skip automatic build-number increment | No |
š App Store Connect API Key Requirements
* **`app_store` mode** (default): All three API key options are **required** unless you pass `--output-upload` or `--skip-build-number-bump` (which bypass the need for API-driven submission).
* **`ad_hoc` mode**: These options are **not required** â no App Store submission takes place. See [Ad-Hoc Distribution Mode](/docs/cli/cloud-build/ios/#ad-hoc-distribution-mode) for details.
### What Gets Stored
[Section titled âWhat Gets Storedâ](#what-gets-stored)
When you save iOS credentials, the CLI:
1. Reads the certificate and provisioning profile files
2. Converts them to base64 encoding
3. Saves the credentials to the `.capgo-credentials` folder
4. Stores passwords and IDs as plain text (local files only)
The stored file structure:
```json
{
"ios": {
"BUILD_CERTIFICATE_BASE64": "...",
"CAPGO_IOS_PROVISIONING_MAP": "{\"com.example.app\":{\"profile\":\"...\",\"name\":\"match AppStore com.example.app\"}}",
"APPLE_KEY_CONTENT": "...",
"P12_PASSWORD": "...",
"APPLE_KEY_ID": "ABC1234567",
"APPLE_ISSUER_ID": "...",
"APP_STORE_CONNECT_TEAM_ID": "TEAM123456",
"CAPGO_IOS_DISTRIBUTION": "app_store"
}
}
```
## Saving Android Credentials
[Section titled âSaving Android Credentialsâ](#saving-android-credentials)
Note
**Donât have a keystore yet?** See the [Android Builds guide](/docs/cli/cloud-build/android/#creating-a-keystore) for instructions on creating a keystore and setting up Play Store credentials.
### Complete Example
[Section titled âComplete Exampleâ](#complete-example-1)
```bash
npx @capgo/cli build credentials save \
--platform android \
--keystore ./release.keystore \
--keystore-alias "my-key-alias" \
--keystore-key-password "KeyPassword123" \
--keystore-store-password "StorePassword123" \
--play-config ./play-store-service-account.json
```
### Android Options
[Section titled âAndroid Optionsâ](#android-options)
| Option | Description | Required |
| -------------------------------------- | --------------------------------------- | ---------------- |
| `--keystore ` | Path to .keystore or .jks file | Yes (release) |
| `--keystore-alias ` | Key alias in the keystore | Yes (release) |
| `--keystore-key-password ` | Password for the key alias | Yes (release) |
| `--keystore-store-password ` | Password for the keystore | Yes (release) |
| `--play-config ` | Path to Play Store service account JSON | Yes (submission) |
### What Gets Stored
[Section titled âWhat Gets Storedâ](#what-gets-stored-1)
When you save Android credentials, the CLI:
1. Reads the keystore and service account JSON files
2. Converts them to base64 encoding
3. Saves the credentials to the `.capgo-credentials` folder
4. Stores passwords and alias as plain text (local files only)
The stored file structure:
```json
{
"android": {
"ANDROID_KEYSTORE_FILE": "...",
"PLAY_CONFIG_JSON": "...",
"KEYSTORE_KEY_ALIAS": "my-key-alias",
"KEYSTORE_KEY_PASSWORD": "...",
"KEYSTORE_STORE_PASSWORD": "..."
}
}
}
```
## Using Saved Credentials
[Section titled âUsing Saved Credentialsâ](#using-saved-credentials)
Once youâve saved credentials, theyâre automatically used when you build:
```bash
# Credentials automatically loaded from .capgo-credentials folder
npx @capgo/cli build com.example.app --platform ios
```
You can also override saved credentials using environment variables:
```bash
# Environment variables take precedence over saved credentials
BUILD_CERTIFICATE_BASE64="..." \
P12_PASSWORD="different-password" \
npx @capgo/cli build com.example.app --platform ios
```
**Precedence order:**
1. Environment variables (highest priority)
2. Saved credentials in `.capgo-credentials` folder
3. No credentials (lowest priority)
## Viewing Saved Credentials
[Section titled âViewing Saved Credentialsâ](#viewing-saved-credentials)
List what credentials you have saved:
```bash
npx @capgo/cli build credentials list
```
Example output:
```plaintext
đ Saved Build Credentials:
iOS Credentials:
â Certificate (base64)
â Provisioning Map (JSON)
â Apple Key Content (base64)
â P12 Password: ********
â Apple Key ID: ABC1234567
â Apple Issuer ID: 00000000-0000-0000-0000-000000000000
â Team ID: TEAM123456
Android Credentials:
â Keystore (base64)
â Play Store Config (base64)
â Keystore Alias: my-key-alias
â Key Password: ********
â Store Password: ********
Location: .capgo-credentials/
đ These credentials are stored locally on your machine only.
When building, they are sent to Capgo but NEVER stored there.
They are auto-deleted after build completion.
```
## Security Best Practices
[Section titled âSecurity Best Practicesâ](#security-best-practices)
### Local Storage Security
[Section titled âLocal Storage Securityâ](#local-storage-security)
1. **File Permissions**
```bash
# Ensure credentials folder is not readable by others
chmod 700 .capgo-credentials
chmod 600 .capgo-credentials/*
```
2. **Never Commit Credentials**
```bash
# Add to .gitignore
echo ".capgo-credentials/" >> .gitignore
```
3. **Separate Credentials**
* Use different credentials for local development vs CI/CD
* Rotate credentials regularly
* Donât share credentials between team members
### CI/CD Usage
[Section titled âCI/CD Usageâ](#cicd-usage)
For CI/CD environments, **prefer environment variables** over saved credentials.
#### Complete Environment Variables Reference
[Section titled âComplete Environment Variables Referenceâ](#complete-environment-variables-reference)
The CLI reads the following environment variables for credentials:
**iOS Credentials:**
| Variable | Description | Format | Required |
| ---------------------------- | ---------------------------------------------------- | --------------------------- | ------------- |
| `BUILD_CERTIFICATE_BASE64` | P12/PKCS12 certificate for code signing | Base64 | Yes (release) |
| `CAPGO_IOS_PROVISIONING_MAP` | JSON map of bundle IDs to provisioning profile data | JSON string | Yes (release) |
| `P12_PASSWORD` | Password for the P12 certificate | Plain text | Optional |
| `APPLE_KEY_ID` | App Store Connect API Key ID | String (e.g., âABC1234567â) | See noteš |
| `APPLE_ISSUER_ID` | App Store Connect API Issuer ID | UUID string | See noteš |
| `APPLE_KEY_CONTENT` | App Store Connect API key (.p8 file content) | Base64 | See noteš |
| `APP_STORE_CONNECT_TEAM_ID` | Apple Developer Team ID | String (e.g., âXXXXXXXXXXâ) | Yes |
| `CAPGO_IOS_DISTRIBUTION` | Distribution mode: `app_store` (default) or `ad_hoc` | String | No |
**Android Credentials:**
| Variable | Description | Format | Required |
| ------------------------- | --------------------------------- | ---------- | ---------------- |
| `ANDROID_KEYSTORE_FILE` | Keystore file for signing APK/AAB | Base64 | Yes (release) |
| `KEYSTORE_KEY_ALIAS` | Key alias within the keystore | String | Yes (release) |
| `KEYSTORE_KEY_PASSWORD` | Password for the key alias | Plain text | Yes\* |
| `KEYSTORE_STORE_PASSWORD` | Password for the keystore file | Plain text | Yes\* |
| `PLAY_CONFIG_JSON` | Google Play service account JSON | Base64 | Yes (submission) |
\*If only one password is provided, it will be used for both `KEYSTORE_KEY_PASSWORD` and `KEYSTORE_STORE_PASSWORD`.
#### GitHub Actions Example
[Section titled âGitHub Actions Exampleâ](#github-actions-example)
.github/workflows/build.yml
```yaml
name: Cloud Build
on:
push:
branches: [main]
jobs:
build-ios:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install
- run: npx @capgo/cli build com.example.app --platform ios
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
CAPGO_IOS_PROVISIONING_MAP: ${{ secrets.CAPGO_IOS_PROVISIONING_MAP }}
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
APPLE_KEY_ID: ${{ secrets.APPLE_KEY_ID }}
APPLE_ISSUER_ID: ${{ secrets.APPLE_ISSUER_ID }}
APPLE_KEY_CONTENT: ${{ secrets.APPLE_KEY_CONTENT }}
APP_STORE_CONNECT_TEAM_ID: ${{ secrets.APP_STORE_CONNECT_TEAM_ID }}
build-android:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install
- run: npx @capgo/cli build com.example.app --platform android
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
ANDROID_KEYSTORE_FILE: ${{ secrets.ANDROID_KEYSTORE_FILE }}
KEYSTORE_KEY_ALIAS: ${{ secrets.KEYSTORE_KEY_ALIAS }}
KEYSTORE_KEY_PASSWORD: ${{ secrets.KEYSTORE_KEY_PASSWORD }}
KEYSTORE_STORE_PASSWORD: ${{ secrets.KEYSTORE_STORE_PASSWORD }}
PLAY_CONFIG_JSON: ${{ secrets.PLAY_CONFIG_JSON }}
```
#### Preparing Base64 Values
[Section titled âPreparing Base64 Valuesâ](#preparing-base64-values)
To convert your credential files to base64 for CI/CD secrets:
```bash
# iOS Certificate (.p12)
base64 -i certificate.p12 | tr -d '\n' > certificate_base64.txt
# iOS Provisioning Profiles â use the CLI to generate CAPGO_IOS_PROVISIONING_MAP:
npx @capgo/cli build credentials save --platform ios \
--ios-provisioning-profile "com.example.app=./profile.mobileprovision" \
# ... other options
# Then copy CAPGO_IOS_PROVISIONING_MAP from .capgo-credentials to your CI secrets
# iOS App Store Connect Key (.p8)
base64 -i AuthKey_XXXXXX.p8 | tr -d '\n' > apple_key_base64.txt
# Android Keystore (.keystore or .jks)
base64 -i release.keystore | tr -d '\n' > keystore_base64.txt
# Google Play Service Account JSON
base64 -i play-store-service-account.json | tr -d '\n' > play_config_base64.txt
```
Tip
The `tr -d '\n'` removes newlines to create a single-line base64 string, which is easier to store as a CI/CD secret.
#### Why Environment Variables Are More Secure
[Section titled âWhy Environment Variables Are More Secureâ](#why-environment-variables-are-more-secure)
This approach is more secure because:
* Secrets are managed by your CI/CD platform
* No credential files on runners
* Easy rotation and access control
* Audit trails for secret usage
### Credential Rotation
[Section titled âCredential Rotationâ](#credential-rotation)
Regularly rotate your credentials:
1. **iOS**: Generate new certificates and API keys yearly
2. **Android**: Change keystore passwords annually
3. **After team changes**: Rotate when team members leave
Update saved credentials:
```bash
# Re-run save command with new credentials
npx @capgo/cli build credentials save --platform ios --certificate ./new-cert.p12 ...
```
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### âNo credentials foundâ
[Section titled ââNo credentials foundââ](#no-credentials-found)
If the build says no credentials were found:
1. **Check if credentials are saved**:
```bash
npx @capgo/cli build credentials list
```
2. **Save credentials if missing**:
```bash
npx @capgo/cli build credentials save --platform ios ...
```
3. **Verify credentials folder exists**:
```bash
ls -la .capgo-credentials/
```
### âPermission deniedâ when reading credentials
[Section titled ââPermission deniedâ when reading credentialsâ](#permission-denied-when-reading-credentials)
Fix file permissions:
```bash
chmod 700 .capgo-credentials
chmod 600 .capgo-credentials/*
```
### Credentials not being used
[Section titled âCredentials not being usedâ](#credentials-not-being-used)
Check that the correct platform is specified:
```bash
# Make sure --platform matches saved credentials
npx @capgo/cli build com.example.app --platform ios # Uses ios credentials
npx @capgo/cli build com.example.app --platform android # Uses android credentials
```
### Clear and re-save credentials
[Section titled âClear and re-save credentialsâ](#clear-and-re-save-credentials)
If credentials seem corrupted:
```bash
# Clear all credentials
npx @capgo/cli build credentials clear
# Save again
npx @capgo/cli build credentials save --platform ios ...
```
## Migration from Environment Variables
[Section titled âMigration from Environment Variablesâ](#migration-from-environment-variables)
If youâre currently using environment variables, you can migrate to saved credentials:
1. **Extract your current environment variables**
```bash
echo $BUILD_CERTIFICATE_BASE64 # Verify they exist
```
2. **Decode base64 files back to original files** (if needed)
```bash
echo "$BUILD_CERTIFICATE_BASE64" | base64 -d > cert.p12
echo "$BUILD_PROVISION_PROFILE_BASE64" | base64 -d > profile.mobileprovision
```
3. **Save using the CLI**
```bash
npx @capgo/cli build credentials save \
--platform ios \
--certificate ./cert.p12 \
--ios-provisioning-profile ./profile.mobileprovision \
--p12-password "$P12_PASSWORD" \
--apple-key-id "$APPLE_KEY_ID" \
--apple-issuer-id "$APPLE_ISSUER_ID" \
--apple-team-id "$APP_STORE_CONNECT_TEAM_ID"
```
If you have existing credentials saved in the old format (single `BUILD_PROVISION_PROFILE_BASE64`), run:
```bash
npx @capgo/cli build credentials migrate --platform ios
```
This converts the legacy single-profile to a `CAPGO_IOS_PROVISIONING_MAP` and removes the old `BUILD_PROVISION_PROFILE_BASE64` and `APPLE_PROFILE_NAME` keys.
4. **Test the build**
```bash
npx @capgo/cli build com.example.app --platform ios
```
5. **Remove environment variables** (optional)
```bash
unset BUILD_CERTIFICATE_BASE64 BUILD_PROVISION_PROFILE_BASE64
```
## File Location
[Section titled âFile Locationâ](#file-location)
Credentials are stored in the `.capgo-credentials` folder:
* **macOS/Linux**: `.capgo-credentials/` (in your project root or home directory)
* **Windows**: `.capgo-credentials\` (in your project root or home directory)
The folder is automatically created when you save credentials for the first time.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* [Getting Started](/docs/cli/cloud-build/getting-started/) - Create your first build
* [iOS Builds](/docs/cli/cloud-build/ios/) - iOS-specific build configuration
* [Android Builds](/docs/cli/cloud-build/android/) - Android-specific build configuration
* [Troubleshooting](/docs/cli/cloud-build/troubleshooting/) - Common issues and solutions
## Need Help?
[Section titled âNeed Help?â](#need-help)
* đ [Troubleshooting guide](/docs/cli/cloud-build/troubleshooting/)
* đŹ [Discord community](https://discord.com/invite/VnYRvBfgA6)
* đ§ Email:
# Getting Started
> Create your first native build with Capgo Cloud Build
Get started with Capgo Cloud Build and create your first iOS or Android native build in minutes.
## What Youâll Need
[Section titled âWhat Youâll Needâ](#what-youll-need)
Before you begin, ensure you have:
* A Capacitor app that builds successfully locally
* Node.js 20 or higher installed
* A Capgo account with an active subscription
* Your app already registered in Capgo (run `bunx @capgo/cli@latest app add` if not)
* **Build credentials configured** (certificates, keystores) - see below
## Before Your First Build
[Section titled âBefore Your First Buildâ](#before-your-first-build)
â ď¸ Setup Credentials First
**Required before building:** You must configure your build credentials (certificates for iOS, keystores for Android).
[Setup Credentials â](/docs/cli/cloud-build/credentials/)
## Quick Start
[Section titled âQuick Startâ](#quick-start)
1. **Setup Build Credentials**
Before you can build, you need to save your credentials locally:
**For iOS:**
```bash
bunx @capgo/cli@latest build credentials save \
--platform ios \
--certificate ./cert.p12 \
--p12-password "password" \
--provisioning-profile ./profile.mobileprovision \
--apple-key ./AuthKey.p8 \
--apple-key-id "KEY123" \
--apple-issuer-id "issuer-uuid" \
--apple-team-id "team-id"
```
**For Android:**
```bash
bunx @capgo/cli@latest build credentials save \
--platform android \
--keystore ./release.keystore \
--keystore-alias "my-key" \
--keystore-key-password "key-pass" \
--keystore-store-password "store-pass"
```
See the [full credentials guide](/docs/cli/cloud-build/credentials/) for details.
2. **Verify Local Build**
First, ensure your app builds locally without errors:
```bash
# Build your web assets
bun run build
# Sync with Capacitor
bunx cap sync
# Test local build (optional but recommended)
bunx cap open ios # For iOS
bunx cap open android # For Android
```
3. **Authenticate with Capgo**
Set your Capgo API key (if not already configured):
```bash
bunx @capgo/cli@latest login
```
Or set the environment variable:
```bash
export CAPGO_TOKEN=your_api_key_here
```
4. **Run Your First Build**
Start with an Android debug build (fastest to test):
```bash
bunx @capgo/cli@latest build com.example.app \
--platform android \
--build-mode debug
```
Youâll see real-time logs as your build progresses:
```plaintext
â Creating build job...
â Uploading project (15.2 MB)...
â Build started
đ Build logs:
â Installing dependencies...
â Running Gradle build...
â Signing APK...
â Build succeeded in 3m 42s
```
5. **Check Build Status**
The CLI will automatically poll and display the build status. Once complete, youâll see:
* Build time
* Success/failure status
* App submitted to App Store/Play Store (if credentials configured)
## Understanding the Build Process
[Section titled âUnderstanding the Build Processâ](#understanding-the-build-process)
When you run the build command, hereâs what happens:
```
flowchart LR
A[Your Machine] -->|1. Zip Project| B[Local Temp]
B -->|2. Upload| C[Capgo Cloud]
C -->|3. Build| D[Mac Mini Silicon M4 Build Server]
D -->|4. Logs Stream| A
D -->|5. Cleanup| E[Auto Delete]
```
1. **Local Preparation** - Your project is zipped (excluding `node_modules` and dotfiles)
2. **Upload** - The zip is uploaded to secure cloud storage (Cloudflare R2)
3. **Build Execution** - Your app builds on dedicated infrastructure
4. **Log Streaming** - Real-time logs stream to your terminal via Server-Sent Events
5. **Automatic Cleanup** - Build artifacts are deleted (Android: instant, iOS: 24 hours)
### Build Infrastructure
[Section titled âBuild Infrastructureâ](#build-infrastructure)
Build execution runs on dedicated Mac Mini Silicon M4 machines:
* 10-core M4 CPU (4 performance cores, 6 efficiency cores)
* 10-core GPU
* 16-core Neural Engine
* 16GB of RAM
* macOS Tahoe 26.2
The build image supports Xcode 26.2, Android Studio 2025, and .NET 9/.NET 10 SDK workloads for native build pipelines.
## Your First Production Build
[Section titled âYour First Production Buildâ](#your-first-production-build)
Once youâve verified the process works, create a production build:
### Android
[Section titled âAndroidâ](#android)
```bash
bunx @capgo/cli@latest build com.example.app \
--platform android \
--build-mode release
```
Youâll need to configure signing credentials first. See [Android Build Configuration](/docs/cli/cloud-build/android/).
### iOS
[Section titled âiOSâ](#ios)
```bash
bunx @capgo/cli@latest build com.example.app \
--platform ios \
--build-mode release
```
iOS builds require signing certificates and provisioning profiles. See [iOS Build Configuration](/docs/cli/cloud-build/ios/).
## What Gets Built
[Section titled âWhat Gets Builtâ](#what-gets-built)
Capgo Build only uploads the **minimum files needed** to compile your native app. Your full source code never leaves your machine.
### What Gets Uploaded
[Section titled âWhat Gets Uploadedâ](#what-gets-uploaded)
| Included | Description |
| ----------------------------------- | ---------------------------------------------------------------- |
| `ios/` or `android/` | The native platform folder youâre building |
| `package.json`, `package-lock.json` | Dependency manifest |
| `capacitor.config.*` | Capacitor configuration |
| `resources/` | App icons, splash screens |
| Native plugin code | Only the `ios/` or `android/` subfolder of each Capacitor plugin |
### Whatâs NOT Uploaded
[Section titled âWhatâs NOT Uploadedâ](#whats-not-uploaded)
| Excluded | Why |
| -------------------------------------- | -------------------------------------------------------- |
| `node_modules/` (most of it) | Only native plugin code is included, not JS dependencies |
| `src/` | Your web source code stays local |
| `dist/`, `www/`, `build/` (root level) | Already synced into the native folder via `cap sync` |
| `.git/` | Version control history |
| `.gradle/`, `.idea/`, `.swiftpm/` | Build caches and IDE settings |
| `.env`, secrets | Never uploaded |
Note
Your built web assets (JS, CSS, HTML) **are** uploaded - but as part of the native folder. When you run `bunx cap sync`, your web build is copied into `ios/App/App/public/` or `android/app/src/main/assets/public/`. Thatâs why running `cap sync` before building is required.
### Your Responsibilities
[Section titled âYour Responsibilitiesâ](#your-responsibilities)
Before running `bunx @capgo/cli@latest build`:
1. **Build your web assets** - Run `bun run build` (or your frameworkâs build command)
2. **Sync to native** - Run `bunx cap sync` to copy web assets into the native project
3. **Commit dependencies** - Ensure all native plugins are in `package.json`
### What Capgo Build Handles
[Section titled âWhat Capgo Build Handlesâ](#what-capgo-build-handles)
* Native iOS compilation (Xcode, Fastlane)
* Native Android compilation (Gradle)
* Code signing with your credentials
* App store submission (if configured)
## Build Time & Costs
[Section titled âBuild Time & Costsâ](#build-time--costs)
Build time is measured from start to completion:
* **Android**: Typically 3-5 minutes
* **iOS**: Typically 5-10 minutes
* **Infrastructure**: Mac Mini Silicon M4 machines running macOS Tahoe 26.2
You only pay for actual build time used. No hidden fees.
## Common Use Cases
[Section titled âCommon Use Casesâ](#common-use-cases)
### CI/CD Integration
[Section titled âCI/CD Integrationâ](#cicd-integration)
Add to your GitHub Actions workflow:
```yaml
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Build native app
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
run: |
bun run build
bunx cap sync
bunx @capgo/cli@latest build ${{ secrets.APP_ID }} \
--platform both \
--build-mode release
```
### Local Development
[Section titled âLocal Developmentâ](#local-development)
Test builds locally before committing:
```bash
# Quick debug build for testing
bun run build && bunx cap sync
bunx @capgo/cli@latest build com.example.app \
--platform android \
--build-mode debug
```
### Multi-Platform Builds
[Section titled âMulti-Platform Buildsâ](#multi-platform-builds)
Build for both platforms by running two commands:
```bash
# iOS build
bunx @capgo/cli@latest build com.example.app \
--platform ios \
--build-mode release
# Android build
bunx @capgo/cli@latest build com.example.app \
--platform android \
--build-mode release
```
In CI/CD, you can run these in parallel jobs for faster builds.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
Now that youâve created your first build:
* [Configure iOS builds](/docs/cli/cloud-build/ios/) - Set up certificates and profiles
* [Configure Android builds](/docs/cli/cloud-build/android/) - Set up keystores and Play Store
* [Troubleshooting](/docs/cli/cloud-build/troubleshooting/) - Common issues and solutions
* [CLI Reference](/docs/cli/reference/build/) - Complete command documentation
## Need Help?
[Section titled âNeed Help?â](#need-help)
* Check the [troubleshooting guide](/docs/cli/cloud-build/troubleshooting/)
* Join our [Discord community](https://discord.com/invite/VnYRvBfgA6)
* Email support at
# iOS Builds
> Configure and build iOS apps with Capgo Cloud Build
Build and submit iOS apps to TestFlight and the App Store using Capgoâs dedicated Mac infrastructure.
## What you will learn
[Section titled âWhat you will learnâ](#what-you-will-learn)
* You will learn how to upload your app via Capgo Native build
* You will learn how to configure the certificates for Capgo Native Build
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
* A Capgo account with an active subscription
* Your app already registered in Capgo (run `bunx @capgo/cli@latest app add` if not)
* A Mac computer with Xcode installed (itâs possible to setup the build on a linux/windows machine, but itâs not yet documented)
* Valid Apple Developer account ($99/year) (You must have admin or owner rights on the Apple Developer account)
* Your app must be able to build successfully via Xcode
* A Capacitor app
* A configured icon for the app. Apps without an icon cannot be uploaded to the App Store.
Note
I will use the following app for the tutorial:
## Before you start in Appleâs portals
[Section titled âBefore you start in Appleâs portalsâ](#before-you-start-in-apples-portals)
Before you set up certificates or trigger your first TestFlight upload, make sure the Apple account and team are ready:
* Turn on two-factor authentication for the Apple Account used for enrollment
* Choose the right membership type:
* **Individual / Sole Proprietor**: your legal personal name becomes the seller name on the App Store
* **Organization**: requires a legal entity, a D-U-N-S number, a public company website, a work email on the company domain, and a person with authority to bind the organization to Appleâs agreements
* Use an account that can access both Apple Developer and App Store Connect for certificates, app records, API keys, and TestFlight
* Lock in your final bundle ID early. Changing it later usually means redoing App Store setup
* Plan these App Store Connect items before App Review: support URL, privacy policy URL, age rating, screenshots, export compliance, and App Review contact details
Note
Useful official references:
* [Become a member of the Apple Developer Program](https://developer.apple.com/programs/enroll/)
* [Submit your apps and games](https://developer.apple.com/app-store/submitting/)
* [Platform version information in App Store Connect](https://developer.apple.com/help/app-store-connect/reference/app-information/platform-version-information)
   
Caution
Apple updates its minimum SDK requirement regularly. As of **April 28, 2026**, iPhone and iPad apps uploaded to App Store Connect must be built with the **iOS & iPadOS 26 SDK or later**.
## The first manual build
[Section titled âThe first manual buildâ](#the-first-manual-build)
Before we can start thinking about building the app with Capgo, we should first set it up, and do a first TestFlight build by hand. There are some advantages to doing a manual build first:
* You will setup the distribution certificate on your local machine
* You will create the App Store record if you havenât done it yet
* You will be able to figure out any issues with the build process linked to your app code
Before we can begin, you must have the distribution certificate installed on your local machine. This is quite a bit complex, but I will explain it below.
### Setting up the distribution certificate
[Section titled âSetting up the distribution certificateâ](#setting-up-the-distribution-certificate)
1. Open Xcode
2. Click on `Xcode` -> `Settings...` Alternatively, you can use the shortcut `Cmd + ,`

3. Go to `Accounts` 
4. Find the Apple Account that is added to the Apple Developer Account 
5. Find the team that you will use to deploy the app 
6. Click on the `Manage Certificates...` button 
7. Make sure you can see the distribution certificate in the list 
8. If you do not, you need to create a new certificate
Note
Apple limits the number of distribution certificates you can have to 3. If you have more than 3 certificates, you need to delete one in order to create a new one. I will not cover that in the tutorial.
1. Click on the `+` button and then on `Apple Distribution` 
2. The certificate will be created automatically. You can see it in the list. Look at the previous step to confirm that you see it.
Now that you have the distribution certificate installed, you can begin the build process.
### Manual build to TestFlight
[Section titled âManual build to TestFlightâ](#manual-build-to-testflight)
1. Open the app in Xcode
Run `bunx cap open ios` to open the app in Xcode.
2. Find and click on the `archive` button
In the Xcode toolbar, find and click on the `product` -> `archive` button.

3. Wait for the build to complete
4. Click on the `Distribute App` button

5. Select `TestFlight Internal Only` as the distribution method and click on `Distribute` button

6. Configure the app record
Fill in the following fields:
1. Name: The name of your app - visible in the App Store
2. SKU - the SKU of your app - this is used to identify your app in the App Store
3. The primary language - the primary language of your app
Then, click on the `next` button

7. If the creation of the app record fails, try to close the window and try to archive the app again.
8. Wait for the upload to complete
9. If everything went well, you should see the following screen 
10. Click on the `Done` button
You may instinctively think that all is good now and that you will be able to see your app in TestFlight now, but there are a few more things still to finish:
1. Add yourself to TestFlight
2. Complete export compliance so the build becomes testable
3. Fill in required App Store Connect metadata such as your support URL, privacy policy URL, and age rating
4. Prepare screenshots that match the devices you actually support
5. Add App Review contact details and any test credentials before the production submission
Letâs start with the first one:
### Adding yourself to TestFlight
[Section titled âAdding yourself to TestFlightâ](#adding-yourself-to-testflight)
1. Go to the [App Store Connect](https://appstoreconnect.apple.com/) page 
2. Sign in with your Apple Developer account
3. Select the team that you used when you created the app record. If you are only in one developer account, can skip this step. 
4. Click on the `Apps` button 
5. Find the app you created in the previous step and click on it 
6. Click on the `TestFlight` button 
7. Click on the `Internal Testers plus` button 
8. Create a new group
I like to name the group âinternalâ. You can name it whatever you want.

9. Click on `Invite testers` button 
10. Add yourself to the group
Find yourself in the list and select the checkbox next to your name. (You may need to refresh the page to see yourself) Then, click on the `Add` button.

11. Verify that you are added to the group
Now, you should see yourself in the group.

Congratulations đ You have added yourself to TestFlight. Now, there is just one more thing you need to do before you can configure Capgo Native Build.
### Setting up the compliance information
[Section titled âSetting up the compliance informationâ](#setting-up-the-compliance-information)
You now need to promise Apple that your app doesnât use any non-standard (like a custom algorithm) encryption. If your app does use any non-standard encryption, I suggest reading the [Apple documentation](https://developer.apple.com/help/app-store-connect/manage-app-information/overview-of-export-compliance) on how to handle this. There are two ways to do this:
1. You can do this by hand every time you build your app.
2. You can configure your plist file to automatically set this value to `false`.
Letâs start with the first one:
1. Follow all the steps from the previous section to find the TestFlight section in App Store Connect
2. Click on `Builds -> iOS` 
3. Find the build with missing compliance information and click on `Manage` 
4. Select the option that best describes your app
For me, this is `none`, but it might be different for you. After, click save

5. Your app should now say `ready to test`

As for the second one, here are the steps:
1. Open the `Info.plist` file
2. Add the following key:
```xml
ITSAppUsesNonExemptEncryption
```
3. Save the file
Note
[Here](https://developer.apple.com/documentation/security/complying-with-encryption-export-regulations) is the official Apple documentation on how to inform Apple of your compliance with encryption export regulations.
### Installing the TestFlight app and accepting the invitation
[Section titled âInstalling the TestFlight app and accepting the invitationâ](#installing-the-testflight-app-and-accepting-the-invitation)
Now, you are **ALMOST** ready to test your app in TestFlight. Before, you need to do the following things:
1. Download the [TestFlight app](https://apps.apple.com/us/app/testflight/id899247664) from the App Store on your iOS/iPadOS device
2. Accept the invitation to test your app
I will skip the details of how to install the TestFlight app on your device. If you are not sure how to install an app, Google has some great guides on how to do it.
As for accepting the invitation, you will receive an email from Apple with a link to accept the invitation.
1. Open the email from Apple with the link to accept the invitation
2. Click on `View in TestFlight` button 
3. Click on the `Install` button 
4. Install the app on your device
If you have installed the app previously using Xcode, you may see the following screen. Please click on the `install` button. 
5. Wait for the app to install
6. Click on the `Open` button and click it
[](/native-build-assets/testflight-open-app.mp4)
Congratulations đ You have accepted the invitation to test your app in TestFlight. Now, you can configure Capgo Native Build to build and submit your app to TestFlight.
## Configuring Capgo Native Build
[Section titled âConfiguring Capgo Native Buildâ](#configuring-capgo-native-build)
There are a few things you need to configure in Capgo Native Build to be able to build and submit your app to TestFlight. Here is a list of the things you will pass to the Capgo CLI:
| Parameter | Description |
| ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `--platform` | The platform to build for (`ios`) |
| `--apple-team-id` | Your Apple Developer Team ID (found in [Apple Developer Portal](https://developer.apple.com/account)) |
| `--apple-key` | Path to your App Store Connect API Key file (`.p8` file) |
| `--apple-key-id` | The Key ID of your App Store Connect API Key |
| `--apple-issuer-id` | Your App Store Connect Issuer ID |
| `--certificate` | Path to your distribution certificate (`.p12` file) |
| `--ios-provisioning-profile` | Provisioning profile mapping (`bundleId=path` or just path for single profile) |
Example command:
```bash
bunx @capgo/cli@latest build credentials save \
--platform ios \
--apple-team-id YOUR_TEAM_ID \
--apple-key '/path/to/AuthKey_XXXXX.p8' \
--apple-key-id YOUR_KEY_ID \
--apple-issuer-id YOUR_ISSUER_ID \
--certificate '/path/to/certificate.p12' \
--ios-provisioning-profile '/path/to/profile.mobileprovision'
```
### Team ID
[Section titled âTeam IDâ](#team-id)
Letâs start with the team ID. Finding it is quite easy.
1. Go to [Apple Developer Account](https://developer.apple.com/account/) and scroll down
2. Find the `Team ID`

### Apple key, Apple key ID and Apple issuer ID
[Section titled âApple key, Apple key ID and Apple issuer IDâ](#apple-key-apple-key-id-and-apple-issuer-id)
Now, letâs move on to the Apple key.
1. Go to [App Store Connect user and access page](https://appstoreconnect.apple.com/access/users/)
Note
For me the link sometimes doesnât work. Reload the page if it doesnât work for you.
2. Select the correct team in the dropdown
1. Click on your name in the top right corner
2. Click on the team you want to use 
3. Click on the `Integrations` button 
4. Find the `issuer`
Caution
This **IS TO BE SAVED** - you will need it later
Click on the `copy` button to copy the issuer 
5. Click on the plus button 
6. Set the name of the key and set the access to `App manager` and click on the `Generate` button 
7. Save the key ID
Caution
This **IS TO BE SAVED** - you will need it later

8. Download the key
Caution
This **IS TO BE SAVED** - you will need it later
Danger
**NEVER SHARE THE KEY WITH ANYONE - USE IT ONLY IN THE CAPGO CLI**


Congratulations đ You have created the Apple key, Apple key ID and Apple issuer ID.
### Certificate
[Section titled âCertificateâ](#certificate)
Now, you are ready to export the certificate. As you remember, one of the first steps of this guide was setting up the distribution certificate.
However, Apple in their infinite wisdom, decided that the way you export the certificate is quite different from the way you create them đ Letâs get into setting it up:
1. Open Keychain Access
1. Click `Command + Space` to open the search bar
2. Search for `Keychain Access`
3. Click on the `Keychain Access` app
[](/native-build-assets/open-keychain-macos.mp4)
2. Select the `login` category and click on the `My Certificates` button 
3. Find your certificate in the list
The certificate should be named `Apple Distribution: [Your Name/Company] (your team ID)` 
4. Right-click on the certificate and select `Export` 
5. Save the certificate as a `.p12` file
Caution
This **IS TO BE SAVED** - you will need it later
1. Make sure to select a good name for the certificate file
2. Make sure the file format is set to `Personal Information Exchange (.p12)`
3. Click on the `Save` button

6. When asked for the password, you can either:
* Skip the password (recommended for simplicity): Click `OK` without entering a password
* Set a password: If you prefer to protect your certificate with a password, you can set one here. Password-protected `.p12` files are fully supported by the Capgo CLI - just provide the password using the `--p12-password` option when running configuration command.

7. When asked for the âlogin keychain passwordâ, give the password you use to login to your Mac
Give the password you use to login to your Mac. Then, click on the `Allow` button.

Congratulations đ You have exported the certificate.
### Provisioning profile
[Section titled âProvisioning profileâ](#provisioning-profile)
Now, you are ready to export the provisioning profile. I promise, this is the last thing you will need to get from Apple.
1. Go to [Apple Developer Profiles](https://developer.apple.com/account/resources/profiles/list)
2. Select the correct team in the dropdown
1. Click on your name in the top right corner
2. Click on the team you want to use 
3. Make sure you are on the correct page It should look like this, if it doesnât click on `profiles` in the sidebar

4. Click on the `+` button 
5. Select the profile type Select `App Store Connect` and click on the `Continue` button

6. Select the app you want to build
Find your app in the dropdown and click on the `Continue` button

7. Select the correct distribution certificate
Select the certificate you exported in the previous step and click on the `Continue` button

If you are unsure which certificate to select, come back to Keychain Access and find the certificate you exported. Then look at the expiration date.

8. Name the profile
Give the profile a name and click on the `Generate` button
Tip
The profile name is automatically extracted by the Capgo CLI â you donât need to remember it.

9. Download the profile
Click on the `Download` button to download the profile
Caution
This file **IS TO BE SAVED** - you will need it later

Congratulations đ You have now got everything you need to configure Capgo Native Build.
Caution
Never commit the credentials you just created to your repository. Keep them safe! đ
### Running the configuration command
[Section titled âRunning the configuration commandâ](#running-the-configuration-command)
You have done it! You have now got everything you need to configure Capgo Native Build.
The command you will need to run is:
```bash
bunx @capgo/cli@latest build credentials save \
--platform ios \
--apple-team-id UVTJ336J2D \
--apple-key ./capgo-tutorial/AuthKey_66FGQZB566.p8 \
--apple-key-id 66FGQZB566 \
--apple-issuer-id 0cd4db4a-5598-45b8-9d32-75cdf127d005 \
--certificate ./capgo-tutorial/capgo-build-tutorial-certificate.p12 \
--ios-provisioning-profile ./capgo-tutorial/capgo_native_build_tutorial.mobileprovision
```
Replace placeholder values
Replace the placeholder values above with your actual credentials gathered in the previous steps:
* `--apple-team-id`: Your Apple Team ID
* `--apple-key`: Path to your downloaded `.p8` key file
* `--apple-key-id`: Your Apple Key ID
* `--apple-issuer-id`: Your Apple Issuer ID
* `--certificate`: Path to your exported `.p12` certificate
* `--ios-provisioning-profile`: Path to your downloaded `.mobileprovision` file (bundle ID auto-inferred for single profiles)
If all went well, you will see the following output:

### CI/CD setup (GitHub Actions)
[Section titled âCI/CD setup (GitHub Actions)â](#cicd-setup-github-actions)
If you already completed [Team ID](#team-id), [Apple key, Apple key ID and Apple issuer ID](#apple-key-apple-key-id-and-apple-issuer-id), [Certificate](#certificate), and [Provisioning profile](#provisioning-profile), you already have everything needed for CI/CD. This section only covers how to pass those values as GitHub Actions secrets and environment variables.
#### 1) Convert credential files to single-line base64
[Section titled â1) Convert credential files to single-line base64â](#1-convert-credential-files-to-single-line-base64)
```bash
# Distribution certificate (.p12)
base64 -i ./capgo-tutorial/capgo-build-tutorial-certificate.p12 | tr -d '\n' > certificate_base64.txt
# Provisioning profile (.mobileprovision)
base64 -i ./capgo-tutorial/capgo_native_build_tutorial.mobileprovision | tr -d '\n' > profile_base64.txt
# App Store Connect API key (.p8)
base64 -i ./capgo-tutorial/AuthKey_66FGQZB566.p8 | tr -d '\n' > apple_key_base64.txt
```
Tip
GitHub secrets should be single-line values. `tr -d '\n'` removes line breaks from base64 output.
#### 2) Create repository secrets
[Section titled â2) Create repository secretsâ](#2-create-repository-secrets)
In `GitHub > Repository > Settings > Secrets and variables > Actions`, add:
| Secret name | Value |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| `CAPGO_TOKEN` | Your Capgo API token |
| `APP_STORE_CONNECT_TEAM_ID` | Team ID from [Team ID](#team-id) |
| `APPLE_KEY_ID` | Key ID from [Apple key, Apple key ID and Apple issuer ID](#apple-key-apple-key-id-and-apple-issuer-id) |
| `APPLE_ISSUER_ID` | Issuer ID from [Apple key, Apple key ID and Apple issuer ID](#apple-key-apple-key-id-and-apple-issuer-id) |
| `BUILD_CERTIFICATE_BASE64` | Content of `certificate_base64.txt` |
| `CAPGO_IOS_PROVISIONING_MAP` | Generated by CLI â copy from `.capgo-credentials` file |
| `APPLE_KEY_CONTENT` | Content of `apple_key_base64.txt` |
| `P12_PASSWORD` (optional) | Your `.p12` password if set during export |
#### 3) Use env vars in your GitHub Actions workflow
[Section titled â3) Use env vars in your GitHub Actions workflowâ](#3-use-env-vars-in-your-github-actions-workflow)
.github/workflows/ios-build.yml
```yaml
name: iOS Cloud Build
on:
workflow_dispatch:
push:
branches: [main]
jobs:
ios-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Request iOS build with Capgo
run: bunx @capgo/cli@latest build request --platform ios
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
APP_STORE_CONNECT_TEAM_ID: ${{ secrets.APP_STORE_CONNECT_TEAM_ID }}
APPLE_KEY_ID: ${{ secrets.APPLE_KEY_ID }}
APPLE_ISSUER_ID: ${{ secrets.APPLE_ISSUER_ID }}
BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
CAPGO_IOS_PROVISIONING_MAP: ${{ secrets.CAPGO_IOS_PROVISIONING_MAP }}
APPLE_KEY_CONTENT: ${{ secrets.APPLE_KEY_CONTENT }}
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
```
Tip
With this setup, CI sends credentials through environment variables only. You do not need to commit signing files or upload them as workflow artifacts.
### Running the build
[Section titled âRunning the buildâ](#running-the-build)
Now, you are ready to run your first build.
Run the following command to build your app:
```bash
bunx @capgo/cli@latest build request --platform ios
```
Congratulations đ At this point, you have successfully built your app and it is ready to be submitted to the App Store.
## Ad-Hoc Distribution Mode
[Section titled âAd-Hoc Distribution Modeâ](#ad-hoc-distribution-mode)
By default, Capgo builds iOS apps for App Store distribution (TestFlight + App Store). If you need ad-hoc builds instead (for internal testing or CI artifact collection), you can use the `--ios-distribution` flag.
Note
Ad-hoc distribution is **not** the same as Enterprise (In-House) distribution. Enterprise distribution requires a separate Apple Developer Enterprise account and uses different provisioning profiles. Capgo currently supports `app_store` and `ad_hoc` modes only.
### When to use ad-hoc mode
[Section titled âWhen to use ad-hoc modeâ](#when-to-use-ad-hoc-mode)
* You want to distribute IPAs directly to registered devices (no TestFlight)
* You donât have or donât want to use an App Store Connect API key
* You want to collect build artifacts via `--output-upload` without submitting to the App Store
### Requirements
[Section titled âRequirementsâ](#requirements)
Ad-hoc builds have **fewer requirements** than App Store builds:
| Credential | Required? |
| ------------------------------------------------ | --------- |
| Distribution certificate (`.p12`) | Yes |
| Ad-hoc provisioning profile (`.mobileprovision`) | Yes |
| Team ID (`--apple-team-id`) | Yes |
| App Store Connect API key (`.p8`) | **No** |
| Apple Key ID / Issuer ID | **No** |
Note
In `ad_hoc` mode, `--apple-key`, `--apple-key-id`, and `--apple-issuer-id` are not supported and are ignored. This is why the two App Store Connect rows above do not show ad-hoc CLI flags; these options apply to `app_store` mode only.
Caution
Without an App Store Connect API key, build number auto-increment uses a timestamp-based fallback. To suppress the warning, pass `--skip-build-number-bump`.
### Creating an ad-hoc provisioning profile
[Section titled âCreating an ad-hoc provisioning profileâ](#creating-an-ad-hoc-provisioning-profile)
Follow the same steps as [Provisioning profile](#provisioning-profile), but in step 5, select **Ad Hoc** instead of **App Store**:
1. Go to [Apple Developer Profiles](https://developer.apple.com/account/resources/profiles/list)
2. Click the `+` button
3. Select **Ad Hoc** and click Continue
4. Select your app and distribution certificate
5. Select the devices you want to register
6. Name and download the profile
### Saving ad-hoc credentials
[Section titled âSaving ad-hoc credentialsâ](#saving-ad-hoc-credentials)
```bash
bunx @capgo/cli@latest build credentials save \
--platform ios \
--ios-distribution ad_hoc \
--apple-team-id YOUR_TEAM_ID \
--certificate './certificate.p12' \
--ios-provisioning-profile './adhoc_profile.mobileprovision'
```
No `--apple-key`, `--apple-key-id`, or `--apple-issuer-id` needed.
### Running an ad-hoc build
[Section titled âRunning an ad-hoc buildâ](#running-an-ad-hoc-build)
```bash
bunx @capgo/cli@latest build request \
--platform ios \
--ios-distribution ad_hoc
```
To collect the IPA as a build artifact, add `--output-upload`:
```bash
bunx @capgo/cli@latest build request \
--platform ios \
--ios-distribution ad_hoc \
--output-upload
```
### CI/CD with ad-hoc builds
[Section titled âCI/CD with ad-hoc buildsâ](#cicd-with-ad-hoc-builds)
For GitHub Actions, you need fewer secrets than App Store builds:
.github/workflows/ios-adhoc-build.yml
```yaml
name: iOS Ad-Hoc Build
on:
workflow_dispatch:
jobs:
ios-adhoc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Request iOS ad-hoc build
run: bunx @capgo/cli@latest build request --platform ios --ios-distribution ad_hoc --output-upload
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
APP_STORE_CONNECT_TEAM_ID: ${{ secrets.APP_STORE_CONNECT_TEAM_ID }}
BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
CAPGO_IOS_PROVISIONING_MAP: ${{ secrets.CAPGO_IOS_PROVISIONING_MAP_ADHOC }}
CAPGO_IOS_DISTRIBUTION: ad_hoc
```
Tip
Notice that `APPLE_KEY_ID`, `APPLE_ISSUER_ID`, and `APPLE_KEY_CONTENT` are not needed for ad-hoc builds.
## Apps with Extensions (Multi-Target Signing)
[Section titled âApps with Extensions (Multi-Target Signing)â](#apps-with-extensions-multi-target-signing)
If your app includes extensions (share extensions, widgets, notification service extensions, etc.), each extension target needs its own provisioning profile. Capgo supports this via the repeatable `--ios-provisioning-profile` flag.
### Example: App + Share Extension
[Section titled âExample: App + Share Extensionâ](#example-app--share-extension)
```bash
bunx @capgo/cli@latest build credentials save \
--platform ios \
--apple-team-id YOUR_TEAM_ID \
--apple-key '/path/to/AuthKey_XXXXX.p8' \
--apple-key-id YOUR_KEY_ID \
--apple-issuer-id YOUR_ISSUER_ID \
--certificate '/path/to/certificate.p12' \
--ios-provisioning-profile "com.example.app=./app_profile.mobileprovision" \
--ios-provisioning-profile "com.example.app.share-extension=./share_ext_profile.mobileprovision"
```
Each `--ios-provisioning-profile` flag maps a bundle ID to its provisioning profile file. The CLI:
1. Reads each mobileprovision file
2. Auto-extracts the profile name from the embedded plist
3. Base64-encodes the file
4. Stores everything as a single `CAPGO_IOS_PROVISIONING_MAP` credential
Tip
You need one distribution certificate for all targets â only provisioning profiles differ per target.
### Migration from Single Profile
[Section titled âMigration from Single Profileâ](#migration-from-single-profile)
If you previously used `BUILD_PROVISION_PROFILE_BASE64` (single profile), run:
```bash
bunx @capgo/cli build credentials migrate --platform ios
```
This converts your existing single-profile credentials to the new `CAPGO_IOS_PROVISIONING_MAP` format and removes the legacy keys (`BUILD_PROVISION_PROFILE_BASE64`, `APPLE_PROFILE_NAME`).
After migration, add extension profiles with the `update` command (additive merge):
```bash
bunx @capgo/cli build credentials update \
--platform ios \
--ios-provisioning-profile "com.example.app.share-extension=./share_ext_profile.mobileprovision"
```
Tip
Use `update` (not `save`) to add profiles to existing credentials. The `update` command merges new profiles with existing ones. Use `save` only when setting up all credentials from scratch.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Provisioning profile doesnât include the XYZ capability.
[Section titled âProvisioning profile doesnât include the XYZ capability.â](#provisioning-profile-doesnt-include-the-xyz-capability)
Sometimes, you might see the following error:
```plaintext
Provisioning profile "YOUR_PROVISIONING_PROFILE_NAME" doesn't include the XYZ capability. (in target 'App' from project 'App')"
```
This happens because you have enabled a new capability after the provisioning profile was created. The old provisioning profile does not include the new capability yet.
To fix this, you need to regenerate the provisioning profile.
1. Open [Apple Developer Portal](https://developer.apple.com/account/)
2. Select the correct team in the dropdown 
3. Click on the `Profiles` button 
4. Find the provisioning profile you want to regenerate 
5. Click on the `Edit` button 
6. Click on the `Save` button 
7. Click on the `Download` button 
8. [Re-run the Capgo Native Build setup command](/docs/cli/cloud-build/ios/#running-the-configuration-command) with the newly downloaded profile.
This should fix the issue.
### Other issues
[Section titled âOther issuesâ](#other-issues)
If for whatever reason you are having issues either with Capgo Native Build, configuring the credentials or building the app, please donât hesitate to reach via our [support](https://support.capgo.app/).
# Troubleshooting
> Common issues and solutions for Capgo Cloud Build
Solutions to common issues when building native apps with Capgo Cloud Build.
## Build Failures
[Section titled âBuild Failuresâ](#build-failures)
### âUpload failedâ or âConnection timeoutâ
[Section titled ââUpload failedâ or âConnection timeoutââ](#upload-failed-or-connection-timeout)
**Symptoms:**
* Build fails during project upload
* Timeout errors after 60 seconds
**Solutions:**
1. **Check your internet connection**
```bash
# Test connection to Capgo
curl -I https://api.capgo.app
```
2. **Reduce project size**
* Ensure `node_modules/` is not being uploaded (should be auto-excluded)
* Check for large files in your project:
```bash
find . -type f -size +10M
```
3. **Check upload URL expiration**
* Upload URLs expire after 1 hour
* If you get an expired URL error, re-run the build command
Tip
Large projects (>200MB) may hit timeout limits. Contact support for enterprise options.
### âBuild timeout after 10 minutesâ
[Section titled ââBuild timeout after 10 minutesââ](#build-timeout-after-10-minutes)
**Symptoms:**
* Build exceeds maximum allowed time
* Status shows `timeout`
**Solutions:**
1. **Optimize dependencies**
* Remove unused npm packages
* Use `npm prune --production` before building
2. **Check for network issues in build**
* Some dependencies may download large files during build
* Consider pre-caching with a lock file
3. **Review native dependencies**
```bash
# iOS - check Podfile for heavy dependencies
cat ios/App/Podfile
# Android - check build.gradle
cat android/app/build.gradle
```
4. **Contact support**
* If your app legitimately needs more time
* We can adjust limits for specific use cases
## Authentication Issues
[Section titled âAuthentication Issuesâ](#authentication-issues)
### âAPI key invalidâ or âUnauthorizedâ
[Section titled ââAPI key invalidâ or âUnauthorizedââ](#api-key-invalid-or-unauthorized)
**Symptoms:**
* Build fails immediately with authentication error
* 401 or 403 errors
**Solutions:**
1. **Verify API key is correct**
```bash
# Test with a simple command
npx @capgo/cli@latest app list
```
2. **Check API key permissions**
* Key must have `write` or `all` permissions
* Check in Capgo dashboard under API Keys
3. **Ensure API key is being read**
```bash
# Check environment variable
echo $CAPGO_TOKEN
# Or verify local .capgo file
cat .capgo
```
4. **Re-authenticate**
```bash
npx @capgo/cli@latest login
```
### âApp not foundâ or âNo permission for this appâ
[Section titled ââApp not foundâ or âNo permission for this appââ](#app-not-found-or-no-permission-for-this-app)
**Symptoms:**
* Authentication works but app-specific error
**Solutions:**
1. **Verify app is registered**
```bash
npx @capgo/cli@latest app list
```
2. **Check app ID matches**
* Verify `capacitor.config.json` appId
* Ensure command uses correct app ID
3. **Verify organization access**
* Check youâre in the correct organization
* API key must have access to the appâs organization
## iOS Build Issues
[Section titled âiOS Build Issuesâ](#ios-build-issues)
### âCode signing failedâ
[Section titled ââCode signing failedââ](#code-signing-failed)
**Symptoms:**
* Build fails during code signing phase
* Xcode errors about certificates or profiles
**Solutions:**
1. **Verify certificate type matches build type**
* Development builds need Development certificates
* App Store builds need Distribution certificates
2. **Check certificate and profile match**
```bash
# Decode and inspect your certificate
echo $BUILD_CERTIFICATE_BASE64 | base64 -d > cert.p12
openssl pkcs12 -in cert.p12 -nokeys -passin pass:$P12_PASSWORD | openssl x509 -noout -subject
```
3. **Ensure provisioning profile is valid**
* Check expiration date
* Verify it includes your App ID
* Confirm it includes the certificate
4. **Regenerate credentials**
* Delete old certificate/profile
* Create new ones in Apple Developer portal
* Re-encode and update environment variables
### âProvisioning profile doesnât include signing certificateâ
[Section titled ââProvisioning profile doesnât include signing certificateââ](#provisioning-profile-doesnt-include-signing-certificate)
**Symptoms:**
* Xcode canât find certificate in profile
**Solutions:**
1. **Download latest profile from Apple**
* Go to Apple Developer â Certificates, IDs & Profiles
* Download provisioning profile
* Ensure it includes your certificate
2. **Verify certificate is in profile**
```bash
# Extract profile
echo $BUILD_PROVISION_PROFILE_BASE64 | base64 -d > profile.mobileprovision
# View profile contents
security cms -D -i profile.mobileprovision
```
3. **Recreate profile with correct certificate**
* In Apple Developer portal, edit profile
* Ensure your distribution certificate is selected
* Download and re-encode
### âApp Store Connect authentication failedâ
[Section titled ââApp Store Connect authentication failedââ](#app-store-connect-authentication-failed)
**Symptoms:**
* Upload to TestFlight fails
* API key errors
**Solutions:**
1. **Verify API key credentials**
* Check APPLE\_KEY\_ID (should be 10 characters)
* Check APPLE\_ISSUER\_ID (should be UUID format)
* Verify APPLE\_KEY\_CONTENT is correctly base64-encoded
2. **Test API key locally**
```bash
# Decode key
echo $APPLE_KEY_CONTENT | base64 -d > AuthKey.p8
# Test with fastlane (if installed)
fastlane pilot list
```
3. **Check API key permissions**
* Key needs âDeveloperâ role or higher
* Verify in App Store Connect â Users and Access â Keys
4. **Ensure key is not revoked**
* Check in App Store Connect
* Generate new key if needed
### âPod install failedâ
[Section titled ââPod install failedââ](#pod-install-failed)
**Symptoms:**
* Build fails during CocoaPods installation
* Podfile errors
**Solutions:**
1. **Verify Podfile.lock is committed**
```bash
git status ios/App/Podfile.lock
```
2. **Test pod install locally**
```bash
cd ios/App
pod install
```
3. **Check for incompatible pods**
* Review Podfile for version conflicts
* Ensure all pods support your iOS deployment target
4. **Clear pod cache**
```bash
cd ios/App
rm -rf Pods
rm Podfile.lock
pod install
# Then commit new Podfile.lock
```
## Android Build Issues
[Section titled âAndroid Build Issuesâ](#android-build-issues)
### âKeystore password incorrectâ
[Section titled ââKeystore password incorrectââ](#keystore-password-incorrect)
**Symptoms:**
* Build fails during signing
* Gradle errors about keystore
**Solutions:**
1. **Verify keystore password**
```bash
# Test keystore locally
keytool -list -keystore my-release-key.keystore
# Enter password when prompted
```
2. **Check environment variables**
```bash
# Ensure no extra spaces or special characters
echo "$KEYSTORE_STORE_PASSWORD" | cat -A
echo "$KEYSTORE_KEY_PASSWORD" | cat -A
```
3. **Verify base64 encoding**
```bash
# Decode and test
echo $ANDROID_KEYSTORE_FILE | base64 -d > test.keystore
keytool -list -keystore test.keystore
```
### âKey alias not foundâ
[Section titled ââKey alias not foundââ](#key-alias-not-found)
**Symptoms:**
* Signing fails with alias error
**Solutions:**
1. **List keystore aliases**
```bash
keytool -list -keystore my-release-key.keystore
```
2. **Verify alias matches exactly**
* Alias is case-sensitive
* Check for typos in KEYSTORE\_KEY\_ALIAS
3. **Use correct alias from keystore**
```bash
# Update environment variable to match
export KEYSTORE_KEY_ALIAS="the-exact-alias-name"
```
### âGradle build failedâ
[Section titled ââGradle build failedââ](#gradle-build-failed)
**Symptoms:**
* Generic Gradle errors
* Compilation or dependency issues
**Solutions:**
1. **Test build locally first**
```bash
cd android
./gradlew clean
./gradlew assembleRelease
```
2. **Check for missing dependencies**
* Review build.gradle files
* Ensure all plugins are listed in dependencies
3. **Verify Gradle version compatibility**
```bash
# Check gradle version
cat android/gradle/wrapper/gradle-wrapper.properties
```
4. **Clear Gradle cache**
```bash
cd android
./gradlew clean
rm -rf .gradle build
```
### âPlay Store upload failedâ
[Section titled ââPlay Store upload failedââ](#play-store-upload-failed)
**Symptoms:**
* Build succeeds but upload fails
* Service account errors
**Solutions:**
1. **Verify service account JSON**
```bash
# Decode and check format
echo $PLAY_CONFIG_JSON | base64 -d | jq .
```
2. **Check service account permissions**
* Go to Play Console â Setup â API Access
* Ensure service account has access to your app
* Grant âRelease to testing tracksâ permission
3. **Verify app is set up in Play Console**
* App must be created in Play Console first
* At least one APK must be uploaded manually initially
4. **Check API is enabled**
* Google Play Developer API must be enabled
* Check in Google Cloud Console
## General Issues
[Section titled âGeneral Issuesâ](#general-issues)
### âJob not foundâ or âBuild status unavailableâ
[Section titled ââJob not foundâ or âBuild status unavailableââ](#job-not-found-or-build-status-unavailable)
**Symptoms:**
* Cannot check build status
* Job ID errors
**Solutions:**
1. **Wait a moment and retry**
* Build jobs may take a few seconds to initialize
2. **Check job ID is correct**
* Verify the job ID from the initial build response
3. **Check build hasnât expired**
* Build data is available for 24 hours
### âProject sync failedâ
[Section titled ââProject sync failedââ](#project-sync-failed)
**Symptoms:**
* Build fails before compilation starts
* Missing files errors
**Solutions:**
1. **Run Capacitor sync locally**
```bash
npx cap sync
```
2. **Ensure all native files are committed**
```bash
git status ios/ android/
```
3. **Check for gitignored native files**
* Review .gitignore
* Ensure important config files arenât ignored
### âBuild succeeded but I donât see outputâ
[Section titled ââBuild succeeded but I donât see outputââ](#build-succeeded-but-i-dont-see-output)
**Symptoms:**
* Build shows success but no download link
**Solutions:**
1. **Check build configuration**
* Artifact storage may not be configured
* Contact support if artifact access is unavailable for your build
2. **For iOS TestFlight submission**
* Check App Store Connect
* Processing may take 5-30 minutes after upload
3. **For Android Play Store**
* Check Play Console â Testing â Internal testing
* Processing may take a few minutes
## CI/CD Specific Issues
[Section titled âCI/CD Specific Issuesâ](#cicd-specific-issues)
### GitHub Actions: âCommand not foundâ
[Section titled âGitHub Actions: âCommand not foundââ](#github-actions-command-not-found)
**Symptoms:**
* `npx @capgo/cli` fails in CI
**Solutions:**
1. **Ensure Node.js is installed**
```yaml
- uses: actions/setup-node@v6
with:
node-version: '24'
```
2. **Install CLI explicitly**
```yaml
- run: npm install -g @capgo/cli
```
### GitHub Actions: âSecrets not foundâ
[Section titled âGitHub Actions: âSecrets not foundââ](#github-actions-secrets-not-found)
**Symptoms:**
* Environment variables empty in build
**Solutions:**
1. **Verify secrets are set**
* Go to repo Settings â Secrets and variables â Actions
* Add all required secrets
2. **Use correct syntax**
```yaml
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
```
3. **Check secret names match**
* Names are case-sensitive
* No typos in secret references
## Getting More Help
[Section titled âGetting More Helpâ](#getting-more-help)
### Enable Verbose Logging
[Section titled âEnable Verbose Loggingâ](#enable-verbose-logging)
```bash
# Add debug flag (when available)
npx @capgo/cli@latest build com.example.app --verbose
```
### Collect Build Information
[Section titled âCollect Build Informationâ](#collect-build-information)
When contacting support, include:
1. **Build command used**
```bash
npx @capgo/cli@latest build com.example.app --platform ios
```
2. **Error message** (full output)
3. **Job ID** (from build output)
4. **Build logs** (copy full terminal output)
5. **Environment info**
```bash
node --version
npm --version
npx @capgo/cli --version
```
### Contact Support
[Section titled âContact Supportâ](#contact-support)
* **Discord**: [Join our community](https://discord.com/invite/VnYRvBfgA6)
* **Email**:
* **Documentation**: [Capgo Docs](/docs/)
### Known Limitations
[Section titled âKnown Limitationsâ](#known-limitations)
Current limitations:
* Maximum build time: 10 minutes
* Maximum upload size: \~500MB
* iOS builds require 24-hour Mac leases, build on Mac will enqueue to ensure optimal usage
* Build artifact download availability depends on build destination and artifact storage configuration
These limitations may be adjusted based on feedback.
## Additional Resources
[Section titled âAdditional Resourcesâ](#additional-resources)
* [Getting Started](/docs/cli/cloud-build/getting-started/) - Initial setup guide
* [iOS Builds](/docs/cli/cloud-build/ios/) - iOS-specific configuration
* [Android Builds](/docs/cli/cloud-build/android/) - Android-specific configuration
* [CLI Reference](/docs/cli/reference/build/) - Complete command documentation
# Commands
> Capgo CLI documentation, how to use it and what is used for
### Usage
[Section titled âUsageâ](#usage)
All command should be run in your app folder with capacitor project ignited properly.
[Capacitor Cross-platform native runtime for web apps ](https://capacitorjs.com/docs/getting-started/)
### **Init**
[Section titled âInitâ](#init)
`npx @capgo/cli@latest init [apikey]`
This method is here to onboard you step by step.
It will add your app to Capgo. It will add the code to your app to validate the update. Likewise, it will build your app. Furthermore, it will upload your app to Capgo. And it will help you to check if the update works.
### **Login**
[Section titled âLoginâ](#login)
`npx @capgo/cli login [apikey]`
This method is here to remember the `apikey` for you.
Note
use `--apikey=********` in any command to override it
**Optionally you can give:**
`--local` This will store your **apikey** in the local repo and git ignore it.
## **Doctor**
[Section titled âDoctorâ](#doctor)
`npx @capgo/cli doctor`
Command to check if you are up-to-date with Capgo packages.
This command will also be useful for bug report.
## App
[Section titled âAppâ](#app)
### **Add**
[Section titled âAddâ](#add)
`npx @capgo/cli app add [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
> đĄ All option will be guessed in your config if not provided.
Optionally, you can give:
* `--icon [/path/to/my/icon]` to have a custom icon display in Capgo web app.
* `--name [test]` to have a custom name in the list.
* `--apikey [key]` API key to link to your account.
* `--retention [retention]` retention period of app bundle in days, 0 by default = infinite.
Example of `capacitor.config.json` for appId and AppName, the icon is guess in the resources folder
```json
{
"appId": "ee.forgr.capacitor_go",
"appName": "Capgo",
"webDir": "dist"
}
```
### **Set**
[Section titled âSetâ](#set)
`npx @capgo/cli app set [appId]`
`[appId]` is your app ID, the format is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--icon [/path/to/my/icon]` to have a custom icon display in Capgo web app.
* `--name [test]` to have a custom name in the list.
* `--retention [retention]` retention period of app bundle in days, 0 by default = infinite.
* `--apikey [key]` API key to link to your account.
### **List**
[Section titled âListâ](#list)
`npx @capgo/cli app list [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
### **Delete**
[Section titled âDeleteâ](#delete)
`npx @capgo/cli app delete [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
* `--bundle` with the version number will only delete this version.
### Debug
[Section titled âDebugâ](#debug)
`npx @capgo/cli app debug [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
* `--device` with the specific device you want to debug
### Setting
[Section titled âSettingâ](#setting)
`npx @capgo/cli app setting [path]`
Edit the Capacitor config.
`[path]` - path of the setting that you would like to change. For example, to change the `appId`, provide `appId`. If you wish to disable auto update in the `capacitor-updater` provide `plugins.CapacitorUpdater.autoUpdate`
You MUST provide either `--string` or `--bool`!
Options:
* `--string ` - sets the setting to a string
* `--bool ` - sets the setting to a boolean
## Bundle
[Section titled âBundleâ](#bundle)
### Upload
[Section titled âUploadâ](#upload)
`npx @capgo/cli bundle upload [appId]`
`[appId]` is your app ID, the format is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey ` API key to link to your account.
* `--path ` Path of the folder to upload.
* `--channel ` Channel to link to.
* `--external ` Link to external URL instead of uploading to Capgo Cloud.
* `--iv-session-key ` Set the IV and session key for bundle URL external.
* `--s3-endpoint ` URL of S3 endpoint. Does not work with delta uploads or the external option.
* `--s3-region ` Region for your S3 bucket.
* `--s3-apikey ` API key for your S3 endpoint.
* `--s3-apisecret ` API secret for your S3 endpoint.
* `--s3-bucket-name ` Name for your AWS S3 bucket.
* `--s3-port ` Port for your S3 endpoint.
* `--no-s3-ssl` Disable SSL for S3 upload.
* `--key ` Custom path for public signing key (v1 system).
* `--key-data ` Public signing key (v1 system).
* `--key-v2 ` Custom path for private signing key (v2 system).
* `--key-data-v2 ` Private signing key (v2 system).
* `--bundle-url` Prints bundle URL into stdout.
* `--no-key` Ignore signing key and send clear update.
* `--no-code-check` Ignore checking if notifyAppReady() is called in source code and index present in root folder.
* `--display-iv-session` Show in the console the IV and session key used to encrypt the update.
* `--bundle ` Bundle version number of the bundle to upload.
* `--min-update-version ` Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel.
* `--auto-min-update-version` Set the min update version based on native packages.
* `--ignore-metadata-check` Ignores the metadata (node\_modules) check when uploading.
* `--ignore-checksum-check` Ignores the checksum check when uploading.
* `--timeout ` Timeout for the upload process in seconds.
* `--delta` Uploads Delta (manifest) files alongside the full bundle.
* `--delta-only` Uploads only Delta (manifest) updates, skipping the full bundle.
* `--no-delta` Disables Delta (manifest) uploads (useful if `directUpdate` is enabled but you want a full bundle).
* `--tus` Upload the bundle using tus protocol.
* `--multipart` Uses multipart protocol to upload data to S3, Deprecated, use TUS instead.
* `--encrypted-checksum ` An encrypted checksum (signature). Used only when uploading an external bundle.
* `--package-json ` A path to package.json. Useful for monorepos.
* `--auto-set-bundle` Set the bundle in capacitor.config.json.
* `--node-modules ` A list of path to node\_modules. Useful for monorepos (comma separated ex: ../../node\_modules,./node\_modules)
> âď¸ External option helps to unlock 2 cases: corporate with privacy concern, donât send the code to a third part and app bigger than 200 MB. With this setting, Capgo store only the link to the zip and sends the link to all apps.
> đ Capgo cloud never looks at what is in the link (for external option), or in the code when stored.
> đ You can add a second layer of security by using encryption, then Capgo will not be able to look or modify anything, it becomes âtrustlessâ.
Example of `package.json` for version
```json
{
"version": "1.0.2"
}
```
> â Version should be greater than â0.0.0â.
> đĄ Donât forget to update the version number each time you send one, version number cannot be overridden, or reused after deletion for security reason.
### **List**
[Section titled âListâ](#list-1)
`npx @capgo/cli bundle list [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
### **Delete**
[Section titled âDeleteâ](#delete-1)
`npx @capgo/cli bundle delete [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
* `--bundle` with the version number will only delete this version.
### Cleanup
[Section titled âCleanupâ](#cleanup)
in a SemVer range for a major version to Cloud
`npx @capgo/cli bundle cleanup [appId] --bundle=[majorVersion] --keep=[numberToKeep]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
* `--bundle [majorVersion]` a version you wish to remove previous packages for, it will keep the last one + `numberToKeep`.
* `--keep [numberToKeep]` the number of packages you wish to keep (default 4).
For example: If you have 10 versions from 10.0.1 to 10.0.11, and you use `npx @capgo/cli cleanup [appId] --bundle=10.0.0` it will remove 10.0.1 to 10.0.6. 10.0.7 until 10.0.11 will be kept.
If you have 20 versions in total, and you donât provide a bundle number like this: `npx @capgo/cli cleanup [appId] --keep=2` It will remove 18 versions, and keep the last 2.
> This command will ask for confirmation, it shows a table of what it will be keeping and removing.
Note
This command will ignore bundles which are currently in use in any channel.
### **Encrypt**
[Section titled âEncryptâ](#encrypt)
> **Warning**: This command is deprecated and will be removed in the next major release. Please use the new encryption system. `npx @capgo/cli bundle encrypt [path/to/zip]`
This command is used when you use external source to store your code or for test purpose.
Optionally, you can give:
`--key [/path/to/my/private_key]` the path of your private key. `--key-data [privateKey]` the private key data, if you want to use inline. The command will print your `ivSessionKey`y and generate an encrypted zip, to use it with the upload command or decryt command.
### **Encrypt V2**
[Section titled âEncrypt V2â](#encrypt-v2)
`npx @capgo/cli bundle encrypt [path/to/zip] [checksum]`
This command is used when you use external source to store your code or for test purpose. The checksum is the sha256 of the bundle (generated by âkey-v2), it is used to verify the integrity of the file after decryption. It will be enncrypted with the private key and sent along with the bundle. In encryption v2 the checksum is upgraded to become a âsignatureâ of the bundle.
Optionally, you can give:
`--key [/path/to/my/private_key]` the path of your private key. `--key-data [privateKey]` the private key data, if you want to use inline. `--json` to output info as json. The command will print your `ivSessionKey`y and generate an encrypted zip, to use it with the upload command or decryt command.
### **Decrypt**
[Section titled âDecryptâ](#decrypt)
`npx @capgo/cli bundle decrypt [path/to/zip] [ivSessionKey]`
Optionally, you can give:
`--key [/path/to/my/private_key]` the path of your private key.
`--key-data [privateKey]` the private key data, if you want to use inline. This command is mainly used for test purpose, it will decrypt the zip and print the base64 decrypted session key in the console.
### **Decrypt V2**
[Section titled âDecrypt V2â](#decrypt-v2)
`npx @capgo/cli bundle decryptV2 [path/to/zip] [ivSessionKey]`
Optionally, you can give:
`--key [/path/to/my/private_key]` the path of your private key. `--key-data [privateKey]` the private key data, if you want to use inline. This command is mainly used for test purpose, it will decrypt the zip and print the base64 decrypted session key in the console. `--checksum [checksum]` the checksum of the file, it will verify the checksum after decryption.
### **Zip**
[Section titled âZipâ](#zip)
`npx @capgo/cli bundle zip [appId]`
`[appId]` is your app ID, the format is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--path [/path/to/my/bundle]` to upload a specific folder.
* `--bundle [1.0.0]` to set the bundle version number of the filename.
* `--name [myapp]` to override the filename.
* `--json` to output info as json.
* `--no-code-check` to ignore the code check and send the bundle anyway.
* `--key-v2` to use the new encryption system. This is required as new encryption system use better checksums to verify the integrity of the file.
### **Compatibility**
[Section titled âCompatibilityâ](#compatibility)
`npx @capgo/cli bundle compatibility [appId] -c [channelId]`
`[appId]` is your app ID, the format is explained [here](https://capacitorjs.com/docs/cli/commands/init/). `[channelId]` the name of your new channel.
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
* `--text` use text instead of emojis in the table
* `--channel [channel]` the channel to check the compatibility with.
* `--package-json ` A path to package.json. Useful for monorepos
* `--node-modules ` A list of path to node\_modules. Useful for monorepos (comma separated ex: ../../node\_modules,./node\_modules)
## Channel
[Section titled âChannelâ](#channel)
### **Add**
[Section titled âAddâ](#add-1)
`npx @capgo/cli channel add [channelId] [appId]`
`[channelId]` the name of your new channel. `[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
### **Delete**
[Section titled âDeleteâ](#delete-2)
`npx @capgo/cli channel delete [channelId] [appId]`
`[channelId]` the name of your channel you want to delete. `[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
### **List**
[Section titled âListâ](#list-2)
`npx @capgo/cli channel list [appId]`
`[appId]` your app ID the format `com.test.app` is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--apikey [key]` API key to link to your account.
### **Set**
[Section titled âSetâ](#set-1)
`npx @capgo/cli channel set [channelId] [appId]`
`[appId]` is your app ID, the format is explained [here](https://capacitorjs.com/docs/cli/commands/init/).
Optionally, you can give:
* `--bundle [1.2.3]` your app bundle already sent to the cloud, to link it to a channel.
* `--latest` get the bundle version from `package.json:version`, cannot be used with `--bundle`.
* `--state [ normal | default ]` set the channel state, can be `normal` or `default`. One channel needs to be `default`.
* `--downgrade` allows the channel to send downgrade version to devices.
* `--no-downgrade` disallows the channel to send downgrade version to devices.
* `--upgrade` allows the channel to send upgrade (major) version to devices.
* `--no-upgrade` disallow the channel to send upgrade (major) version to devices.
* `--ios` allows the channel to send version to iOS devices.
* `--no-ios` disallows the channel to send version to iOS devices.
* `--android` allows the channel to send version to android devices.
* `--no-android` disallows the channel to send version to android devices.
* `--self-assign` allows devices to self assign to this channel.
* `--no-self-assign` disallows devices to self assign to this channel.
* `--disable-auto-update STRATEGY` Disable auto update strategy for this channel. The possible options are: major, minor, metadata, none.
* `--apikey [key]` API key to link to your account.
## Disable updates strategy
[Section titled âDisable updates strategyâ](#disable-updates-strategy)
There are a few ways to handle disabling updates for too old versions.\
Capgo cannot update native code thus an update from a version with the old native code to a version with the updated native code should not be possible. There are a couple of ways to achieve that.
First, the `major` strategy. It prevents an update from `0.0.0` -> `1.0.0`. The major is the highlighted number (**1**.0.0 and **0**.0.0).\
Second is the `minor` strategy. It prevents an update from `0.0.0` -> `1.1.0` or an update from `1.1.0` to `1.2.0`. **BE AWARE** this strategy does not prevent an update from `0.1.0` -> `1.1.0`
Third, the `patch` strategy. It was added into capgo as a very strict mode. Itâs not recommended to be used unless you fully understand how it works. In order for it to accept a update the following conditions must be meet:
* The major is the same between the new and the old version
* The minor is the same between the new and the old version
* The patch of the new version if greater then the patch of the old version
Here is an example of which scenarios the update is allowed or denied
* 0.0.311 -> 0.0.314 â
* 0.0.0 -> 0.0.314 â
* 0.0.316 -> 0.0.314 â
* 0.1.312 -> 0.0.314 â
* 1.0.312 -> 0.0.314 â
Lastly the most complicated strategy. The `metadata` strategy.\
First you need to know that initially after you enable it the updates **WILL** fail as the channel is lacking the required metadata.\
If the channel is lacking metadata you will see a message like this:

If you see something like this you know that you have to go to the current bundle for the failing channel and set the metadata.\
First, figure out what channel is failing. You can do that by looking at the `misconfigured` column

Then go to the failing channel and click on `Bundle number`. This should take you to the bundle page.

Once there fill the `Minimal update version` field. This should be a [semver](https://devhints.io/semver/).\
If the value you pass is not a semver you will get an error, but if everything goes correctly you should see something like this:

Now, you likely do not want to set this data manually every time you update. Fortunately, the CLI will prevent you from sending an update without this metadata

To properly upload a bundle when using the `metadata` option you need to pass the `--min-update-version` with the valid semver. Something like this:

The `--min-update-version` is not the ONLY way to do compatibility. There also exists the `--auto-min-update-version`. Here is how it works.
First, it takes a look at the version currently uploaded to the channel. It checks compatibility same as `bundle compatibility` command would. Second, if the new version is 100% compatible it reuses the `min_update_version` from the latest version in the channel. If not, then it sets the `min_update_version` to the bundle number of the newly uploaded version.
You will always get an information what is the `min_update_version` when using this option. It will look something like this:

If the new version is not compatible it should look something like this

## End-to-End encryption (Trustless)
[Section titled âEnd-to-End encryption (Trustless)â](#end-to-end-encryption-trustless)
Capgo supports end-to-end encryption, this means that your bundle(code) is encrypted before sent to the cloud and decrypted on the device. For that, you need to generate an RSA key pair, you can use the following command to generate it.
The encryption system is a combination of RSA and AES, the RSA key is used to encrypt the AES key, and the AES key is used to encrypt the file.
See below for more information about the encryption system.

Encryption schema
### Create key for your app
[Section titled âCreate key for your appâ](#create-key-for-your-app)
`npx @capgo/cli key create`
Optionally, you can give: `--force` to overwrite the existing key. This command will create for you a key pair in your app, and will ask you to save the private key in a safe place. Itâs recommended to not git commit the private key, and to not share it with anyone.
> After your local test, remove the key from the config file and add it on the CI step with `key save`
### Save key in your app config
[Section titled âSave key in your app configâ](#save-key-in-your-app-config)
`npx @capgo/cli key save`
Optionally, you can give:
`--key [/path/to/my/public_key]` the path of your public key file.
`--key-data [publicKey]` the public key data, if you want to use inline. This command is useful if you followed the recommendation and didnât commit the key in your app config.
## Ci integration
[Section titled âCi integrationâ](#ci-integration)
To automate your work, I recommend you make GitHub action do the job of pushing to our server
[GitHub action tutorial](https://capgo.app/blog/automatic-build-and-release-with-github-actions/)
## Our demo app
[Section titled âOur demo appâ](#our-demo-app)
[GitHub - Cap-go/demo-app](https://github.com/Cap-go/demo-app/)
Donât forget to configure CI env variable with your API key
# CLI From 0.x to 1.x
> How to upgrade from 0.x to 1.x, of the updater of Capgo, learn what are the breaking changes and how to handle them
There are no significant changes in the CLI.
The breaking change is mainly the rename of the argument `--version` to `--bundle` to avoid conflict, and follow the new naming everywhere.
# Encryption
> How to encrypt your data with encryption v2, secure your app and ensure only you can update your users with your updates
This documentation explains how to migrate to the encryption v2 system. Learn more about the encryption v2 system in the [blog post](/blog/introducing-end-to-end-security-to-capacitor-updater-with-code-signing).
## 1. Create Key Pair
[Section titled â1. Create Key Pairâ](#1-create-key-pair)
```bash
npx @capgo/cli key create
```
Store the private key securely. Never commit it to source control or share it with untrusted parties.
This command:
* Creates a new key pair in your app
* Removes the old key from your Capacitor config
* Keeps old key files for backward compatibility
## 2. Update Capacitor Config
[Section titled â2. Update Capacitor Configâ](#2-update-capacitor-config)
When prompted âDo you want to setup encryption with the new channel in order to support old apps and facilitate the migration?â, select yes. This adds a new `defaultChannel` option to your Capacitor config.
capacitor.config.ts
```ts
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'Example App',
plugins: {
CapacitorUpdater: {
// ... other options
defaultChannel: 'encryption_v2' // New apps will use this channel
}
}
};
export default config;
```
## 3. Upload Bundle to New Channel
[Section titled â3. Upload Bundle to New Channelâ](#3-upload-bundle-to-new-channel)
```bash
npx @capgo/cli bundle upload --channel encryption_v2
```
## 4. Enable Self-Assignment
[Section titled â4. Enable Self-Assignmentâ](#4-enable-self-assignment)
Caution
Required for the `defaultChannel` option to work
```bash
npx @capgo/cli channel set encryption_v2 --self-assign
```
## 5. Upload to Old Channel
[Section titled â5. Upload to Old Channelâ](#5-upload-to-old-channel)
```bash
npx @capgo/cli bundle upload --channel production
```
Tip
Capacitor config is never uploaded to Capgo
## 6. Cleanup (After 3-4 Months)
[Section titled â6. Cleanup (After 3-4 Months)â](#6-cleanup-after-3-4-months)
Once all users have updated their apps:
1. Remove `defaultChannel` from your Capacitor config
2. Delete the old channel:
```bash
npx @capgo/cli channel delete encryption_v2
```
Note
Apps using `encryption_v2` as default will switch to `production` channel after deletion
# Overview
> This document provides a comprehensive overview of the Capgo CLI, how it can be utilized to enhance your app development process by enabling seamless live updates
Use Capgoâs Live Updates feature to update the JavaScript bundles of your app remotely, in real-time. Push JS updates directly to your users without going through the app store review process to instantly fix bugs and ship new features.
Note
Live Updates are limited to JavaScript bundle changes. If you need to update native code, such as adding or removing a plugin or changing native project configuration, youâll need to submit a new native binary build to the app stores.
## How Live Updates Work
[Section titled âHow Live Updates Workâ](#how-live-updates-work)
Capgoâs Live Update system has two key components:
1. The Capgo SDK, which you install in your app. The SDK checks for available updates and downloads them in the background.
2. Channels, which let you target updates to specific groups of users. You can use channels to manage different release tracks, such as `Production`, `Staging`, and `Dev`.
When you upload a new JS bundle to Capgo and assign it to a channel, the Capgo SDK in apps configured for that channel will detect the update and download it. The next time the app restarts, the new bundle will be loaded.
## Getting Started
[Section titled âGetting Startedâ](#getting-started)
To start using Live Updates, follow these steps:
1. Complete the [Capgo Quickstart](/docs/getting-started/quickstart) to set up your app in Capgo and install the Capgo SDK.
2. In your app code, call `CapacitorUpdater.notifyAppReady()` after your app has finished initializing. This tells the Capgo SDK that your app is ready to receive updates.
3. Build your JS bundle and upload it to Capgo:
```shell
npm run build
npx @capgo/cli@latest bundle upload --channel=production
```
4. Open your app and wait for the update to download. You can check the status with:
```shell
npx @capgo/cli@latest app debug
```
5. Once the update is downloaded, close and reopen your app to load the new bundle.
See the [Deploying Live Updates](/docs/getting-started/deploy) guide for more details.
## The Capgo CLI
[Section titled âThe Capgo CLIâ](#the-capgo-cli)
The Capgo CLI is a powerful tool that allows developers to interact with Capgoâs services from their own CI/CD pipelines. With the CLI, you have granular control over when builds are produced and deployed, enabling you to integrate Capgo into your existing enterprise workflows.
### What is the Capgo CLI for?
[Section titled âWhat is the Capgo CLI for?â](#what-is-the-capgo-cli-for)
The Capgo CLI is designed for developers and teams who need more control and flexibility in their live update workflows. By using the CLI in your CI/CD pipelines, you can:
* Decide exactly when to build and deploy updates, rather than relying on Capgoâs built-in automation
* Insert your own processes, such as code signing, QA testing, or manager approvals, between the build and deploy steps
* Integrate Capgo into your existing DevOps tooling and workflows
### Authentication
[Section titled âAuthenticationâ](#authentication)
To use the Capgo CLI, youâll need to authenticate with your API key. You can generate an API key in your Capgo account settings.
To log in and securely store your API key, run:
```shell
npx @capgo/cli@latest login [API_KEY]
```
This command will then be saved for future use. You wonât need to provide your API key with each command after logging in.
### Key Differences from Other CLI Tools
[Section titled âKey Differences from Other CLI Toolsâ](#key-differences-from-other-cli-tools)
If youâre familiar with other live update CLI tools, there are a few key things to note about Capgoâs CLI:
* Capgo uses a single CLI for both development and CI/CD use cases, as Capgo is focused solely on the live update feature set.
* The Capgo CLI doesnât require a separate installation step. Itâs bundled with the `@capgo/cli` package and can be run directly using `npx`.
* Capgoâs CLI is designed specifically for the live update workflow, so it may not include some features or commands found in more general-purpose CLI tools.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
[ Channels](/docs/live-updates/channels/)
[Learn how to use channels to manage different release tracks and target updates to specific users.](/docs/live-updates/channels/)
[ Rollbacks](/docs/live-updates/rollbacks/)
[Discover how to roll back to a previous JS bundle version if an update causes issues.](/docs/live-updates/rollbacks/)
[ Update Behavior](/docs/live-updates/update-behavior/)
[Customize how and when updates are downloaded and applied in your app.](/docs/live-updates/update-behavior/)
[ Fast Updates](/docs/live-updates/differentials/)
[Learn how to use fast updates to speed up the update process.](/docs/live-updates/differentials/)
# đ¤ account
> đ¤ Manage your Capgo account details and retrieve information for support or collaboration.
đ¤ Manage your Capgo account details and retrieve information for support or collaboration.
### []()đš **Id**
[Section titled â đš Idâ](#--id)
```bash
npx @capgo/cli@latest account id
```
𪪠Retrieve your account ID, safe to share for collaboration or support purposes in Discord or other platforms.
**Example:**
```bash
npx @capgo/cli@latest account id
```
**Options:**
| Param | Type | Description |
| ------- | -------- | ------------------------------- |
| **-a,** | `string` | API key to link to your account |
# đą app
> đą Manage your Capgo app settings and configurations in Capgo Cloud.
đą Manage your Capgo app settings and configurations in Capgo Cloud.
### []()â **Add**
[Section titled â â Addâ](#--add)
**Alias:** `a`
```bash
npx @capgo/cli@latest app add
```
â Add a new app to Capgo Cloud with a unique app ID in the format com.test.app. All options can be guessed from config if not provided.
**Example:**
```bash
npx @capgo/cli@latest app add com.example.app --name "My App" --icon ./icon.png
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-n,** | `string` | App name for display in Capgo Cloud |
| **-i,** | `string` | App icon path for display in Capgo Cloud |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đď¸ **Delete**
[Section titled â đď¸ Deleteâ](#-ď¸-delete)
```bash
npx @capgo/cli@latest app delete
```
đď¸ Delete an app from Capgo Cloud, optionally specifying a version to delete only that bundle.
**Example:**
```bash
npx @capgo/cli@latest app delete com.example.app
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ **List**
[Section titled â đ Listâ](#--list)
**Alias:** `l`
```bash
npx @capgo/cli@latest app list
```
đ List all apps registered under your account in Capgo Cloud.
**Example:**
```bash
npx @capgo/cli@latest app list
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ **Debug**
[Section titled â đ Debugâ](#--debug)
```bash
npx @capgo/cli@latest app debug
```
đ Listen for live update events in Capgo Cloud to debug your app. Optionally target a specific device for detailed diagnostics.
**Example:**
```bash
npx @capgo/cli@latest app debug com.example.app --device DEVICE_ID
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **-d,** | `string` | The specific device ID to debug |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()âď¸ **Setting**
[Section titled â âď¸ Settingâ](#-ď¸-setting)
```bash
npx @capgo/cli@latest app setting
```
âď¸ Modify Capacitor configuration programmatically. Specify setting path (e.g., plugins.CapacitorUpdater.defaultChannel) with âstring or âbool.
**Example:**
```bash
npx @capgo/cli@latest app setting plugins.CapacitorUpdater.defaultChannel --string "Production"
```
**Options:**
| Param | Type | Description |
| ----------- | -------- | ----------------------------------------------------------------------- |
| **âbool** | `string` | A value for the setting to modify as a boolean, ex: âbool true |
| **âstring** | `string` | A value for the setting to modify as a string, ex: âstring âProductionâ |
### []()âď¸ **Set**
[Section titled â âď¸ Setâ](#-ď¸-set)
**Alias:** `s`
```bash
npx @capgo/cli@latest app set
```
âď¸ Update settings for an existing app in Capgo Cloud, such as name, icon, or retention period for bundles. Retention of 0 means infinite storage.
**Example:**
```bash
npx @capgo/cli@latest app set com.example.app --name "Updated App" --retention 30
```
**Options:**
| Param | Type | Description |
| -------------------- | -------- | ------------------------------------------------------------------------------------ |
| **-n,** | `string` | App name for display in Capgo Cloud |
| **-i,** | `string` | App icon path for display in Capgo Cloud |
| **-a,** | `string` | API key to link to your account |
| **-r,** | `string` | Days to keep old bundles (0 = infinite, default: 0) |
| **âexpose-metadata** | `string` | Expose bundle metadata (link and comment) to the plugin (true/false, default: false) |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đš build
> đď¸ Manage native iOS/Android builds through Capgo Cloud.
đď¸ Manage native iOS/Android builds through Capgo Cloud.
### []()đ **Init**
[Section titled â đ Initâ](#--init)
**Alias:** `onboarding`
```bash
npx @capgo/cli@latest build init
```
Set up iOS build credentials interactively (creates certificates and profiles automatically)
### []()đš **Request**
[Section titled â đš Requestâ](#--request)
```bash
npx @capgo/cli@latest build request
```
Request a native build from Capgo Cloud. This command will zip your project directory and upload it to Capgo for building. The build will be processed and sent directly to app stores. đ SECURITY: Credentials are never stored on Capgo servers. They are auto-deleted after build completion. Build outputs may optionally be uploaded for time-limited download links. đ PREREQUISITE: Save credentials first with: `npx @capgo/cli build credentials save --appId --platform `
**Example:**
```bash
npx @capgo/cli@latest build request com.example.app --platform ios --path .
```
**Options:**
| Param | Type | Description |
| -------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------ |
| **âpath** | `string` | Path to the project directory to build (default: current directory) |
| **âplatform** | `string` | Target platform: ios or android (required) |
| **âbuild-mode** | `string` | Build mode: debug or release (default: release) |
| **âbuild-certificate-base64** | `string` | iOS: Base64-encoded .p12 certificate |
| **âp12-password** | `string` | iOS: Certificate password (optional if cert has no password) |
| **âapple-id** | `string` | iOS: Apple ID email |
| **âapple-app-specific-password** | `string` | iOS: App-specific password |
| **âapple-key-id** | `string` | iOS: App Store Connect API Key ID |
| **âapple-issuer-id** | `string` | iOS: App Store Connect Issuer ID |
| **âapple-key-content** | `string` | iOS: Base64-encoded App Store Connect API key (.p8) |
| **âapp-store-connect-team-id** | `string` | iOS: App Store Connect Team ID |
| **âios-scheme** | `string` | iOS: Xcode scheme to build (default: App) |
| **âios-target** | `string` | iOS: Xcode target for reading build settings (default: same as scheme) |
| **âios-distribution** | `string` | iOS: Distribution mode |
| **âios-provisioning-profile** | `string` | iOS: Provisioning profile path or bundleId=path mapping (repeatable) |
| **âandroid-keystore-file** | `string` | Android: Base64-encoded keystore file |
| **âkeystore-key-alias** | `string` | Android: Keystore key alias |
| **âkeystore-key-password** | `string` | Android: Keystore key password |
| **âkeystore-store-password** | `string` | Android: Keystore store password |
| **âplay-config-json** | `string` | Android: Base64-encoded Google Play service account JSON |
| **âandroid-flavor** | `string` | Android: Product flavor to build (e.g. production). Required if your project has multiple flavors. |
| **âno-playstore-upload** | `boolean` | Skip Play Store upload for this build (nulls out saved play config). Requires âoutput-upload. |
| **âoutput-upload** | `boolean` | Override output upload behavior for this build only (enable). Precedence: CLI > env > saved credentials |
| **âno-output-upload** | `boolean` | Override output upload behavior for this build only (disable). Precedence: CLI > env > saved credentials |
| **âoutput-retention** | `string` | Override output link TTL for this build only (1h to 7d). Examples: 1h, 6h, 2d. Precedence: CLI > env > saved credentials |
| **âskip-build-number-bump** | `boolean` | Skip automatic build number/version code incrementing. Uses whatever version is already in the project files. |
| **âno-skip-build-number-bump** | `boolean` | Override saved credentials to re-enable automatic build number incrementing for this build only. |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
| **âverbose** | `boolean` | Enable verbose output with detailed logging |
### []()đš **Credentials**
[Section titled â đš Credentialsâ](#--credentials)
```bash
npx @capgo/cli@latest build credentials
```
Manage build credentials stored locally on your machine. đ SECURITY:
* Credentials saved to \~/.capgo-credentials/credentials.json (global) or .capgo-credentials.json (local)
* When building, sent to Capgo but NEVER stored permanently
* Deleted from Capgo immediately after build
* Build outputs may optionally be uploaded for time-limited download links đ DOCUMENTATION: iOS setup: Android setup:
# đŚ bundle
> đŚ Manage app bundles for deployment in Capgo Cloud, including upload, compatibility checks, and encryption.
đŚ Manage app bundles for deployment in Capgo Cloud, including upload, compatibility checks, and encryption.
### []()âŹď¸ **Upload**
[Section titled â âŹď¸ Uploadâ](#-ď¸-upload)
**Alias:** `u`
```bash
npx @capgo/cli@latest bundle upload
```
âŹď¸ Upload a new app bundle to Capgo Cloud for distribution. Version must be > 0.0.0 and unique. Deleted versions cannot be reused for security. External option: Store only a URL link (useful for apps >200MB or privacy requirements). Capgo never inspects external content. Add encryption for trustless security.
**Example:**
```bash
npx @capgo/cli@latest bundle upload com.example.app --path ./dist --channel production
```
**Options:**
| Param | Type | Description |
| ----------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **-p,** | `string` | Path of the folder to upload, if not provided it will use the webDir set in capacitor.config |
| **-c,** | `string` | Channel to link to |
| **-e,** | `string` | Link to external URL instead of upload to Capgo Cloud |
| **âiv-session-key** | `string` | Set the IV and session key for bundle URL external |
| **âs3-region** | `string` | Region for your S3 bucket |
| **âs3-apikey** | `string` | API key for your S3 endpoint |
| **âs3-apisecret** | `string` | API secret for your S3 endpoint |
| **âs3-endpoint** | `string` | URL of S3 endpoint |
| **âs3-bucket-name** | `string` | Name for your AWS S3 bucket |
| **âs3-port** | `string` | Port for your S3 endpoint |
| **âno-s3-ssl** | `boolean` | Disable SSL for S3 upload |
| **âkey-v2** | `string` | Custom path for private signing key (v2 system) |
| **âkey-data-v2** | `string` | Private signing key (v2 system) |
| **âbundle-url** | `boolean` | Prints bundle URL into stdout |
| **âno-key** | `boolean` | Ignore signing key and send clear update |
| **âno-code-check** | `boolean` | Ignore checking if notifyAppReady() is called in source code and index present in root folder |
| **âdisplay-iv-session** | `boolean` | Show in the console the IV and session key used to encrypt the update |
| **-b,** | `string` | Bundle version number of the bundle to upload |
| **âlink** | `string` | Link to external resource (e.g. GitHub release) |
| **âcomment** | `string` | Comment about this version, could be a release note, a commit hash, a commit message, etc. |
| **âmin-update-version** | `string` | Minimal version required to update to this version. Used only if the disable auto update is set to metadata in channel |
| **âauto-min-update-version** | `boolean` | Set the min update version based on native packages |
| **âignore-metadata-check** | `boolean` | Ignores the metadata (node\_modules) check when uploading |
| **âignore-checksum-check** | `boolean` | Ignores the checksum check when uploading |
| **âforce-crc32-checksum** | `boolean` | Force CRC32 checksum for upload (override auto-detection) |
| **âtimeout** | `string` | Timeout for the upload process in seconds |
| **âmultipart** | `boolean` | \[DEPRECATED] Use âtus instead. Uses multipart protocol for S3 uploads |
| **âzip** | `boolean` | Upload the bundle using zip to Capgo cloud (legacy) |
| **âtus** | `boolean` | Upload the bundle using TUS to Capgo cloud |
| **âtus-chunk-size** | `string` | Chunk size in bytes for TUS resumable uploads (default: auto) |
| **âpartial** | `boolean` | \[DEPRECATED] Use âdelta instead. Upload incremental updates |
| **âpartial-only** | `boolean` | \[DEPRECATED] Use âdelta-only instead. Upload only incremental updates, skip full bundle |
| **âdelta** | `boolean` | Upload delta updates (only changed files) for instant, super fast updates instead of big zip downloads |
| **âdelta-only** | `boolean` | Upload only delta updates without full bundle for maximum speed (useful for large apps) |
| **âno-delta** | `boolean` | Disable delta updates even if Direct Update is enabled |
| **âencrypted-checksum** | `string` | An encrypted checksum (signature). Used only when uploading an external bundle. |
| **âauto-set-bundle** | `boolean` | Set the bundle in capacitor.config.json |
| **âdry-upload** | `boolean` | Dry upload the bundle process, mean it will not upload the files but add the row in database (Used by Capgo for internal testing) |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
| **ânode-modules** | `string` | Paths to node\_modules directories for monorepos (comma-separated) |
| **âencrypt-partial** | `boolean` | Encrypt delta update files (auto-enabled for updater > 6.14.4) |
| **âdelete-linked-bundle-on-upload** | `boolean` | Locates the currently linked bundle in the channel you are trying to upload to, and deletes it |
| **âno-brotli-patterns** | `string` | Files to exclude from Brotli compression (comma-separated globs, e.g., â*.jpg,*.pngâ) |
| **âdisable-brotli** | `boolean` | Completely disable brotli compression even if updater version supports it |
| **âversion-exists-ok** | `boolean` | Exit successfully if bundle version already exists, useful for CI/CD workflows with monorepos |
| **âself-assign** | `boolean` | Allow devices to auto-join this channel (updates channel setting) |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
| **âverbose** | `boolean` | Enable verbose output with detailed logging |
### []()đ§Ş **Compatibility**
[Section titled â đ§Ş Compatibilityâ](#--compatibility)
```bash
npx @capgo/cli@latest bundle compatibility
```
đ§Ş Check compatibility of a bundle with a specific channel in Capgo Cloud to ensure updates are safe.
**Example:**
```bash
npx @capgo/cli@latest bundle compatibility com.example.app --channel production
```
**Options:**
| Param | Type | Description |
| ----------------- | --------- | ------------------------------------------------------------------ |
| **-a,** | `string` | API key to link to your account |
| **-c,** | `string` | Channel to check the compatibility with |
| **âtext** | `boolean` | Output text instead of emojis |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
| **ânode-modules** | `string` | Paths to node\_modules directories for monorepos (comma-separated) |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đš **ReleaseType**
[Section titled â đš ReleaseTypeâ](#--releasetype)
```bash
npx @capgo/cli@latest bundle releaseType
```
đ§ Print ânativeâ or âOTAâ based on compatibility with a channelâs latest metadata.
**Example:**
```bash
npx @capgo/cli@latest bundle releaseType com.example.app --channel production
```
**Options:**
| Param | Type | Description |
| ----------------- | -------- | ------------------------------------------------------------------ |
| **-a,** | `string` | API key to link to your account |
| **-c,** | `string` | Channel to compare against |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
| **ânode-modules** | `string` | Paths to node\_modules directories for monorepos (comma-separated) |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đď¸ **Delete**
[Section titled â đď¸ Deleteâ](#-ď¸-delete)
**Alias:** `d`
```bash
npx @capgo/cli@latest bundle delete
```
đď¸ Delete a specific bundle from Capgo Cloud, optionally targeting a single version.
**Example:**
```bash
npx @capgo/cli@latest bundle delete BUNDLE_ID com.example.app
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ **List**
[Section titled â đ Listâ](#--list)
**Alias:** `l`
```bash
npx @capgo/cli@latest bundle list
```
đ List all bundles uploaded for an app in Capgo Cloud.
**Example:**
```bash
npx @capgo/cli@latest bundle list com.example.app
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ§š **Cleanup**
[Section titled â đ§š Cleanupâ](#--cleanup)
**Alias:** `c`
```bash
npx @capgo/cli@latest bundle cleanup
```
đ§š Delete old bundles in Capgo Cloud, keeping specified number of recent versions. Bundles linked to channels are preserved unless âignore-channel is used.
**Example:**
```bash
npx @capgo/cli@latest bundle cleanup com.example.app --bundle=1.0 --keep=3
```
**Options:**
| Param | Type | Description |
| ------------------- | --------- | ------------------------------------------------------------------------- |
| **-b,** | `string` | Bundle version number of the app to delete |
| **-a,** | `string` | API key to link to your account |
| **-k,** | `string` | Number of versions to keep |
| **-f,** | `string` | Force removal |
| **âignore-channel** | `boolean` | Delete bundles even if linked to channels (WARNING: deletes channels too) |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ **Encrypt**
[Section titled â đ Encryptâ](#--encrypt)
```bash
npx @capgo/cli@latest bundle encrypt
```
đ Encrypt a zip bundle for secure external storage. Returns ivSessionKey for upload/decryption. Get checksum using âbundle zip âjsonâ.
**Example:**
```bash
npx @capgo/cli@latest bundle encrypt ./myapp.zip CHECKSUM
```
**Options:**
| Param | Type | Description |
| ----------------- | -------- | ----------------------------------------------------------- |
| **âkey** | `string` | Custom path for private signing key |
| **âkey-data** | `string` | Private signing key |
| **-j,** | `string` | Output in JSON |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
### []()đ **Decrypt**
[Section titled â đ Decryptâ](#--decrypt)
```bash
npx @capgo/cli@latest bundle decrypt
```
đ Decrypt an encrypted bundle (mainly for testing). Prints base64 session key for verification.
**Example:**
```bash
npx @capgo/cli@latest bundle decrypt ./myapp_encrypted.zip CHECKSUM
```
**Options:**
| Param | Type | Description |
| ----------------- | -------- | ------------------------------------------------------------- |
| **âkey** | `string` | Custom path for private signing key |
| **âkey-data** | `string` | Private signing key |
| **âchecksum** | `string` | Checksum of the bundle, to verify the integrity of the bundle |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
### []()đš **Zip**
[Section titled â đš Zipâ](#--zip)
```bash
npx @capgo/cli@latest bundle zip
```
đď¸ Create a zip file of your app bundle. Returns checksum for use with encryption. Use âjson for machine-readable output.
**Example:**
```bash
npx @capgo/cli@latest bundle zip com.example.app --path ./dist
```
**Options:**
| Param | Type | Description |
| ------------------ | --------- | --------------------------------------------------------------------------------------------- |
| **-p,** | `string` | Path of the folder to upload, if not provided it will use the webDir set in capacitor.config |
| **-b,** | `string` | Bundle version number to name the zip file |
| **-n,** | `string` | Name of the zip file |
| **-j,** | `string` | Output in JSON |
| **âno-code-check** | `boolean` | Ignore checking if notifyAppReady() is called in source code and index present in root folder |
| **âkey-v2** | `boolean` | Use encryption v2 |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
# đ˘ channel
> đ˘ Manage distribution channels for app updates in Capgo Cloud, controlling how updates are delivered to devices.
đ˘ Manage distribution channels for app updates in Capgo Cloud, controlling how updates are delivered to devices.
### []()â **Add**
[Section titled â â Addâ](#--add)
**Alias:** `a`
```bash
npx @capgo/cli@latest channel add
```
â Create a new channel for app distribution in Capgo Cloud to manage update delivery.
**Example:**
```bash
npx @capgo/cli@latest channel add production com.example.app --default
```
**Options:**
| Param | Type | Description |
| ---------------- | --------- | ---------------------------------------------------------------- |
| **-d,** | `string` | Set the channel as default |
| **âself-assign** | `boolean` | Allow device to self-assign to this channel |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đď¸ **Delete**
[Section titled â đď¸ Deleteâ](#-ď¸-delete)
**Alias:** `d`
```bash
npx @capgo/cli@latest channel delete
```
đď¸ Delete a channel from Capgo Cloud, optionally removing associated bundles to free up resources.
**Example:**
```bash
npx @capgo/cli@latest channel delete production com.example.app
```
**Options:**
| Param | Type | Description |
| ------------------------- | --------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âdelete-bundle** | `boolean` | Delete the bundle associated with the channel |
| **âsuccess-if-not-found** | `boolean` | Success if the channel is not found |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đ **List**
[Section titled â đ Listâ](#--list)
**Alias:** `l`
```bash
npx @capgo/cli@latest channel list
```
đ List all channels configured for an app in Capgo Cloud to review distribution settings.
**Example:**
```bash
npx @capgo/cli@latest channel list com.example.app
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đŚ **CurrentBundle**
[Section titled â đŚ CurrentBundleâ](#--currentbundle)
```bash
npx @capgo/cli@latest channel currentBundle
```
đŚ Get the current bundle linked to a specific channel in Capgo Cloud for update tracking.
**Example:**
```bash
npx @capgo/cli@latest channel currentBundle production com.example.app
```
**Options:**
| Param | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------- |
| **-c,** | `string` | Channel to get the current bundle from |
| **-a,** | `string` | API key to link to your account |
| **âquiet** | `boolean` | Only print the bundle version |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()âď¸ **Set**
[Section titled â âď¸ Setâ](#-ď¸-set)
**Alias:** `s`
```bash
npx @capgo/cli@latest channel set
```
âď¸ Configure settings for a channel, such as linking a bundle, setting update strategies (major, minor, metadata, patch, none), or device targeting (iOS, Android, dev, prod, emulator, device). One channel must be default.
**Example:**
```bash
npx @capgo/cli@latest channel set production com.example.app --bundle 1.0.0 --state default
```
**Options:**
| Param | Type | Description |
| -------------------------- | --------- | -------------------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **-b,** | `string` | Bundle version number of the file to set |
| **-s,** | `string` | Set the state of the channel, default or normal |
| **âlatest-remote** | `boolean` | Get the latest bundle uploaded in capgo cloud and set it to the channel |
| **âlatest** | `boolean` | Get the latest version key in the package.json to set it to the channel |
| **âdowngrade** | `boolean` | Allow to downgrade to version under native one |
| **âno-downgrade** | `boolean` | Disable downgrade to version under native one |
| **âios** | `boolean` | Allow sending update to iOS devices |
| **âno-ios** | `boolean` | Disable sending update to iOS devices |
| **âandroid** | `boolean` | Allow sending update to Android devices |
| **âno-android** | `boolean` | Disable sending update to Android devices |
| **âself-assign** | `boolean` | Allow device to self-assign to this channel |
| **âno-self-assign** | `boolean` | Disable devices to self-assign to this channel |
| **âdisable-auto-update** | `string` | Block updates by type: major, minor, metadata, patch, or none (allows all) |
| **âdev** | `boolean` | Allow sending update to development devices |
| **âno-dev** | `boolean` | Disable sending update to development devices |
| **âprod** | `boolean` | Allow sending update to production devices |
| **âno-prod** | `boolean` | Disable sending update to production devices |
| **âemulator** | `boolean` | Allow sending update to emulator devices |
| **âno-emulator** | `boolean` | Disable sending update to emulator devices |
| **âdevice** | `boolean` | Allow sending update to physical devices |
| **âno-device** | `boolean` | Disable sending update to physical devices |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
| **âignore-metadata-check** | `boolean` | Ignore checking node\_modules compatibility if present in the bundle |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đ¨ââď¸ doctor
> đ¨ââď¸ Check if your Capgo app installation is up-to-date and gather information useful for bug reports.
đ¨ââď¸ Check if your Capgo app installation is up-to-date and gather information useful for bug reports.
```bash
npx @capgo/cli@latest doctor
```
This command helps diagnose issues with your setup.
**Example:**
```bash
npx @capgo/cli@latest doctor
```
## []()Options
[Section titled â Optionsâ](#-options)
| Param | Type | Description |
| ----------------- | -------- | ----------------------------------------------------------- |
| **âpackage-json** | `string` | Paths to package.json files for monorepos (comma-separated) |
# đ init
> đ Initialize a new app in Capgo Cloud with step-by-step guidance.
đ Initialize a new app in Capgo Cloud with step-by-step guidance.
**Alias:** `i`
```bash
npx @capgo/cli@latest init
```
This includes adding code for updates, building, uploading your app, and verifying update functionality. Capgo bundles are web assets and can be fetched by anyone who knows the URL. Use encryption for banking, regulated, or other high-security apps.
**Example:**
```bash
npx @capgo/cli@latest init YOUR_API_KEY com.example.app
```
## []()Options
[Section titled â Optionsâ](#-options)
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-n,** | `string` | App name for display in Capgo Cloud |
| **-i,** | `string` | App icon path for display in Capgo Cloud |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đ key
> đ Manage encryption keys for secure bundle distribution in Capgo Cloud, supporting end-to-end encryption with RSA and AES combination.
đ Manage encryption keys for secure bundle distribution in Capgo Cloud, supporting end-to-end encryption with RSA and AES combination.
### []()đš **Save**
[Section titled â đš Saveâ](#--save)
```bash
npx @capgo/cli@latest key save
```
đž Save the public key in the Capacitor config, useful for CI environments. Recommended not to commit the key for security.
**Example:**
```bash
npx @capgo/cli@latest key save --key ./path/to/key.pub
```
**Options:**
| Param | Type | Description |
| ------------- | -------- | ------------------------------------ |
| **-f,** | `string` | Force generate a new one |
| **âkey** | `string` | Key path to save in Capacitor config |
| **âkey-data** | `string` | Key data to save in Capacitor config |
### []()đ¨ **Create**
[Section titled â đ¨ Createâ](#--create)
```bash
npx @capgo/cli@latest key create
```
đ¨ Create RSA key pair for end-to-end encryption. Creates .capgo\_key\_v2 (private) and .capgo\_key\_v2.pub (public) in project root. Public key is saved to capacitor.config for mobile app decryption. NEVER commit the private key - store it securely!
**Example:**
```bash
npx @capgo/cli@latest key create
```
**Options:**
| Param | Type | Description |
| ------- | -------- | ------------------------ |
| **-f,** | `string` | Force generate a new one |
### []()đď¸ **Delete\_old**
[Section titled â đď¸ Delete\_oldâ](#-ď¸-delete_old)
```bash
npx @capgo/cli@latest key delete_old
```
đ§š Delete the old encryption key from the Capacitor config to ensure only the current key is used.
**Example:**
```bash
npx @capgo/cli@latest key delete_old
```
# đ login
> đ Save your Capgo API key to your machine or local folder for easier access to Capgo Cloud services.
đ Save your Capgo API key to your machine or local folder for easier access to Capgo Cloud services.
**Alias:** `l`
```bash
npx @capgo/cli@latest login
```
Use âapikey=\*\*\*\*\*\*\*\* in any command to override it.
**Example:**
```bash
npx @capgo/cli@latest login YOUR_API_KEY
```
## []()Options
[Section titled â Optionsâ](#-options)
| Param | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------- |
| **âlocal** | `boolean` | Only save in local folder, git ignored for security. |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đš organisation
> [DEPRECATED] Use "organization" instead. This command will be removed in a future version.
\[DEPRECATED] Use âorganizationâ instead. This command will be removed in a future version.
### []()đ **List**
[Section titled â đ Listâ](#--list)
**Alias:** `l`
```bash
npx @capgo/cli@latest organisation list
```
\[DEPRECATED] Use âorganization listâ instead.
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()â **Add**
[Section titled â â Addâ](#--add)
**Alias:** `a`
```bash
npx @capgo/cli@latest organisation add
```
\[DEPRECATED] Use âorganization addâ instead.
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-n,** | `string` | Organization name |
| **-e,** | `string` | Management email for the organization |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()âď¸ **Set**
[Section titled â âď¸ Setâ](#-ď¸-set)
**Alias:** `s`
```bash
npx @capgo/cli@latest organisation set
```
\[DEPRECATED] Use âorganization setâ instead.
**Options:**
| Param | Type | Description |
| --------------------------------- | --------- | -------------------------------------------------------------------------- |
| **-n,** | `string` | Organization name |
| **-e,** | `string` | Management email for the organization |
| **âenforce-2fa** | `boolean` | Enable 2FA enforcement for all organization members |
| **âno-enforce-2fa** | `boolean` | Disable 2FA enforcement for organization |
| **âpassword-policy** | `boolean` | Enable password policy enforcement for organization |
| **âno-password-policy** | `boolean` | Disable password policy enforcement |
| **âmin-length** | `string` | Minimum password length (6-128, default: 10) |
| **ârequire-uppercase** | `boolean` | Require uppercase letter in password |
| **âno-require-uppercase** | `boolean` | Do not require uppercase letter |
| **ârequire-number** | `boolean` | Require number in password |
| **âno-require-number** | `boolean` | Do not require number |
| **ârequire-special** | `boolean` | Require special character in password |
| **âno-require-special** | `boolean` | Do not require special character |
| **ârequire-apikey-expiration** | `boolean` | Require all API keys to have an expiration date |
| **âno-require-apikey-expiration** | `boolean` | Do not require API key expiration |
| **âmax-apikey-expiration-days** | `string` | Maximum days before API key expiration (1-365, null for no limit) |
| **âenforce-hashed-api-keys** | `boolean` | Enforce hashed/secure API keys (key value stored as hash, shown only once) |
| **âno-enforce-hashed-api-keys** | `boolean` | Allow plain-text API keys |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đď¸ **Delete**
[Section titled â đď¸ Deleteâ](#-ď¸-delete)
**Alias:** `d`
```bash
npx @capgo/cli@latest organisation delete
```
\[DEPRECATED] Use âorganization deleteâ instead.
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đš organization
> đ˘ Manage your organizations in Capgo Cloud for team collaboration and app management.
đ˘ Manage your organizations in Capgo Cloud for team collaboration and app management.
### []()đ **List**
[Section titled â đ Listâ](#--list)
**Alias:** `l`
```bash
npx @capgo/cli@latest organization list
```
đ List all organizations you have access to in Capgo Cloud.
**Example:**
```bash
npx @capgo/cli@latest organization list
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()â **Add**
[Section titled â â Addâ](#--add)
**Alias:** `a`
```bash
npx @capgo/cli@latest organization add
```
â Create a new organization in Capgo Cloud for team collaboration.
**Example:**
```bash
npx @capgo/cli@latest organization add --name "My Company" --email admin@mycompany.com
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-n,** | `string` | Organization name |
| **-e,** | `string` | Management email for the organization |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đš **Members**
[Section titled â đš Membersâ](#--members)
**Alias:** `m`
```bash
npx @capgo/cli@latest organization members
```
đĽ List organization members and their 2FA status. Shows all members of an organization with their roles and whether they have 2FA enabled. Useful before enabling 2FA enforcement to see which members will be affected.
> âšď¸ Viewing 2FA status requires super\_admin rights in the organization.
**Example:**
```bash
npx @capgo/cli@latest organization members ORG_ID
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()âď¸ **Set**
[Section titled â âď¸ Setâ](#-ď¸-set)
**Alias:** `s`
```bash
npx @capgo/cli@latest organization set
```
âď¸ Update organization settings including name, email, security policies, and enforcement options. Security settings require super\_admin role.
**Example:**
```bash
npx @capgo/cli@latest organization set ORG_ID --name "New Name"
```
**Options:**
| Param | Type | Description |
| --------------------------------- | --------- | -------------------------------------------------------------------------- |
| **-n,** | `string` | Organization name |
| **-e,** | `string` | Management email for the organization |
| **âenforce-2fa** | `boolean` | Enable 2FA enforcement for all organization members |
| **âno-enforce-2fa** | `boolean` | Disable 2FA enforcement for organization |
| **âpassword-policy** | `boolean` | Enable password policy enforcement for organization |
| **âno-password-policy** | `boolean` | Disable password policy enforcement |
| **âmin-length** | `string` | Minimum password length (6-128, default: 10) |
| **ârequire-uppercase** | `boolean` | Require uppercase letter in password |
| **âno-require-uppercase** | `boolean` | Do not require uppercase letter |
| **ârequire-number** | `boolean` | Require number in password |
| **âno-require-number** | `boolean` | Do not require number |
| **ârequire-special** | `boolean` | Require special character in password |
| **âno-require-special** | `boolean` | Do not require special character |
| **ârequire-apikey-expiration** | `boolean` | Require all API keys to have an expiration date |
| **âno-require-apikey-expiration** | `boolean` | Do not require API key expiration |
| **âmax-apikey-expiration-days** | `string` | Maximum days before API key expiration (1-365, null for no limit) |
| **âenforce-hashed-api-keys** | `boolean` | Enforce hashed/secure API keys (key value stored as hash, shown only once) |
| **âno-enforce-hashed-api-keys** | `boolean` | Allow plain-text API keys |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
### []()đď¸ **Delete**
[Section titled â đď¸ Deleteâ](#-ď¸-delete)
**Alias:** `d`
```bash
npx @capgo/cli@latest organization delete
```
đď¸ Delete an organization from Capgo Cloud. This action cannot be undone. Only organization owners can delete organizations.
**Example:**
```bash
npx @capgo/cli@latest organization delete ORG_ID
```
**Options:**
| Param | Type | Description |
| -------------- | -------- | ---------------------------------------------------------------- |
| **-a,** | `string` | API key to link to your account |
| **âsupa-host** | `string` | Custom Supabase host URL (for self-hosting or Capgo development) |
| **âsupa-anon** | `string` | Custom Supabase anon key (for self-hosting) |
# đš probe
> đ Probe the Capgo updates endpoint to check if an update is available for your app.
đ Probe the Capgo updates endpoint to check if an update is available for your app.
```bash
npx @capgo/cli@latest probe
```
Sends a single request to the updates endpoint using your projectâs capacitor config and reports whether an update would be delivered, or explains why not.
**Example:**
```bash
npx @capgo/cli@latest probe --platform ios
```
## []()Options
[Section titled â Optionsâ](#-options)
| Param | Type | Description |
| ------------- | -------- | --------------------------------- |
| **âplatform** | `string` | Platform to probe: ios or android |
# đš star
> â Star a Capgo GitHub repository to support the project.
â Star a Capgo GitHub repository to support the project.
```bash
npx @capgo/cli@latest star
```
If you do not pass a repository name, this defaults to capacitor-updater in the Cap-go org.
# đš star-all
> â Star all Capgo GitHub repositories with a small random delay between each request.
â Star all Capgo GitHub repositories with a small random delay between each request.
```bash
npx @capgo/cli@latest star-all
```
If you do not pass repositories, this defaults to all Cap-go repositories whose name starts with `capacitor-`.
## []()Options
[Section titled â Optionsâ](#-options)
| Param | Type | Description |
| -------------------- | -------- | ---------------------------------------------------------------- |
| **âmin-delay-ms** | `string` | Minimum delay in ms between each star action (default: 20) |
| **âmax-delay-ms** | `string` | Maximum delay in ms between each star action (default: 180) |
| **âmax-concurrency** | `string` | Maximum number of star requests running in parallel (default: 4) |
# Adding or Updating Plugins
> Complete guide for contributors and agents on how to add new plugins or update existing plugins in the Capgo documentation.
This guide explains how to add new Capacitor plugins to the Capgo website or update existing plugin documentation. This is useful for contributors, maintainers, and AI agents helping to maintain the documentation.
## Overview
[Section titled âOverviewâ](#overview)
When adding a new plugin to the Capgo ecosystem, you need to update several files and locations across the website to ensure the plugin appears correctly in all relevant places:
1. **Plugin List Configuration** - Add plugin metadata to the master list
2. **Plugin Index Page** - Add plugin to the categorized plugin listing page
3. **Sidebar Navigation** - Add plugin to the documentation sidebar
4. **Plugin Documentation** - Create overview and getting-started pages
5. **Plugin Tutorial** - Create a comprehensive tutorial
## File Locations
[Section titled âFile Locationsâ](#file-locations)
### Key Files to Update
[Section titled âKey Files to Updateâ](#key-files-to-update)
| File | Purpose |
| ----------------------------------------------- | --------------------------------- |
| `/src/config/plugins.ts` | Master plugin list with metadata |
| `/src/content/docs/docs/plugins/index.mdx` | Plugin index page with categories |
| `/astro.config.mjs` | Sidebar navigation configuration |
| `/src/content/docs/docs/plugins/[plugin-name]/` | Plugin documentation directory |
| `/src/content/plugins-tutorials/en/` | English tutorial files |
## Step-by-Step Guide
[Section titled âStep-by-Step Guideâ](#step-by-step-guide)
1. ### Add Plugin to Master List
[Section titled âAdd Plugin to Master Listâ](#add-plugin-to-master-list)
Open `/src/config/plugins.ts` and add your plugin to the `actions` array:
```typescript
// First, import an appropriate Heroicon
import YourIconName from 'astro-heroicons/mini/IconName.astro'
// Then add to the actions array
{
name: '@capgo/your-plugin-name',
author: 'github.com/Cap-go',
description: 'Brief description of what the plugin does',
href: 'https://github.com/Cap-go/your-plugin-name/',
title: 'Display Name',
icon: YourIconName,
}
```
**Available Icons**: Check `/node_modules/astro-heroicons/mini/` for available icons.
2. ### Add Plugin to Index Page
[Section titled âAdd Plugin to Index Pageâ](#add-plugin-to-index-page)
Open `/src/content/docs/docs/plugins/index.mdx` and add your plugin under the appropriate category:
```mdx
```
**Categories**:
* â Featured Plugins
* đą Device & System Plugins
* đĽ Media & Camera Plugins
* đ ď¸ Utility Plugins
* đ¤ AI & Advanced Media
* đ Location & Background Services
* đ Communication & Analytics
* đ Security & System
* đ Android-Specific Features
* đĽ Download & Navigation
3. ### Add to Sidebar Navigation
[Section titled âAdd to Sidebar Navigationâ](#add-to-sidebar-navigation)
Open `/astro.config.mjs` and add your plugin to the sidebar configuration (around line 540):
```javascript
{
label: 'Your Plugin Name',
items: [
{ label: 'Overview', link: '/docs/plugins/your-plugin-name/' },
{ label: 'Getting started', link: '/docs/plugins/your-plugin-name/getting-started' },
],
collapsed: true,
}
```
Plugins are listed alphabetically in the sidebar.
4. ### Create Plugin Documentation Directory
[Section titled âCreate Plugin Documentation Directoryâ](#create-plugin-documentation-directory)
Create a new directory for your plugin documentation:
```bash
mkdir -p /src/content/docs/docs/plugins/your-plugin-name/
```
5. ### Create Plugin Overview Page
[Section titled âCreate Plugin Overview Pageâ](#create-plugin-overview-page)
Create `/src/content/docs/docs/plugins/your-plugin-name/index.mdx`:
```mdx
---
title: "@capgo/your-plugin-name"
description: Brief description of the plugin's purpose
tableOfContents: false
next: false
prev: false
sidebar:
order: 1
label: "Introduction"
hero:
tagline: Detailed tagline explaining what the plugin does
image:
file: ~public/your-plugin-icon.svg
actions:
- text: Get started
link: /docs/plugins/your-plugin-name/getting-started/
icon: right-arrow
variant: primary
- text: Github
link: https://github.com/Cap-go/your-plugin-name/
icon: external
variant: minimal
---
import { Card, CardGrid } from '@astrojs/starlight/components';
Description of first key feature
Description of second key feature
Works on both iOS and Android đą
Check the [Documentation](/docs/plugins/your-plugin-name/getting-started/) to master the plugin.
```
6. ### Create Getting Started Guide
[Section titled âCreate Getting Started Guideâ](#create-getting-started-guide)
Create `/src/content/docs/docs/plugins/your-plugin-name/getting-started.mdx`:
```mdx
---
title: Getting Started
description: Learn how to install and use the plugin in your Capacitor app.
sidebar:
order: 2
---
import { Steps } from '@astrojs/starlight/components';
import { PackageManagers } from 'starlight-package-managers'
1. **Install the package**
2. **Sync with native projects**
## Configuration
### iOS Configuration
[iOS-specific setup instructions]
### Android Configuration
[Android-specific setup instructions]
## Usage
[Basic usage examples]
## API Reference
[Detailed API documentation]
## Complete Example
[Full working example]
## Best Practices
[Recommended practices and tips]
## Platform Notes
[Platform-specific notes and limitations]
```
7. ### Create Tutorial File
[Section titled âCreate Tutorial Fileâ](#create-tutorial-file)
Create `/src/content/plugins-tutorials/en/your-plugin-name.md`:
```markdown
---
locale: en
---
# Using @capgo/your-plugin-name Package
The `@capgo/your-plugin-name` package [brief description]. In this tutorial, we will guide you through the installation, configuration, and usage of this package in your Ionic Capacitor app.
## Installation
[Installation steps]
## Configuration
[Configuration steps for iOS and Android]
## API Usage
[Detailed API usage examples]
## Complete Example
[Full working example]
## Best Practices
[Tips and best practices]
## Troubleshooting
[Common issues and solutions]
## Conclusion
[Summary and links to additional resources]
```
## Plugin Documentation Structure
[Section titled âPlugin Documentation Structureâ](#plugin-documentation-structure)
### Required Files
[Section titled âRequired Filesâ](#required-files)
```plaintext
src/content/docs/docs/plugins/your-plugin-name/
âââ index.mdx # Overview page with hero and feature cards
âââ getting-started.mdx # Installation and usage guide
src/content/plugins-tutorials/en/
âââ your-plugin-name.md # Comprehensive tutorial
```
### Optional Files
[Section titled âOptional Filesâ](#optional-files)
For complex plugins, you may add additional documentation pages:
```plaintext
src/content/docs/docs/plugins/your-plugin-name/
âââ index.mdx
âââ getting-started.mdx
âââ api-reference.mdx # Detailed API documentation
âââ examples.mdx # Additional examples
âââ troubleshooting.mdx # Troubleshooting guide
âââ migrations.mdx # Migration guides
```
## Content Guidelines
[Section titled âContent Guidelinesâ](#content-guidelines)
### Writing Plugin Descriptions
[Section titled âWriting Plugin Descriptionsâ](#writing-plugin-descriptions)
* **Be Concise**: Keep descriptions under 100 characters
* **Be Specific**: Explain what the plugin does, not what it is
* **Use Action Words**: Start with verbs like âControlâ, âIntegrateâ, âEnableâ
**Good Examples**:
* âControl device flashlight and torch with simple on/off toggleâ
* âIntegrate Crisp live chat and customer support into your appâ
* âEnable secure authentication using Face ID and Touch IDâ
**Bad Examples**:
* âA plugin for flashâ
* âThis is a Crisp pluginâ
* âBiometric pluginâ
### Writing Documentation
[Section titled âWriting Documentationâ](#writing-documentation)
1. **Start with Installation**: Always begin with clear installation steps
2. **Provide Configuration**: Include platform-specific setup requirements
3. **Show Usage Examples**: Provide working code examples
4. **Include API Reference**: Document all methods and parameters
5. **Add Complete Examples**: Show real-world usage patterns
6. **List Best Practices**: Share tips for optimal usage
7. **Document Platform Differences**: Clarify iOS vs Android behavior
8. **Add Troubleshooting**: Address common issues
### Code Examples
[Section titled âCode Examplesâ](#code-examples)
* Use TypeScript for all code examples
* Include imports at the top
* Add comments explaining key steps
* Show error handling
* Demonstrate both basic and advanced usage
## Checklist
[Section titled âChecklistâ](#checklist)
Use this checklist when adding a new plugin:
* [ ] Added plugin to `/src/config/plugins.ts`
* [ ] Selected appropriate icon from Heroicons
* [ ] Added plugin to `/src/content/docs/docs/plugins/index.mdx` under correct category
* [ ] Added sidebar entry in `/astro.config.mjs`
* [ ] Created plugin documentation directory
* [ ] Created `index.mdx` overview page
* [ ] Created `getting-started.mdx` guide
* [ ] Created tutorial in `/src/content/plugins-tutorials/en/`
* [ ] Included installation instructions
* [ ] Documented iOS configuration
* [ ] Documented Android configuration
* [ ] Provided usage examples
* [ ] Added API reference
* [ ] Included complete working example
* [ ] Listed best practices
* [ ] Added platform-specific notes
* [ ] Tested all links work correctly
## Icon Reference
[Section titled âIcon Referenceâ](#icon-reference)
Common icons used for plugins (from `astro-heroicons/mini/`):
| Icon | Use Case |
| ------------------------ | ----------------------------------- |
| `BoltIcon` | Flash, power, energy |
| `CameraIcon` | Camera, photo, video |
| `ChatBubbleLeftIcon` | Chat, messaging, communication |
| `FingerPrintIcon` | Biometric, security, authentication |
| `MapPinIcon` | Location, geolocation, maps |
| `SpeakerWaveIcon` | Audio, sound, music |
| `VideoCameraIcon` | Video, recording, streaming |
| `CreditCardIcon` | Payments, purchases |
| `PlayCircleIcon` | Media players, video players |
| `SignalIcon` | Connectivity, network, beacon |
| `RadioIcon` | Beacon, broadcast, wireless |
| `ChatBubbleOvalLeftIcon` | Social media, WeChat |
## Updating Existing Plugins
[Section titled âUpdating Existing Pluginsâ](#updating-existing-plugins)
When updating an existing plugin:
1. **Update version numbers** in documentation
2. **Add migration guides** if breaking changes exist
3. **Update API reference** with new methods
4. **Add new examples** for new features
5. **Update platform requirements** if changed
6. **Revise best practices** based on new features
7. **Keep tutorial current** with latest API
## Language Paths
[Section titled âLanguage Pathsâ](#language-paths)
Write and review plugin docs in English. Localized paths are generated by the site metadata and translated at the edge by the translation Worker.
## Testing Your Changes
[Section titled âTesting Your Changesâ](#testing-your-changes)
After adding or updating plugin documentation:
1. **Build the site locally**:
```bash
bun run build
```
2. **Check for errors**:
* Verify all links work
* Ensure images load correctly
* Confirm code examples are valid
* Test navigation works
3. **Preview the site**:
```bash
bun run dev
```
4. **Verify your plugin appears**:
* Check plugin listing page
* Verify sidebar navigation
* Test all documentation pages
* Confirm tutorial page works
## Common Pitfalls
[Section titled âCommon Pitfallsâ](#common-pitfalls)
Caution
**Avoid these common mistakes:**
1. **Forgetting to sync**: Always run `bunx cap sync` in examples
2. **Inconsistent naming**: Use the same plugin name everywhere
3. **Missing platform config**: Document both iOS and Android setup
4. **Broken links**: Use relative links and verify they work
5. **No error handling**: Always show try-catch in examples
6. **Missing imports**: Include all necessary imports in examples
7. **Unclear descriptions**: Be specific about what the plugin does
## Getting Help
[Section titled âGetting Helpâ](#getting-help)
If you need help adding or updating plugin documentation:
* **Discord**: Join our [Discord community](https://discord.capgo.app)
* **GitHub**: Open an issue on the [website repository](https://github.com/Cap-go/website)
* **Email**: Contact the team at
## Examples
[Section titled âExamplesâ](#examples)
For reference, check these well-documented plugins:
* **Updater**: `/src/content/docs/docs/plugins/updater/` (complex plugin with multiple pages)
* **Flash**: `/src/content/docs/docs/plugins/flash/` (simple plugin, good starter example)
* **Social Login**: `/src/content/docs/docs/plugins/social-login/` (plugin with sub-pages)
## Summary
[Section titled âSummaryâ](#summary)
Adding a plugin to the Capgo documentation involves:
1. Adding metadata to the master configuration
2. Adding the plugin to the categorized index page
3. Configuring sidebar navigation
4. Creating comprehensive documentation pages
5. Writing a detailed tutorial
6. Testing all changes locally
By following this guide, you ensure that plugins are consistently documented and easily discoverable by users.
# FAQ
> Frequently asked questions about Capgo, how to solve the most common issue in Capgo or with the Updater, what is OTA and how to manage them
If you have questions not answered here, please ask! Both filing an issue or asking on [Discord](https://discord.capgo.app) work.
### What is âcode pushâ?[](https://capgo.app/docs/#what-is-code-push "Direct link to What is \"code push\"?")
[Section titled âWhat is âcode pushâ?â](#what-is-code-push)
Code push, also referred to as âover-the-air updatesâ (OTA) is a cloud service enabling Capacitor developers to deploy updates to their apps in production. Capgo currently works on Android, iOS, and Electron.
âCode Pushâ is a reference to the name of a deploy feature used by the React Native community from [Microsoft](https://appcenter.ms/) and [Expo](https://expo.dev/), neither of which support Capacitor.
### What is the difference between a bundle and a release?[](https://capgo.app/docs/faq/#what-is-the-difference-between-a-bundle-and-a-release "Direct link to What is the difference between a bundle and a release?")
[Section titled âWhat is the difference between a bundle and a release?â](#what-is-the-difference-between-a-bundle-and-a-release)
We use the term âreleaseâ to mean preparing a binary for the app stores. In order to later generate a bundle Capgo needs to know the exact binary that was shipped to the app stores.
We use the term âbundleâ to mean a patch that can be applied to a release to update it to new code. The `npx @capgo/cli@latest bundle upload` command is used to generate a bundle from your new local code which is then shipped to your users.
### What is the roadmap?[](https://capgo.app/docs/faq/#what-is-the-roadmap "Direct link to What is the roadmap?")
[Section titled âWhat is the roadmap?â](#what-is-the-roadmap)
Our project boards are also public and found at: [https://github.com/orgs/Cap-go/projects](https://github.com/orgs/Cap-go/projects/)
Our team also operates in the public, so you can see what weâre working on at any time. Weâre happy to answer any questions you have about our roadmap or priorities via Github issues or [Discord](https://discord.capgo.app).
### Can I use Capgo with my team?[](https://capgo.app/docs/faq/#can-i-use-capgo-with-my-team "Direct link to Can I use Capgo with my team?")
[Section titled âCan I use Capgo with my team?â](#can-i-use-capgo-with-my-team)
Yes! All plans support unlimited developers. We only limit app metrics (MAU, storage and bandwidth) to each organization.
See [Teams](https://capgo.app/pricing/) for more information.
### Does Capgo store my source code?[](https://capgo.app/docs/faq/#does-capgo-store-my-source-code "Direct link to Does Capgo store my source code?")
[Section titled âDoes Capgo store my source code?â](#does-capgo-store-my-source-code)
No. Capgo servers never see your source code. When you run `npx @capgo/cli@latest bundle upload`, Capgo stores a zip file of the minified/compiled code - the same code that a browser would receive, not your source code.
For additional security, you have two options:
* **End-to-End Encryption**: Encrypt your bundle before uploading to protect it in storage and transit and to prevent third parties from generating valid encrypted updates without your private key. This does not make shipped web assets impossible to reverse engineer because the public key is present in the distributed app.
* **External URL Upload**: Store the bundle on your own server and only provide Capgo with the download link with the option `--external `
See also our privacy policy: [https://capgo.app/privacy](https://capgo.app/privacy/)
### Can I use Capgo from my CI system?[](https://capgo.app/docs/faq/#can-i-use-capgo-from-my-ci-system "Direct link to Can I use Capgo from my CI system?")
[Section titled âCan I use Capgo from my CI system?â](#can-i-use-capgo-from-my-ci-system)
Yes. Capgo is intended to be used from CI systems. Weâve published a guide for [Android and Github Actions](https://capgo.app/blog/automatic-capacitor-android-build-github-action/) and [iOS](https://capgo.app/blog/automatic-capacitor-ios-build-github-action/), and for [GitLab](https://capgo.app/blog/setup-ci-and-cd-in-gitlab/). Other CI systems should be similar.
Please donât hesitate to reach out over GitHub issues or Discord if you encounter any issues.
### How does this relate to Firebase Remote Config or Launch Darkly?[](https://capgo.app/docs/faq/#how-does-this-relate-to-firebase-remote-config-or-launch-darkly "Direct link to How does this relate to Firebase Remote Config or Launch Darkly?")
[Section titled âHow does this relate to Firebase Remote Config or Launch Darkly?â](#how-does-this-relate-to-firebase-remote-config-or-launch-darkly)
Code push allows adding new code / replacing code on the device. Firebase Remote Config and Launch Darkly are both configuration systems. They allow you to change the configuration of your app without having to ship a new version. They are not intended to replace code.
### How big of a dependency footprint does this add?[](https://capgo.app/docs/faq/#how-big-of-a-dependency-footprint-does-this-add "Direct link to How big of a dependency footprint does this add?")
[Section titled âHow big of a dependency footprint does this add?â](#how-big-of-a-dependency-footprint-does-this-add)
I havenât measured recently, but I expect the code push library to add less than one megabyte to Capacitor apps. We know of ways we can make this smaller when that becomes a priority. If size is a blocker for you, please let us know!
### Does Capgo work on the iOS 18.4 Simulator?[](https://capgo.app/docs/faq/#does-capgo-work-on-the-ios-18-4-simulator "Direct link to Does Capgo work on the iOS 18.4 Simulator?")
[Section titled âDoes Capgo work on the iOS 18.4 Simulator?â](#does-capgo-work-on-the-ios-184-simulator)
No. Due to an upstream issue affecting the iOS 18.4 Simulator, Capgo does not run reliably there. Please test on a real device or use a different iOS simulator version.
See details in the React Native issue: [facebook/react-native#50510](https://github.com/facebook/react-native/issues/50510)
### Does code push work with large applications?[](https://capgo.app/docs/faq/#does-code-push-work-with-large-applications "Direct link to Does code push work with large applications?")
[Section titled âDoes code push work with large applications?â](#does-code-push-work-with-large-applications)
Yes. There is no limit on the size of the application that can be updated with code push. As noted [below](https://capgo.app/docs/faq/#what-types-of-changes-does-capgo-code-push-support), Capgo can change any JS code in your application regardless of size.
To note: A bigger size make it harder for users to download updates. We recommend keeping your app as small as possible.
### What can I use Capgo code push for?[](https://capgo.app/docs/faq/#what-can-i-use-capgo-code-push-for "Direct link to What can I use Capgo code push for?")
[Section titled âWhat can I use Capgo code push for?â](#what-can-i-use-capgo-code-push-for)
Weâve seen a variety of uses, including:
* Emergency fixes to production apps.
* Shipping bug fixes to users on older versions of your app.
* Shipping constantly (e.g. every hour).
Note that most app stores prohibit shipping code that changes the behavior of the app in a significant way. Please see [below](https://capgo.app/docs/faq/#how-does-this-relate-to-the-appplay-store-review-process-or-policies) for more information.
### What counts as a âMAUâ for Capgo?[](https://capgo.app/docs/faq/#what-counts-as-a-mau-for-capgo "Direct link to What counts as a \"MAU\" for Capgo?")
[Section titled âWhat counts as a âMAUâ for Capgo?â](#what-counts-as-a-mau-for-capgo)
A MAU is a âMonthly Active Userâ. In Capgoâs context, this actually refers to a Monthly Active Device. We count a MAU as any device that has contacted our servers in the last 30 days. We do not count devices that have not contacted our servers in the last 30 days.
**Important**: Starting from plugin version **v5.10.0**, **v6.25.0** and **v7.25.0**, the deviceID now persists across app reinstalls. Before these versions, each app reinstall would generate a new deviceID and count as a new MAU.
With the current versions:
* DeviceID persists across app reinstalls (stored securely in Keychain on iOS and EncryptedSharedPreferences on Android)
* Updating the app does not create a new Device ID
* During development, if youâre using an older plugin version (< v5.10.0 / v6.25.0 / v7.25.0), each reinstall still creates a new MAU
Note: TestFlight downloads and channel switches in Android may still generate new device registrations depending on your configuration.
> We recommend after first setup, to disable dev devices and emulators to reduce the amount of duplicated devices.
### What canât we use Capgo code push for?[](https://capgo.app/docs/faq/#what-cant-we-use-capgo-code-push-for "Direct link to What can't we use Capgo code push for?")
[Section titled âWhat canât we use Capgo code push for?â](#what-cant-we-use-capgo-code-push-for)
As above, Capgo should not be used to violate app store polices. Please see [below](https://capgo.app/docs/faq/#does-capgo-comply-with-play-store-guidelines) for more information.
Also Capgo does not support changing native code (e.g. Java/Kotlin on Android or Objective-C/Swift on iOS). The tool will warn you during an attempted update if you have changed native code.
### Can I update capacitor.config.ts changes via Capgo?[](https://capgo.app/docs/faq/#can-i-update-capacitorconfigts-changes-via-capgo "Direct link to Can I update capacitor.config.ts changes via Capgo?")
[Section titled âCan I update capacitor.config.ts changes via Capgo?â](#can-i-update-capacitorconfigts-changes-via-capgo)
No. Changes to `capacitor.config.ts` cannot be sent through Capgo live updates. The Capacitor configuration file is read at native build time and compiled into the native app binary. This means any changes to `capacitor.config.ts` (such as plugin configurations, app ID, server settings, or native plugin options) require a new native release through the App Store or Google Play.
Capgo can only update web assets (HTML, CSS, JavaScript) that are loaded at runtime. If you need to change your Capacitor configuration, you must:
1. Update `capacitor.config.ts` locally
2. Rebuild your native app (`npx cap sync` followed by a native build)
3. Submit the new binary to the app stores
### Does Capgo submit to the stores for me?[](https://capgo.app/docs/faq/#does-capgo-submit-to-the-stores-for-me "Direct link to Does Capgo submit to the stores for me?")
[Section titled âDoes Capgo submit to the stores for me?â](#does-capgo-submit-to-the-stores-for-me)
Capgo does not currently support submitting to the app stores on your behalf. We have plans to add this in the future, but for now you will need to continue to use your existing processes to submit to the app stores.
You can use our [CI guide Android](https://capgo.app/blog/automatic-capacitor-android-build-github-action/) to automate this process and [CI guide iOS](https://capgo.app/blog/automatic-capacitor-ios-build-github-action/).
### What does Capgo store on disk and where?[](https://capgo.app/docs/faq/#what-does-capgo-store-on-disk-and-where "Direct link to What does Capgo store on disk and where?")
[Section titled âWhat does Capgo store on disk and where?â](#what-does-capgo-store-on-disk-and-where)
The Capgo updater (included in your application when you build your app) caches the latest downloaded bundle in the only directory that capacitor allow to load code. On Android, this is located in `/data/user/0/com.example.app/code_cache/capgo_updater` although the base of that path is provided by the Android system and can change dynamically at runtime. On iOS devices, data is stored under `Library/Application Support/capgo`.
The Capgo command line tools (e.g. `npx @capgo/cli@latest bundle upload`) are installed on disk in npm caches, your logins are stored in your home directory in `~/.capgo`.
### How does this relate to Capacitor Hot Reload?[](https://capgo.app/docs/faq/#how-does-this-relate-to-capacitor-hot-reload "Direct link to How does this relate to Capacitor Hot Reload?")
[Section titled âHow does this relate to Capacitor Hot Reload?â](#how-does-this-relate-to-capacitor-hot-reload)
Capacitorâs Hot reload is a development-time-only feature. Code push is for production.
Hot reload is a feature of Capacitor that allows you to change code on the device during development. It requires building the Capacitor app with a proxy to connect to your local machine.
Code push is a feature that allows you to change code on the device in production. We will use a variety of different techniques to make this possible depending on the platform.
### What types of changes does Capgo code push support?[](https://capgo.app/docs/faq/#what-types-of-changes-does-capgo-code-push-support "Direct link to What types of changes does Capgo code push support?")
[Section titled âWhat types of changes does Capgo code push support?â](#what-types-of-changes-does-capgo-code-push-support)
Capgo can change any JS code in your application. This includes app code and generated code. You can also update dependencies in `package.json` as long as they donât require native code changes.
We do not have plans to support changing native code (e.g. Java/Kotlin on Android or Objective-C/Swift on iOS), and the tool will warn you if it detects that you have changed native code as it will not be included in the bundle.
### Does this support Web?[](https://capgo.app/docs/faq/#does-this-support-web "Direct link to Does this support Web?")
[Section titled âDoes this support Web?â](#does-this-support-web)
Code push isnât needed for web as the web already works this way. When a user opens a web app it downloads the latest version from the server if needed.
If you have a use case for code push with web, weâd love to know!
### Will this work on iOS, Android, Mac, Windows, Linux, etc?[](https://capgo.app/docs/faq/#will-this-work-on-ios-android-mac-windows-linux-etc "Direct link to Will this work on iOS, Android, Mac, Windows, Linux, etc?")
[Section titled âWill this work on iOS, Android, Mac, Windows, Linux, etc?â](#will-this-work-on-ios-android-mac-windows-linux-etc)
Yes.
So far weâve focused on Android, iOS, and Electron support, and code push is production-ready on all three.
### What OS versions does Capgo support?[](https://capgo.app/docs/faq/#what-os-versions-does-capgo-support "Direct link to What OS versions does Capgo support?")
[Section titled âWhat OS versions does Capgo support?â](#what-os-versions-does-capgo-support)
Capgo supports the same versions of Android that Capacitor supports.
Capacitor currently supports Android API level 22+ and iOS 13.0+: [https://capacitorjs.com/docs/main/reference/support-policy](https://capacitorjs.com/docs/main/reference/support-policy/)
### What versions of Capacitor does Capgo support?[](https://capgo.app/docs/faq/#what-versions-of-capacitor-does-capgo-support "Direct link to What versions of Capacitor does Capgo support?")
[Section titled âWhat versions of Capacitor does Capgo support?â](#what-versions-of-capacitor-does-capgo-support)
Capgo currently supports only recent stable releases of Capacitor. We could support older versions of Capacitor as well, we just havenât built out the infrastructure necessary to maintain such over time. We intend to support more versions of Capacitor in the future, including any version for our enterprise customers. [https://github.com/Cap-go/capgo/issues/1100](https://github.com/Cap-go/capgo/issues/1100/)
Capgo tracks Capacitor stable and generally updates within a few hours of any stable release. Our system for doing these updates is automated takes a few minutes to run. We then do an extra manual verification step before publishing to our servers.
### How does this relate to the App/Play Store review process or policies?[](https://capgo.app/docs/faq/#how-does-this-relate-to-the-appplay-store-review-process-or-policies "Direct link to How does this relate to the App/Play Store review process or policies?")
[Section titled âHow does this relate to the App/Play Store review process or policies?â](#how-does-this-relate-to-the-appplay-store-review-process-or-policies)
Developers are bound by their agreements with store providers when they choose to use those stores. Code push is designed to allow developers to update their apps and still comply with store policies on iOS, Android, and Electron delivery channels. Similar to the variety of commercial products available to do so with React Native (e.g. [Microsoft](https://appcenter.ms/), [Expo](https://expo.dev/)).
Microsoft also publishes a guide on how their solution complies with the app stores: [https://github.com/microsoft/react-native-code-push#store-guideline-compliance](https://github.com/microsoft/react-native-code-push/#store-guideline-compliance)
Code push is a widely used technique throughout the app stores. All of the large apps Iâm aware of use code push. The major policy to be aware of is not to change the behavior of the app in a significant way. Please see [below](https://capgo.app/docs/faq/#does-capgo-comply-with-play-store-guidelines) for more information.
### Does Capgo comply with Play Store guidelines?[](https://capgo.app/docs/faq/#does-capgo-comply-with-play-store-guidelines "Direct link to Does Capgo comply with Play Store guidelines?")
[Section titled âDoes Capgo comply with Play Store guidelines?â](#does-capgo-comply-with-play-store-guidelines)
Yes.
The Play Store offers two restrictions relating to update tools.
1. Updates must use an interpreter or virtual machine (Capgo uses JavaScript in a WebView). [https://support.google.com/googleplay/android-developer/answer/9888379?hl=en](https://support.google.com/googleplay/android-developer/answer/9888379/?hl=en)
```plaintext
An app distributed via Google Play may not modify, replace, or update itself
using any method other than Google Play's update mechanism. Likewise, an app
may not download executable code (such as dex, JAR, .so files) from a
source other than Google Play. *This restriction does not apply to code
that runs in a virtual machine or an interpreter* where either provides
indirect access to Android APIs (such as JavaScript in a webview or
browser).
Apps or third-party code, like SDKs, with interpreted languages (JavaScript,
Python, Lua, etc.) loaded at run time (for example, not packaged with the
app) must not allow potential violations of Google Play policies.
```
2. Changes to the app must not be deceptive (e.g. changing the purpose of the app via update). [https://support.google.com/googleplay/android-developer/answer/9888077](https://support.google.com/googleplay/android-developer/answer/9888077/) Please be clear with your users about what you are providing with your application and do not violate their expectations with significant behavioral changes through the use of Capgo.
Capgo is designed to be compatible with the Play Store guidelines. However Capgo is a tool, and as with any tool, can be abused. Deliberately abusing Capgo to violate Play Store guidelines is in violation of the Capgo [Terms of Service](https://capgo.app/tos/) and can result in termination of your account.
Finally, code push services are widely used in the industry (all of the large apps Iâm aware of use them) and there are multiple other code push services publicly available (e.g. expo.dev & appcenter.ms). This is a well trodden path.
Microsoft also publishes a guide on how their react native âcodepushâ library complies with the app stores: [https://github.com/microsoft/react-native-code-push#store-guideline-compliance](https://github.com/microsoft/react-native-code-push/#store-guideline-compliance)
### Does Capgo comply with App Store guidelines?[](https://capgo.app/docs/faq/#does-capgo-comply-with-app-store-guidelines "Direct link to Does Capgo comply with App Store guidelines?")
[Section titled âDoes Capgo comply with App Store guidelines?â](#does-capgo-comply-with-app-store-guidelines)
Yes.
Similar to the Play Store, the App Store offers both technical and policy restrictions.
```plaintext
3.2.2
... interpreted code may be downloaded to an Application but only so long as
such code:
(a) does not change the primary purpose of the Application by providing
features or functionality that are inconsistent with the intended and
advertised purpose of the Application as submitted to the App Store,
(b) does not create a store or storefront for other code or applications, and
(c) does not bypass signing, sandbox, or other security features of the OS.
```
Capgo uses JavaScript in a WebView to comply with the interpreter-only restriction for updates on iOS. So long as your application is not engaging in deceptive behavior via updates (e.g. changing the purpose of the app via update), updating via Capgo (or any other code push solution) is standard industry practice and compliant with App Store guidelines.
Deliberately abusing Capgo to violate App Store guidelines is in violation of the Capgo [Terms of Service](https://capgo.app/tos/) and can result in termination of your account.
Microsoft also publishes a guide on how their react native âcodepushâ library complies with the app stores: [https://github.com/microsoft/react-native-code-push#store-guideline-compliance](https://github.com/microsoft/react-native-code-push/#store-guideline-compliance)
### Can I use Capgo in my country?[](https://capgo.app/docs/faq/#can-i-use-capgo-in-my-country "Direct link to Can I use Capgo in my country?")
[Section titled âCan I use Capgo in my country?â](#can-i-use-capgo-in-my-country)
We have not attempted to restrict access to Capgo from any country.
We recognize that some countries have restrictions on what urls can be accessed from within the country. Capgo currently uses Cloudflare Cloud for hosting, including R2 Storage and Cloudflare workers.
The following URLs are used by Capgo:
* [https://api.capgo.app](https://api.capgo.app/) â used by the `npx @capgo/cli` command line tools to interact with the Capgo servers as well as the Capgo updater on usersâ devices to check for updates.
* [https://\*.r2.cloudflarestorage.com](https://*.r2.cloudflarestorage.com/) â used by the `npx @capgo/cli` command line tool to upload and download bundle
If all of those URLs are accessible from your country, then Capgo should work.
If your region requires blocking access to any of those URLs, please let us know and we can work with you to find a solution. Proxy servers are one option.
### Can I self-host Capgo?[](https://capgo.app/docs/faq/#can-i-self-host-capgo "Direct link to Can I self-host Capgo?")
[Section titled âCan I self-host Capgo?â](#can-i-self-host-capgo)
Yes, you can self-host Capgo. The guide is not yet written, but the code is open source and available at [https://github.com/cap-go/capgo](https://github.com/cap-go/capgo/)
### Does code push require the internet to work?[](https://capgo.app/docs/faq/#does-code-push-require-the-internet-to-work "Direct link to Does code push require the internet to work?")
[Section titled âDoes code push require the internet to work?â](#does-code-push-require-the-internet-to-work)
Yes. One could imagine running a server to distribute the updates separately from the general internet, but some form of network connectivity is required to transport updates to the devices.
### How is Capgo affected by lack of network connectivity?[](https://capgo.app/docs/faq/#how-is-capgo-affected-by-lack-of-network-connectivity "Direct link to How is Capgo affected by lack of network connectivity?")
[Section titled âHow is Capgo affected by lack of network connectivity?â](#how-is-capgo-affected-by-lack-of-network-connectivity)
Capgo updater (included in your application when you build your app with Capgo) is designed to be resilient to network connectivity issues.
In the default update behavior, when the application launches it alerts the Capgo updater, which spawns a separate thread to make a network request to Capgoâs servers and ask for an update. We intentionally use a separate thread to avoid affecting blocking anything else the application might be doing. If the network request fails or times out, the updater will simply try to check again next time the application launches.
Capgo command line tools (e.g. `npx @capgo/cli@latest bundle upload`) require network connectivity to function. If you are using Capgo to distribute your app, you should ensure that your CI system has network connectivity.
### What happens if a user doesnât update for a long time and misses an update?[](https://capgo.app/docs/faq/#what-happens-if-a-user-doesnt-update-for-a-long-time-and-misses-an-update "Direct link to What happens if a user doesn't update for a long time and misses an update?")
[Section titled âWhat happens if a user doesnât update for a long time and misses an update?â](#what-happens-if-a-user-doesnt-update-for-a-long-time-and-misses-an-update)
Our implementation always sends an update specifically tailored for the device that is requesting it updating the requestor always to the latest version available. Thus if a user doesnât update for a while they will âmissâ intermediate updates.
The update server could be changed to support responding with either the next incremental version or the latest version depending on your applicationâs needs. Please let us know if alternative update behaviors are important to you.
### How does Capgo relate to Capacitor?[](https://capgo.app/docs/faq/#how-does-capgo-relate-to-capacitor "Direct link to How does Capgo relate to Capacitor?")
[Section titled âHow does Capgo relate to Capacitor?â](#how-does-capgo-relate-to-capacitor)
Capgo is a plugin for Capacitor that adds code push. Capgo is not a replacement for Capacitor. You can continue to use the Capacitor tooling you already know and love.
We track the latest stable release of Capacitor and update our code push plugin to work with it.
### When do updates happen?[](https://capgo.app/docs/faq/#when-do-updates-happen "Direct link to When do updates happen?")
[Section titled âWhen do updates happen?â](#when-do-updates-happen)
By default, the Capgo updater checks for updates on app startup. It runs on a background thread and does not block the UI thread. Any updates will be installed while the user is using the app and will be applied the next time the app is restarted.
It is also possible to run the Capgo updater manually using the `@capgo/capacitor-updater` package, through which it is possible to trigger updates at any time, including via a push notification.
The Capgo updater is designed such that when the network is not available, or the server is down or otherwise unreachable, the app will continue to run as normal. Should you ever choose to delete an update from our servers, all your clients will continue to run as normal.
We have added the ability to rollback patches. The simplest thing is to simply attach a previous bundle to your channel to undo.
### Do I need to keep my app\_id secret?[](https://capgo.app/docs/faq/#do-i-need-to-keep-my-app_id-secret "Direct link to Do I need to keep my app_id secret?")
[Section titled âDo I need to keep my app\_id secret?â](#do-i-need-to-keep-my-app_id-secret)
No. The `app_id` is included in your app and is safe to be public. You can check it into version control (even publicly) and not worry about someone else accessing it.
Someone who has your `app_id` can fetch the latest version of your app from Capgo servers, but they cannot push updates to your app or access any other aspect of your Capgo account.
### What information is sent to Capgo servers?[](https://capgo.app/docs/faq/#what-information-is-sent-to-capgo-servers "Direct link to What information is sent to Capgo servers?")
[Section titled âWhat information is sent to Capgo servers?â](#what-information-is-sent-to-capgo-servers)
Although Capgo connects to the network, it does not send any personally identifiable information. Including Capgo should not affect your declarations for the Play Store or App Store.
Requests sent from the app to Capgo servers include:
* app\_id (specified `capacitor.config.json`)
* channel (optional in `capacitor.config.json`)
* release\_version (versionName from AndroidManifest.xml or CFBundleShortVersionString from Info.plist or `capacitor.config.json` if set in [`CapacitorUpdater.version`](/docs/plugins/updater/settings/#version) )
* version\_number (generated as part of `npx @capgo/cli@latest bundle upload`)
* os\_version (e.g. â11.2.1â)
* platform (e.g. âandroidâ, needed to send down the right patch) Thatâs it. The code for this is in `updater/library/src/network.rs`
* device\_id (generated on the device on first run, used to de-duplicate per-device installs and allow us to charge based on users installed to (e.g. monthly active users), rather than total patches or total patch installs)
* custom\_id ( optional, set at runtime by the developer, used for you to link a device to a user in your system)
### What platforms does Capgo support?[](https://capgo.app/docs/faq/#what-platforms-does-capgo-support "Direct link to What platforms does Capgo support?")
[Section titled âWhat platforms does Capgo support?â](#what-platforms-does-capgo-support)
Currently, Capgo supports Android, iOS, and Electron. All are production-ready.
Use of Capgo for iOS, Android, or Electron can be independent decisions. You can set your channel strategy for Android and an ipa built to the App Store, or Electron channels, as needed.
Capgo can (relatively easily) be made to support desktop or embedded targets. If those are important to you, please let us know.
### How does Capgo interact with Play Testing Tracks or Apple TestFlight?[](https://capgo.app/docs/faq/#how-does-capgo-interact-with-play-testing-tracks-or-apple-testflight "Direct link to How does Capgo interact with Play Testing Tracks or Apple TestFlight?")
[Section titled âHow does Capgo interact with Play Testing Tracks or Apple TestFlight?â](#how-does-capgo-interact-with-play-testing-tracks-or-apple-testflight)
Each of the app stores have separate mechanisms for distributing apps to limited groups of users (e.g. âinternal testingâ, âclosed betaâ, etc.). These are all mechanisms for segmenting your users into groups and distributing specific versions of your apps to each.
Unfortunately, these not all of these mechanisms allow 3rd parties to detect when apps are installed in any specific Test Track or via TestFlight. Thus, we do not have reliable visibility into composition of these groups, and cannot reliably gate access to Capgo patches based on these groups. [https://stackoverflow.com/questions/53291007/can-an-android-application-identify-the-test-track-within-google-play](https://stackoverflow.com/questions/53291007/can-an-android-application-identify-the-test-track-within-google-play/) [https://stackoverflow.com/questions/26081543/how-to-tell-at-runtime-whether-an-ios-app-is-running-through-a-testflight-beta-i](https://stackoverflow.com/questions/26081543/how-to-tell-at-runtime-whether-an-ios-app-is-running-through-a-testflight-beta-i/)
If youâd like to segment availability of Capgo bundle, there are 4 potential options:
1. Use separate channel for each group. This is the most straightforward approach, but requires you to manage multiple channels. You may already have a dev channels and prod channels with different availability. You can thus update your dev channels, verify it and then separately update your prod channels. We recommend using branches / tags in your version control to help keep track of the sources associated with each release.
2. Track your own set of opt-in users, disable automatic updates, and trigger updates only for certain users via the `@capgo/capacitor-updater` package. This works today, but requires you to manage your own opt-in list.
3. Capgo allow creare its own opt-in mechanism on a per-device basis (similar to Test Tracks or TestFlight, just platform agnostic). This allow your QA team to opt-in to bundle before theyâre promoted to the general public.
4. Capgo have percentage based rollouts. This does not let you choose which devices to send to, but can help you roll out incrementally and roll-back on sight of any problems.
## Billing[](https://capgo.app/docs/faq/#billing "Direct link to Billing")
[Section titled âBillingâ](#billing)
### How do I upgrade or downgrade my plan?[](https://capgo.app/docs/faq/#how-do-i-upgrade-or-downgrade-my-plan "Direct link to How do I upgrade or downgrade my plan?")
[Section titled âHow do I upgrade or downgrade my plan?â](#how-do-i-upgrade-or-downgrade-my-plan)
You can upgrade or downgrade your plan at any time in your dashboard: [https://console.capgo.app/settings/organization/plans](https://console.capgo.app/settings/organization/plans/)
### When does my billing period reset?[](https://capgo.app/docs/faq/#when-does-my-billing-period-reset "Direct link to When does my billing period reset?")
[Section titled âWhen does my billing period reset?â](#when-does-my-billing-period-reset)
Billing periods are reset automatically every month on the month you first subscribed to Capgo. For example, if you subscribed on the 15th of the month, your billing period will reset on the 15th of every month.
### How do I cancel my subscription?[](https://capgo.app/docs/faq/#how-do-i-cancel-my-subscription "Direct link to How do I cancel my subscription?")
[Section titled âHow do I cancel my subscription?â](#how-do-i-cancel-my-subscription)
You can cancel your subscription at any time in your dashboard: [https://console.capgo.app/settings/organization/plans](https://console.capgo.app/settings/organization/plans/)
### Can I pay for a year in advance?[](https://capgo.app/docs/faq/#can-i-pay-for-a-year-in-advance "Direct link to Can I pay for a year in advance?")
[Section titled âCan I pay for a year in advance?â](#can-i-pay-for-a-year-in-advance)
Yes you can can at any time in your dashboard: [https://console.capgo.app/settings/organization/plans](https://console.capgo.app/settings/organization/plans/)
### Stats and analytics[](https://capgo.app/docs/faq/#stats-and-analytics "Direct link to Stats and analytics")
[Section titled âStats and analyticsâ](#stats-and-analytics)
The stats in your dashboard are updated every midnight UTC. The stats are calculated based on the number of [MAU](https://capgo.app/docs/faq/#what-is-the-difference-between-a-bundle-and-a-release "Direct link to What is the difference between a bundle and a release?") that have been installed on your devices.
## How device ID is generated[](https://capgo.app/docs/faq/#how-device-id-is-generated "Direct link to How device ID is generated")
[Section titled âHow device ID is generatedâ](#how-device-id-is-generated)
The device ID is generated on the device on first run, and is used to de-duplicate per-device installs and allow us to charge based on users installed to (e.g. monthly active users), rather than total patches or total patch installs.
MAU is a better solution than number of installs to price Capgo, as it is more accurate and reflects the actual cost of Capgo per device.
**DeviceID Persistence (Updated in v6.25.0 and v7.25.0)**:
* **Current behavior**: The deviceID now persists across app reinstalls. It is stored securely in the deviceâs Keychain (iOS) or EncryptedSharedPreferences (Android), allowing us to track the same device even after uninstall/reinstall.
* **Previous behavior** (before v6.25.0/v7.25.0): For privacy reasons related to Apple and Google store policies, the deviceID was reset on each app reinstall, making it impossible to track the same device across reinstalls.
The privacy rules are enforced by Apple and Google, and Capgoâs implementation complies with their best practices for device identification.
Device ID will not be listed in your device list until they get their first patch installed.
## Why my device number is different than my MAU?[](https://capgo.app/docs/faq/#why-my-device-number-is-different-than-my-mau "Direct link to Why my device number is different than my MAU?")
[Section titled âWhy my device number is different than my MAU?â](#why-my-device-number-is-different-than-my-mau)
Currently, the device list is not updated as often as the MAU.
The device list is updated only when a device installs an update.
While the MAU is updated at every app launch. This is a current limitation of the platform. Our Analytics platform do not support raw updates so we use conventional database for Devices list.
To limit the number of database queries, we do update row only on app update.
This limitation will be removed in the future.
## How to have different update by platform?[](https://capgo.app/docs/faq/#how-to-have-different-update-by-platform "Direct link to How to have different update by platform?")
[Section titled âHow to have different update by platform?â](#how-to-have-different-update-by-platform)
You can create a channel for each platform. and disable platform specific updates in each channel.
On ios channel disable android updates and on android channel disable ios updates.
Then upload a bundle to each channel to have different update for each platform.
If you need to have the same update for both platform, you can link one bundle to multiple channels. No need to duplicate the bundle.
# Tech support for Capgo
> How to get tech support for Capgo and our updater, please follow this guide to get help when the doc and our articles are not enough
## Support by discord
[Section titled âSupport by discordâ](#support-by-discord)
Capgo has an official [discord server](https://discord.capgo.app). Getting tech support there is likely one of the fastest ways to get a response.
Here is a crash course:
Step 1 - go to the `questions` channel

Step 2 - create your thread

Step 3 - Describe your problem and select the relevant tags

Step 4 - Share your secure account id (optional)
This will allow the capgo staff to take a look at your account. Sharing this id is safe, as it was designed to be shared publicly.
To share this, please go to [capgoâs settings](https://console.capgo.app/dashboard/settings/account/). There please click on `copy account id`.

This will copy the secure account id to the clipboard. Please include that in your discord post.
## Support by email
[Section titled âSupport by emailâ](#support-by-email)
This is the slowest way to get support. Please use the discord server first.
If you need to contact us by email, please send an email to .
# Add an App
> Add an app to your Capgo account, and install the plugin in your app
## Requirements
[Section titled âRequirementsâ](#requirements)
Before getting started with Capgo, make sure you have:
* A Capacitor app installed and configured. [Learn how to set up Capacitor](https://capacitorjs.com/docs/getting-started/)
* Node.js 20 or later installed
* One of the following development environments:
* **macOS** with Xcode (for iOS development) and/or Android Studio (for Android development)
* **Linux** with Android Studio (for Android development)
* **Windows** with Android Studio (for Android development)
## Introduction to Capgo
[Section titled âIntroduction to Capgoâ](#introduction-to-capgo)
[Capgo in 15 min](https://www.youtube-nocookie.com/embed/NzXXKoyhTIo)
## Live updates are 3 step away
[Section titled âLive updates are 3 step awayâ](#live-updates-are-3-step-away)
### Guided setup
[Section titled âGuided setupâ](#guided-setup)
1. Create your account at . 
2. Use the Init commands to get started
```bash
npx @capgo/cli@latest init [APIKEY]
```
You will be presented with a series of questions. Provide the necessary answers to complete the automated setup.
3. Deploy a live update
Tip
By following these steps, youâll be up and running in no time. If you need any further assistance during the process, our support team is [here to help](https://support.capgo.app). Happy onboarding!
[Detailed Onboarding Guide ](/docs/getting-started/onboarding/)See the complete step-by-step guide for the CLI onboarding process
[Deploy a live update ](/docs/getting-started/deploy/)Learn how to deploy a live update to your app
### Manual setup
[Section titled âManual setupâ](#manual-setup)
In case the init command doesnât work for you, you can manually add an app.
1. Connect the CLI to your account:
```bash
npx @capgo/cli@latest login [APIKEY]
```
2. Add the app to your account with this command:
```bash
npx @capgo/cli@latest app add [APP_NAME]
```
3. Install the plugin in your app:
```bash
npm i @capgo/capacitor-updater
```
4. Configure the plugin in your `capacitor.config`
```json
{
"plugins": {
CapacitorUpdater: {
"appId": "Your appID",
"autoUpdate": true,
"version": "1.0.0"
}
}
}
```
[See all available options](/docs/plugins/updater/settings/). This information will be inferred if not provided.
5. Call the init method as early as possible in your app:
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater';
CapacitorUpdater.notifyAppReady();
```
6. Deploy a live update
Installing for older Capacitor versions
The command above (step 3) installs the latest version (v8.x) for Capacitor 8. For older Capacitor versions, use the appropriate npm tag:
```bash
# Capacitor 7
npm i @capgo/capacitor-updater@lts-v7
# Capacitor 6
npm i @capgo/capacitor-updater@lts-v6
# Capacitor 5
npm i @capgo/capacitor-updater@lts-v5
```
Each plugin major version matches the Capacitor major version (v8 â Capacitor 8, v7 â Capacitor 7, v6 â Capacitor 6, v5 â Capacitor 5). Minor versions share the same feature set across all major versions (e.g., 5.34.0, 6.34.0, 7.34.0, and 8.34.0 all include the same features).
# CI/CD Integration
> Integrating Capgo into your CI/CD pipeline allows you to fully automate the process of building and deploying updates to your app. By leveraging the Capgo CLI and semantic-release, you can ensure consistent, reliable deployments and enable rapid iteration.
Integrating Capgo into your CI/CD pipeline allows you to fully automate the process of building and deploying updates to your app. By leveraging the Capgo CLI and semantic-release, you can ensure consistent, reliable deployments and enable rapid iteration.
## Benefits of CI/CD Integration
[Section titled âBenefits of CI/CD Integrationâ](#benefits-of-cicd-integration)
* **Automation**: No more manual steps or room for human error. Your entire build, test, and deployment process can be automated from end to end.
* **Consistency**: Every deployment follows the same set of steps, ensuring a predictable and repeatable process. This is especially valuable when you have multiple team members contributing code.
* **Faster iterations**: With automated deployments, you can ship updates more frequently and with confidence. No more waiting for manual QA or release approvals.
## Capgo CLI
[Section titled âCapgo CLIâ](#capgo-cli)
The Capgo CLI is the key to integrating Capgo into your CI/CD workflow. It provides commands for pushing new bundle versions, managing channels, and more.
The most important command for CI/CD integration is `bundle upload`:
```shell
npx @capgo/cli@latest bundle upload --channel Production --apikey YOUR_API_KEY
```
If you use encryption you should provide it from one of these ways:
**Using a private key file path:**
```shell
npx @capgo/cli@latest bundle upload --channel Production --apikey YOUR_API_KEY --key-v2 PRIVATE_KEY_PATH
```
**Using the private key content directly (recommended for CI/CD):**
```shell
npx @capgo/cli@latest bundle upload --channel Production --apikey YOUR_API_KEY --key-data-v2 PRIVATE_KEY_CONTENT
```
**Using environment variables (best practice for CI/CD):**
```shell
npx @capgo/cli@latest bundle upload --channel Production --apikey YOUR_API_KEY --key-data-v2 "$CAPGO_PRIVATE_KEY"
```
### Setting up Environment Variables for Encryption
[Section titled âSetting up Environment Variables for Encryptionâ](#setting-up-environment-variables-for-encryption)
For CI/CD environments, itâs recommended to store your private key as an environment variable rather than a file. Hereâs how to set it up:
1. **Get your private key content:**
```shell
cat .capgo_key_v2 | pbcopy
```
This copies the key content to your clipboard.
2. **Add it to your CI/CD environment:**
* **GitHub Actions**: Add `CAPGO_PRIVATE_KEY` to your repository secrets
* **GitLab CI**: Add it as a masked variable in your project settings
* **CircleCI**: Add it as an environment variable in your project settings
* **Jenkins**: Add it as a secret text credential
3. **Use it in your pipeline:**
```yaml
- run: npx @capgo/cli@latest bundle upload --channel=production --apikey=${{ secrets.CAPGO_API_KEY }} --key-data-v2 "${{ secrets.CAPGO_PRIVATE_KEY }}"
```
**Note**: The `--key-data-v2` flag allows you to pass the private key content directly as a string, making it perfect for environment variables in CI/CD pipelines where you donât want to create temporary files.
This command uploads the current web build to the specified channel. Youâll typically run this as the last step in your CI/CD pipeline, after your web build has completed successfully.
## Setting up Capgo in your CI/CD Pipeline
[Section titled âSetting up Capgo in your CI/CD Pipelineâ](#setting-up-capgo-in-your-cicd-pipeline)
While the exact steps will vary depending on your CI/CD tool of choice, the general process for integrating Capgo looks like this:
1. **Generate an API key**: Log in to the Capgo dashboard and create a new API key. This key will be used to authenticate the CLI in your CI/CD environment. Keep it secret and never commit it to your repository!
2. **Configure the `bundle upload` command**: Add a step to your CI/CD configuration that runs the `bundle upload` command with the appropriate arguments:
upload.yml
```yaml
- run: npx @capgo/cli@latest bundle upload --channel=production --apikey=${{ secrets.CAPGO_API_KEY }}
```
\n Replace `Production` with the channel you want to deploy to, `${{ secrets.CAPGO_API_KEY }}` with the environment variable holding your API key, and add `--key-data-v2 "${{ secrets.CAPGO_PRIVATE_KEY }}"` if using encryption.
3. **Add the `upload` step after your web build**: Ensure that the `upload` step comes after your web build has completed successfully. This ensures youâre always deploying your latest code.\n Hereâs an example configuration for GitHub Actions:\n
upload.yml
```yaml
name: Deploy to Capgo
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '24'
- run: npm ci
- run: npm run build
- run: npm install -g @capgo/cli
- run: npx @capgo/cli@latest bundle upload --channel=production --apikey=${{ secrets.CAPGO_API_KEY }} --key-data-v2 "${{ secrets.CAPGO_PRIVATE_KEY }}"
```
## Version Management with Semantic-release
[Section titled âVersion Management with Semantic-releaseâ](#version-management-with-semantic-release)
The recommended way to handle versioning with Capgo is to set the version in your `capacitor.config.ts` file by importing it from `package.json`:
```ts
import pkg from './package.json'
const config: CapacitorConfig = {
// ... other config
plugins: {
CapacitorUpdater: {
version: pkg.version,
}
}
}
```
This approach allows you to:
1. Use semantic-release (or any other tool) to update the `package.json` version
2. Build your app with the updated version automatically included
3. Upload the bundle with the correct version
Your CI/CD workflow would look like this:
```yaml
- run: npm ci
- run: npx semantic-release # Updates package.json version
- run: npm run build # Builds with new version from capacitor.config
- run: npx @capgo/cli@latest bundle upload --channel=production --apikey=${{ secrets.CAPGO_API_KEY }}
```
Hereâs a sample `.releaserc` configuration file for semantic-release:
```json
{
"branches": [
"main",
{
"name": "beta",
"prerelease": true
}
],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/changelog",
[
"@semantic-release/git",
{
"assets": ["CHANGELOG.md", "package.json"],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
]
]
}
```
This configuration does the following:
1. Analyzes commit messages to determine the next version number, following the Conventional Commits spec.
2. Generates release notes based on the commits since the last release.
3. Updates the `CHANGELOG.md` file with the new release notes.
4. Updates the `package.json` version, which will be picked up by your capacitor.config.
5. Commits the updated `CHANGELOG.md`, `package.json`, and any other changed files back to the repository.
Make sure to run semantic-release before building your app so that the updated version from `package.json` is included in your build through the capacitor.config.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
If you encounter issues with your Capgo CI/CD integration, here are a few things to check:
* **API key**: Ensure your API key is valid and has the necessary permissions. If using an environment variable, double check that itâs set correctly.
* **CLI version**: Make sure youâre using the latest version of the Capgo CLI. Older versions may have compatibility issues or lack certain features.
* **Build artifacts**: Confirm that your web build is generating the expected output files. The Capgo CLI needs a valid web build to create a bundle.
* **Network connectivity**: Check that your CI/CD environment has network access to the Capgo servers. Firewall or proxy issues can sometimes interfere with the `upload` command.
If youâre still having trouble, reach out to Capgo support for assistance. They can help troubleshoot any issues with your specific setup.
## Conclusion
[Section titled âConclusionâ](#conclusion)
Integrating Capgo into your CI/CD pipeline with proper version management can greatly streamline your development workflow. By automating your deployments and versioning through the capacitor.config approach, you can ship updates faster and with more confidence.
The recommended approach of setting the version in your `capacitor.config.ts` file and using semantic-release to update `package.json` provides a robust and reliable deployment process that allows you to focus on building great features rather than worrying about manual release steps.
For more details on the Capgo CLI commands and options, check out the [CLI reference](/docs/cli/overview). And for a deeper dive into semantic-release configuration, see the [semantic-release docs](https://github.com/semantic-release/semantic-release).
Happy deploying!
# Deploy a Live Update
> Learn how to deploy a live update to your app using Capgo's Live Updates feature, enabling real-time UI and logic updates without app store resubmission.
Use Capgoâs Live Updates feature to update the UI and business logic of your app remotely, in real-time. Push JS bundle updates directly to your users without going through the app store to instantly fix bugs and ship new features.
This guide assumes youâve completed the [Capgo Quickstart](/docs/getting-started/quickstart) and have already:
1. Installed the `@capgo/capacitor-updater` SDK in your Capacitor app
2. Configured your app ID and update channel in `capacitor.config.ts`
3. Added in your code the `CapacitorUpdater.notifyAppReady()` method
If you havenât done those steps yet, please go back and complete the quickstart first.
[Add an app ](/docs/getting-started/add-an-app/)Add an app to your Capgo account, and install the plugin in your app
## Uploading a Bundle
[Section titled âUploading a Bundleâ](#uploading-a-bundle)
With the Capgo SDK installed and configured, youâre ready to upload your first live update bundle:
1. Build your web assets:
```shell
npm run build
```
2. Upload the bundle to Capgo:
* Console
```shell
npx @capgo/cli@latest bundle upload --channel=production
```
* Github Actions
.github/workflows/build\_and\_deploy.yml
```yml
name: Build source code and send to Capgo
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
push:
branches:
- main
jobs:
deploy_to_capgo:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '24'
- name: Install dependencies
run: npm install
- name: Build
run: npm run build
- name: Deploy to Capgo
run: npx @capgo/cli@latest bundle upload -a ${{ secrets.CAPGO_TOKEN }} --channel ${{ env.CHANNEL }}
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
```
* Gitlab
.gitlab-ci.yml
```yml
stages:
- build
build:
stage: build
image: node:18
cache:
- key:
files:
- package-lock.json
paths:
- .node_modules/
script:
- npm install
- npm run build
- npx @capgo/cli@latest bundle upload -a $CAPGO_TOKEN --channel $CAPGO_CHANNEL
artifacts:
paths:
- node_modules/
- dist/
only:
- master
```
This will upload a new bundle version to the channel specified in the command.
### Troubleshooting Uploads
[Section titled âTroubleshooting Uploadsâ](#troubleshooting-uploads)
If your upload fails, double check:
* Your app ID in `capacitor.config.ts` matches your app in the Capgo dashboard
* Youâre running the upload command from the root of your Capacitor project
* Your web assets are built and up to date
If youâre still having trouble, go to the [Troubleshooting](/docs/getting-started/troubleshooting/) section.
## Receiving an Update on a Device
[Section titled âReceiving an Update on a Deviceâ](#receiving-an-update-on-a-device)
Once your bundle is uploaded, you can test the live update on a device:
1. Sync your app to the device:
```shell
npx cap sync ios
```
2. Open another terminal and run the following command to check the update status:
```shell
npx @capgo/cli@latest app debug
```
3. Run your app locally:
```shell
npx cap run ios
```
Or open the iOS/Android project in Xcode/Android Studio and do a native run.
4. Keep the app open for about 30 seconds to allow the update to download in the background.
5. The logs will take a few seconds to update and show the update status.
6. Close and reopen the app. You should see your live update applied!
Refer back to the [Capgo Quickstart](/docs/getting-started/quickstart#receiving-a-live-update-on-a-device) for more details on testing live updates.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
Congrats on deploying your first live update with Capgo! đ
To learn more, review the rest of the [Capgo Live Updates documentation](/docs/live-updates). Some key topics to check out next:
* [Targeting Updates with Channels](/docs/live-updates/channels)
* [Customizing Update Behavior](/docs/live-updates/update-behavior)
* [Live Update Rollbacks](/docs/live-updates/rollbacks)
# CLI Onboarding Guide
> Complete step-by-step guide to onboard your app with Capgo using the interactive CLI
## Quick Overview
[Section titled âQuick Overviewâ](#quick-overview)
The Capgo CLI provides an interactive onboarding that sets up live updates for your Capacitor app. Youâll:
1. â Register your app in Capgo
2. đ Install and configure the updater plugin
3. đ Deploy your first live update
4. đą Test the update on your device
**Estimated time:** 10-20 minutes (varies based on your internet speed and build time)
Tip
The onboarding is fully resumable - exit anytime and continue later from where you left off.
## Starting the Onboarding
[Section titled âStarting the Onboardingâ](#starting-the-onboarding)
Run the onboarding command with your API key:
```bash
npx @capgo/cli@latest init [APIKEY]
```
Youâll see the welcome message:
```plaintext
Capgo onboarding đŤ
```
## What Happens During Onboarding
[Section titled âWhat Happens During Onboardingâ](#what-happens-during-onboarding)
The CLI will guide you through 13 interactive steps:
**Setup Phase (Steps 1-6):**
* Check your development environment (Xcode/Android Studio)
* Add your app to Capgo and create a production channel
* Install the `@capgo/capacitor-updater` plugin
* Inject the required code into your app
* Optionally enable end-to-end encryption
* Choose a platform for testing (iOS or Android)
**Testing Phase (Steps 7-12):**
* Build your app and run it on a device/simulator
* Make a visible code change (automatic or manual)
* Upload the updated bundle to Capgo
* See the live update appear on your device in real-time
**Completion (Step 13):**
* Your app is ready for live updates! đ
## The 13-Step Onboarding Process
[Section titled âThe 13-Step Onboarding Processâ](#the-13-step-onboarding-process)
### Step 1: Check Prerequisites
[Section titled âStep 1: Check Prerequisitesâ](#step-1-check-prerequisites)
The CLI checks your development environment to ensure you have the necessary tools installed.
**Whatâs checked:**
* **Xcode** (macOS only) - for iOS development
* **Android SDK** - for Android development
**Possible outcomes:**
â **Both environments found:**
```plaintext
â Xcode detected - iOS development ready
â Android SDK detected - Android development ready
```
â ď¸ **No environment found:**
```plaintext
â ď¸ Xcode not found
â ď¸ Android SDK not found
â No development environment detected
đą To develop mobile apps with Capacitor, you need:
⢠For iOS: Xcode (macOS only) - https://developer.apple.com/xcode/
⢠For Android: Android Studio - https://developer.android.com/studio
```
**Questions you may be asked:**
Caution
If no development environment is detected, youâll be asked if you want to continue. Itâs recommended to install at least one platform before proceeding.
### Step 2: Add Your App
[Section titled âStep 2: Add Your Appâ](#step-2-add-your-app)
The CLI will log you into Capgo and add your app to your account.
```plaintext
(spinner) Running: npm @capgo/cli@latest login ***
Login Done â
â Add {appId} in Capgo?
```
**If your app ID is already taken:**
The CLI will suggest alternatives:
```plaintext
â App ID "com.example.app" is already taken
đĄ Here are some suggestions:
1. com.example.app2
2. com.example.app3
3. com.example.app.new
4. com.example.app.app
â What would you like to do?
```
You can choose a suggestion or enter a custom app ID.
Note
App IDs must follow reverse domain notation (e.g., `com.example.myapp`)
### Step 3: Create Production Channel
[Section titled âStep 3: Create Production Channelâ](#step-3-create-production-channel)
Channels allow you to manage different update streams for your app.
```plaintext
â Create default channel production for {appId} in Capgo?
```
Tip
**Donât worry!** This is just for local testing during onboarding. Creating a âproductionâ channel doesnât mean your updates will go live to customers immediately. You have full control over when updates are deployed. Select **Yes** unless you have specific channel requirements.
**If you select Yes:**
```plaintext
(spinner) Running: npm @capgo/cli@latest channel add production {appId} --default
Channel add Done â (or "Channel already added â ")
```
A production channel will be created and set as default. This is the recommended option for most users.
**If you select No:**
```plaintext
If you change your mind, run it for yourself with: "npm @capgo/cli@latest channel add production {appId} --default"
```
Youâll need to create and configure channels manually later. Alternatively, you can:
* Set the channel in your `capacitor.config.ts` file
* Use the JavaScript `setChannel()` method to dynamically set the channel
* Configure channels later from the Capgo web console
### Step 4: Install Updater Plugin
[Section titled âStep 4: Install Updater Pluginâ](#step-4-install-updater-plugin)
The CLI will install the `@capgo/capacitor-updater` plugin compatible with your Capacitor version.
```plaintext
â Automatic Install "@capgo/capacitor-updater" dependency in {appId}?
```
**Version compatibility:**
* **Capacitor 5**: Installs `@capgo/capacitor-updater` v5
* **Capacitor 6**: Installs `@capgo/capacitor-updater` v6
* **Capacitor 7**: Installs `@capgo/capacitor-updater` v7
* **Capacitor 8+**: Installs latest version
Caution
Capgo only supports Capacitor v5 and above. If youâre using an older version, youâll need to upgrade first.
**Instant updates option:**
After installation, youâll be asked:
```plaintext
â Do you want to set instant updates in {appId}?
Read more: https://capgo.app/docs/live-updates/update-behavior/#applying-updates-immediately
```
Tip
**What are instant updates?** With instant updates enabled, your app applies updates immediately when backgrounded and reopened. This works seamlessly because Capgo can distribute updates worldwide in under 300ms. Without it (standard mode), updates download in the background and apply on the next app restart. Instant updates are great for faster iteration during development and critical bug fixes in production.
**If you select Yes:**
* Updates will be configured to apply immediately when the app is backgrounded and reopened
* `directUpdate: 'always'` and `autoSplashscreen: true` will be added to your config
* Your `capacitor.config.ts` will be updated automatically
* **Delta updates** will be automatically enabled - this sends only the files that changed between updates instead of the full bundle, making updates much faster
**If you select No:**
* Updates will use standard behavior (download in background, apply on next restart)
* You can always enable instant updates later by modifying your `capacitor.config.ts`
### Step 5: Add Integration Code
[Section titled âStep 5: Add Integration Codeâ](#step-5-add-integration-code)
The CLI will automatically inject the required code into your main application file.
```plaintext
â Automatic Add "CapacitorUpdater.notifyAppReady()" code and import in {appId}?
```
**What gets added:**
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
CapacitorUpdater.notifyAppReady()
```
**Project type detection:**
* **Nuxt.js**: Creates `plugins/capacitorUpdater.client.ts`
* **Other frameworks**: Adds to your main entry file
Tip
**If auto-injection fails**, you can add the code manually to your main application file:
**For Nuxt.js:** Create `plugins/capacitorUpdater.client.ts`:
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
export default defineNuxtPlugin(() => {
CapacitorUpdater.notifyAppReady()
})
```
**For other frameworks:** Add to your main entry file (e.g., `main.ts`, `index.js`, `App.tsx`):
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
CapacitorUpdater.notifyAppReady()
```
Place this code after your imports and before your app initialization. For more details, see the [Add an App guide](/docs/getting-started/add-an-app/).
### Step 6: Setup Encryption (Optional)
[Section titled âStep 6: Setup Encryption (Optional)â](#step-6-setup-encryption-optional)
End-to-end encryption adds an extra security layer for your updates.
```plaintext
đ End-to-end encryption
â Use this for: Banking, healthcare, or apps with legal encryption requirements
â ď¸ Note: Makes debugging harder - skip if you don't need it
â Enable end-to-end encryption for {appId} updates?
```
Note
Encryption is only available for Capacitor v6 and above.
If you enable encryption, the CLI will:
1. Generate encryption keys
2. Offer to sync your Capacitor configuration
### Step 7: Select Platform
[Section titled âStep 7: Select Platformâ](#step-7-select-platform)
Choose which platform to test with during onboarding.
```plaintext
đą Platform selection for onboarding
This is just for testing during onboarding - your app will work on all platforms
â Which platform do you want to test with during this onboarding?
Options:
- iOS
- Android
```
Tip
This only affects the onboarding process. Your final app will support all platforms.
### Step 8: Build Your Project
[Section titled âStep 8: Build Your Projectâ](#step-8-build-your-project)
The CLI will build your app and sync it with Capacitor.
```plaintext
â Automatic build {appId} with "npm run build"?
```
**What happens:**
1. Detects your project type
2. Runs your build script
3. Executes `npx cap sync {platform}`
**If build script is missing:**
Youâll be asked if you want to skip the build or add a build script to your `package.json`.
### Step 9: Run on Device
[Section titled âStep 9: Run on Deviceâ](#step-9-run-on-device)
Test the initial version of your app on a device or simulator.
```plaintext
â Run {appId} on {PLATFORM} device now to test the initial version?
```
If you select **Yes**:
```plaintext
(spinner) Running: npx cap run {platform}
(device picker appears)
App started â
đą Your app should now be running on your {platform} device with Capgo integrated
đ This is your baseline version - we'll create an update next
```
### Step 10: Make a Test Change
[Section titled âStep 10: Make a Test Changeâ](#step-10-make-a-test-change)
Now itâs time to test Capgoâs update system by making a visible change.
```plaintext
đŻ Now let's test Capgo by making a visible change and deploying an update!
â How would you like to test the update?
Options:
- Auto: Let Capgo CLI make a visible change for you
- Manual: I'll make changes myself
```
**Auto mode:** The CLI will automatically modify your files to add a visible test banner or change.
**Manual mode:** You make your own changes (e.g., change text, colors, or add elements).
**Version handling:**
```plaintext
â How do you want to handle the version for this update?
Options:
- Auto: Bump patch version ({currentVersion} â {nextVersion})
- Manual: I'll provide the version number
```
**Build with changes:**
```plaintext
â Build {appId} with changes before uploading?
```
Tip
If you need to build manually in another terminal, select âNoâ and build yourself, then continue.
### Step 11: Upload Bundle
[Section titled âStep 11: Upload Bundleâ](#step-11-upload-bundle)
Upload your updated app bundle to Capgo.
```plaintext
â Upload the updated {appId} bundle (v{version}) to Capgo?
```
The CLI runs:
```bash
npx @capgo/cli@latest bundle upload
```
Tip
**Delta updates with Direct Update:** If you enabled instant updates (Direct Update) in Step 4, the CLI will automatically ask if you want to enable delta updates. Delta updates send only the files that changed between versions instead of the entire bundle. Since usually only a few files change between updates, this makes downloads much faster. Select **Yes** for the best experience with instant updates.
**Delta updates prompt (if Direct Update is enabled):**
```plaintext
đĄ Direct Update (instant updates) is enabled in your config
Delta updates send only changed files instead of the full bundle
â Enable delta updates for this upload? (Recommended with Direct Update)
```
Caution
For monorepos, you may need to provide additional paths to your `package.json` and `node_modules`.
**Success:**
```plaintext
â Update v{version} uploaded successfully!
đ Your updated bundle is now available on Capgo
```
### Step 12: Test Update on Device
[Section titled âStep 12: Test Update on Deviceâ](#step-12-test-update-on-device)
Time to see the update in action!
```plaintext
đ§Ş Time to test the Capgo update system!
đą Go to your device where the app is running
```
**For instant updates:**
```plaintext
đ IMPORTANT: Background your app (swipe up/press home button) and then reopen it
âąď¸ The update should be downloaded and applied automatically
```
**For standard updates:**
```plaintext
đą With standard updates, you will need to:
1. Background the app (swipe up/press home button) to start download
2. Wait a few seconds for download to complete
3. Background and foreground again to see the update
```
**Monitor logs:**
```plaintext
â Monitor Capgo logs to verify the update worked?
```
If you select **Yes**, youâll see live logs from your device showing the update process.
### Step 13: Completion
[Section titled âStep 13: Completionâ](#step-13-completion)
```plaintext
Welcome onboard âď¸!
```
Congratulations! Youâve successfully set up Capgo live updates for your app.
## What Youâve Accomplished
[Section titled âWhat Youâve Accomplishedâ](#what-youve-accomplished)
After completing the onboarding, you have:
â App Registered
Your app is registered in Capgo with a production channel
â Plugin Installed
The Capacitor Updater plugin is installed and configured
â Code Integrated
Integration code is added to your app
â Update Tested
Youâve successfully deployed and received a live update
## Daily Workflow
[Section titled âDaily Workflowâ](#daily-workflow)
For subsequent updates, use:
```bash
npm run build
npx @capgo/cli@latest bundle upload --channel=production
```
For more deployment options, see [Deploy a Live Update](/docs/getting-started/deploy/).
## Resuming Onboarding
[Section titled âResuming Onboardingâ](#resuming-onboarding)
If you exit the onboarding process, you can resume anytime:
```bash
npx @capgo/cli@latest init [APIKEY]
```
Youâll see:
```plaintext
You have already got to the step {stepNumber}/13 in the previous session
â Would you like to continue from where you left off?
```
Tip
Progress is saved locally, so you can safely exit and resume the onboarding process.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### No Development Environment
[Section titled âNo Development Environmentâ](#no-development-environment)
**Problem:** Neither Xcode nor Android SDK is detected.
**Solution:**
* **For iOS**: Install [Xcode](https://developer.apple.com/xcode/) (macOS only)
* **For Android**: Install [Android Studio](https://developer.android.com/studio)
### App ID Already Taken
[Section titled âApp ID Already Takenâ](#app-id-already-taken)
**Problem:** Your app ID is already registered.
**Solution:** Choose one of the suggested alternatives or enter a custom app ID in reverse domain notation.
### Build Script Missing
[Section titled âBuild Script Missingâ](#build-script-missing)
**Problem:** No build script found in `package.json`.
**Solution:** Add a build script to your `package.json`:
```json
{
"scripts": {
"build": "your-build-command"
}
}
```
### Auto-Injection Failed
[Section titled âAuto-Injection Failedâ](#auto-injection-failed)
**Problem:** CLI cannot automatically inject the integration code.
**Solution:** Add the code manually to your main file:
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
CapacitorUpdater.notifyAppReady()
```
### Capacitor Version Too Old
[Section titled âCapacitor Version Too Oldâ](#capacitor-version-too-old)
**Problem:** Your Capacitor version is below v5.
**Solution:** Upgrade Capacitor to v5 or higher:
* [Upgrading to Capacitor 5](https://capacitorjs.com/docs/updating/5-0)
* [Upgrading to Capacitor 6](https://capacitorjs.com/docs/updating/6-0)
* [Upgrading to Capacitor 7](https://capacitorjs.com/docs/updating/7-0)
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
Now that youâve completed onboarding, explore these topics:
[ Deploy Updates](/docs/getting-started/deploy/)
[Learn how to deploy updates from the Capgo dashboard](/docs/getting-started/deploy/)
[ Update Types](/docs/live-updates/update-types/)
[Reference of all OTA update types: apply timing, delay conditions, version blocking, and delivery](/docs/live-updates/update-types/)
[ CI/CD Integration](/docs/getting-started/cicd-integration/)
[Automate your update deployments with CI/CD](/docs/getting-started/cicd-integration/)
[ Channels](/docs/live-updates/channels/)
[Manage multiple update streams with channels](/docs/live-updates/channels/)
[ Encryption](/docs/live-updates/encryption/)
[Secure your updates with end-to-end encryption](/docs/live-updates/encryption/)
[ Update Behavior](/docs/live-updates/update-behavior/)
[Customize when and how updates are applied (direct, delta, etc.)](/docs/live-updates/update-behavior/)
## Getting Help
[Section titled âGetting Helpâ](#getting-help)
If you encounter issues during onboarding:
* Check the [Troubleshooting Guide](/docs/getting-started/troubleshooting/)
* Join the [Discord Community](https://discord.capgo.app)
* Review the [FAQ](/docs/faq/)
* Contact [Support](/docs/getting-help/)
# Overview
> Get started with Capgo by learning the key concepts and steps to integrate and deploy live updates to your app.
The quickstart tutorial will walk you through the key concepts of Capgo! Concepts that will be explored include:
1. Adding an app to your Capgo account
2. Integrating Capgo with your CI/CD
3. Triggering bundle upload on Capgo by pushing commits
4. Configuring and customizing the Capgo bundle publishing
5. Setting up your app to enable live updates via Capgo
6. Deploying live updates to your app from Capgo
Simply follow the guide step-by-step, or navigate directly to the documentation for the component that interests you.
[ Start the Tutorial](/docs/getting-started/add-an-app/)
[Follow the quickstart tutorial and get up and running with Capgo in no time!](/docs/getting-started/add-an-app/)
[ CLI Onboarding Guide](/docs/getting-started/onboarding/)
[Complete step-by-step guide for the interactive CLI onboarding process.](/docs/getting-started/onboarding/)
[ Ship updates](/docs/getting-started/deploy/)
[Ship updates to your app from the Capgo dashboard.](/docs/getting-started/deploy/)
[ Automate updates](/docs/getting-started/cicd-integration/)
[Integrate Capgo with your CI/CD and trigger bundle uploads on Capgo by pushing commits.](/docs/getting-started/cicd-integration/)
[ Trouble Shooting](/docs/getting-started/troubleshooting/)
[Common issues and how to solve them.](/docs/getting-started/troubleshooting/)
[ Wrap Up](/docs/getting-started/wrapping-up/)
[Wrap up the tutorial and get a quick overview of what youâve learned.](/docs/getting-started/wrapping-up/)
Tip
The Over-the-Air (OTA) update feature is applicable only for modifications made to HTML, CSS, and JavaScript files.
If you make any changes to the native code, such as updates to Capacitor plugins, it is mandatory to resubmit the application to the app store for approval.
Bundle Confidentiality
Treat every bundle uploaded to Capgo as a public web asset unless you enable Capgo encryption. Private channels control which devices are eligible to receive an update, but they do not make the uploaded bundle confidential. Encryption protects the delivery path and prevents third parties from producing valid encrypted updates, but shipped web assets can still be reverse engineered from the app with enough effort because the public key is distributed in the binary. See [Live Update encryption](/docs/live-updates/encryption/).
## Join Discord Community
[Section titled âJoin Discord Communityâ](#join-discord-community)
[Join the Capgo Discord Server!](https://discord.capgo.app)
## Maintenance
[Section titled âMaintenanceâ](#maintenance)
| Plugin version | Capacitor compatibility | Maintained |
| ------------------ | ----------------------- | -------------------------------------------------------- |
| v7.\*.\* (âĽ7.25.0) | v7.\*.\* | â Fully supported |
| v6.\*.\* (âĽ6.25.0) | v6.\*.\* | â Fully supported |
| v5.\*.\* (âĽ5.10.0) | v5.\*.\* | â Fully supported |
| v5.\*.\* (<5.10.0) | v5.\*.\* | â ď¸ Deprecated |
| v4.\*.\* | v4.\*.\* | â No longer supported |
| v3.\*.\* | v3.\*.\* | â No longer supported |
| >= 8 | v4.\*.\* | â ď¸ Deprecated due to versioning issues in our CI process |
## Store Guideline Compliance
[Section titled âStore Guideline Complianceâ](#store-guideline-compliance)
Android Google Play and iOS App Store have corresponding guidelines that have rules you should be aware of before integrating the Capacitor-updater solution within your application.
### Google play
[Section titled âGoogle playâ](#google-play)
Third paragraph of [Device and Network Abuse](https://support.google.com/googleplay/android-developer/answer/9888379/?hl=en) topic describe that updating source code by any method other than Google Playâs update mechanism is restricted. But this restriction does not apply to updating javascript bundles.
> This restriction does not apply to code that runs in a virtual machine and has limited access to Android APIs (such as JavaScript in a webview or browser).
That fully allows Capacitor-updater as it updates just the JS bundles and wonât update native code.
### App Store
[Section titled âApp Storeâ](#app-store)
Paragraph **3.3.2**, since back in 2015âs [Apple Developer Program License Agreement](https://developer.apple.com/programs/ios/information/) fully allows performing over-the-air updates of JavaScript and assets - and in its latest version (20170605) [downloadable here](https://developer.apple.com/terms/) this ruling is even broader:
> Interpreted code may be downloaded to an Application but only so long as such code: (a) does not change the primary purpose of the Application by providing features or functionality that are inconsistent with the intended and advertised purpose of the Application as submitted to the App Store, (b) does not create a store or storefront for other code or applications, and (c) does not bypass signing, sandbox, or other security features of the OS.
Capacitor Updater allows you to follow these rules in full compliance so long as the update you push does not significantly deviate your product from its original App Store approved intent.
To further remain in compliance with Appleâs guidelines we suggest that App Store-distributed apps do not enable the `Force update` scenario, since in the [App Store Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) state that:
> Apps must not force users to rate the app, review the app, download other apps, or other similar actions in order to access functionality, content, or use of the app.
This is not a problem for the default behavior of background update, since it wonât force the user to apply the new version until next time they close the app, but at least you should be aware of that role if you decide to show it.
## Open source
[Section titled âOpen sourceâ](#open-source)
The plugin is under the LGPL-3.0 License and the back-end is AGPL-3.0 License.
> đĄ LGPL-3.0 means if someone modifies the code of the plugin, itâs mandatory to publish it, in open-source with the same licensing. If you use the code without modification, that doesnât concern you. See the issue below for more details check the link đ
[Licensing? ](https://github.com/Cap-go/capacitor-updater/issues/7)
[Try GPTS Capgo to Get help instead of reading the docs ](https://chat.openai.com/g/g-3dMwHbF2w-capgo-doc-gpt)
> You can include it in your app without worrying
## Final Notes
[Section titled âFinal Notesâ](#final-notes)
If you self-host and find this tool useful, please consider supporting my work by becoming a [GitHub sponsor](https://github.com/sponsors/riderx/).
I made a bet to open-source all the code I built here instead of paywalling it. By opening it up instead of fighting and hiding, I believe we can make the world a better place.
To make this possible, itâs necessary for all of us to do our part, including you đĽš. If Capgo cloud doesnât meet your needs, you can back a bootstrapped Maker [here](https://github.com/sponsors/riderx/) on your own terms.
## Simple Maths
[Section titled âSimple Mathsâ](#simple-maths)
The price of the basic plan: $14\*12 = $168 a year. While average dev/hour = $60. That means that 3 hours wasted of dev time on self-host allows you to pay for a whole year, if you spent more than 3 hours youâre losing money ^^
# Troubleshooting
> Resolve common issues encountered while using Capgo with detailed troubleshooting steps and advanced options for upload and debugging.
Here are some common issues you might encounter while using Capgo and how to resolve them.
đ Need Expert Help?
Stuck with a complex issue? Our expert team is here to help! Get personalized support, code reviews, and custom solutions tailored to your specific needs.
[Get Professional Support](/consulting/)
### Upload failures
[Section titled âUpload failuresâ](#upload-failures)
If your bundle upload fails, double check:
* Your app ID in `capacitor.config.ts` matches your app in the Capgo dashboard
* Youâre running the upload command from the root of your Capacitor project
* Your web assets are built and up to date
#### Advanced upload options
[Section titled âAdvanced upload optionsâ](#advanced-upload-options)
The Capgo CLI provides some additional flags to help with common upload issues:
* `--tus`: Uses the [tus resumable upload protocol](https://tus.io/) for more reliable uploads of large bundles or on poor network connections. If your bundle is over 10MB or youâre on a spotty connection, consider using `--tus`:
```shell
npx @capgo/cli@latest bundle upload --tus
```
* `--package-json` and `--node-modules`: Tells Capgo where to find your root `package.json` and `node_modules` if your app uses a non-standard structure like a monorepo or npm workspace. Pass the path to the root `package.json` and the `--node_modules` path:
```shell
npx @capgo/cli@latest bundle upload --package-json=path/to/package.json --node_modules=path/to/node_modules
```
Capgo needs this information to correctly bundle your appâs dependencies.
You can combine these flags with other options like `--channel` as needed. See the [Capgo CLI docs](/docs/cli/overview/) for full details on the available upload options.
If youâre still having trouble with uploads, reach out to [Capgo support](https://support.capgo.app) for further assistance.
### Debugging Updates
[Section titled âDebugging Updatesâ](#debugging-updates)
If youâre encountering issues with live updates, the Capgo debug command is a helpful tool for troubleshooting. To use it:
1. Run the following command in your project directory:
```shell
npx @capgo/cli@latest app debug
```
2. Launch your app on a device or emulator and perform the action that should trigger an update (e.g. reopening the app after uploading a new bundle).
3. Watch the output of the debug command. It will log information about the update process, including:
* When the app checks for an update
* If an update is found and what version it is
* Download and installation progress for the update
* Any errors that occur during the update process
4. Use the debug logs to identify where the issue is occurring. For example:
* If no update is found, double check that your bundle was uploaded successfully and the app is configured to use the correct channel.
* If the update downloads but doesnât install, make sure youâve called `CapacitorUpdater.notifyAppReady()` and that the app was fully closed and reopened.
* If you see an error message, look up that specific error in the Capgo docs or reach out to support for help.
The debug command is especially useful for identifying issues with the update download and installation process. If the logs show the expected update version was found but not ultimately applied, focus your troubleshooting on the steps after the download.
### Debugging with Native Logs
[Section titled âDebugging with Native Logsâ](#debugging-with-native-logs)
In addition to the Capgo debug command, the native logs on Android, iOS, and Electron can provide valuable troubleshooting information, especially for issues on the native side of the update process.
#### Android Logs
[Section titled âAndroid Logsâ](#android-logs)
To access the Android logs:
1. Connect your device or start your emulator
2. Open Android Studio and select âView > Tool Windows > Logcatâ
3. In the Logcat window, filter the logs to just your appâs process by selecting it from the dropdown at the top
4. Look for any lines that include `Capgo` to find the SDK logs
Alternatively, you can use the `adb logcat` command and grep for `Capgo` to filter the logs.
The Capgo SDK will log key events during the update process, such as:
* When an update check is initiated
* If an update is found and what version it is
* When the update download starts and completes
* When the update installation is triggered
* Any errors that occur during the native update steps
Common Android-specific issues you might see in the logs include:
* Network connectivity problems preventing the update download
* File permissions errors when saving or reading the update bundle
* Out of storage space for the update bundle
* Failure to restart the app after the update is installed
#### iOS Logs
[Section titled âiOS Logsâ](#ios-logs)
To access the iOS logs:
1. Connect your device or start your simulator
2. Open Xcode and go to âWindow > Devices and Simulatorsâ
3. Select your device and click on âOpen Consoleâ
4. In the console output, look for any lines that include `Capgo` to find the SDK logs
You can also use the `log stream` command in the terminal and grep for `Capgo` to filter the logs.
Similar to Android, the Capgo SDK will log key iOS-side events:
* Update check initiation and result
* Download start, progress, and completion
* Installation trigger and result
* Any errors during the native update process
iOS-specific issues you might identify in the logs include:
* SSL certificate problems when downloading the update
* App transport security blocking the update download
* Insufficient storage space for the update bundle
* Failure to properly extract or apply the update bundle
#### Electron Logs
[Section titled âElectron Logsâ](#electron-logs)
For Electron apps, check both the main process and renderer process output:
1. Run the Electron app from your terminal using your normal launch command (for example `bun run electron:dev` or `bun run electron:serve`) and watch the terminal output for startup, update checks, and network errors.
2. Open DevTools in the renderer window (View â Toggle Developer Tools) and inspect console logs and failed network requests while reproducing the update flow.
3. For packaged apps, check OS log tools for crashes or startup failures:
* **macOS**: open `Console.app` and filter on your app name
* **Windows**: open **Event Viewer** â **Windows Logs** â **Application**
* **Linux**: use your desktop log viewer or `journalctl` for your app process
When debugging updates, compare messages from both main-process and renderer-process logs to separate Electron bootstrap issues from Capgo update lifecycle issues.
Across platforms, the native logs provide a lower-level view into the update process, with more details on the native implementation. They are especially useful for identifying issues that occur outside of the Capgo JavaScript layer.
When troubleshooting a tricky live update problem, itâs a good idea to capture both the Capgo debug logs and the native logs for a comprehensive picture of whatâs happening. The two logs together will give you the best chance of identifying and resolving the issue.
### Updates not applying
[Section titled âUpdates not applyingâ](#updates-not-applying)
If youâve uploaded a bundle but arenât seeing the changes on your device:
* Make sure youâve called `CapacitorUpdater.notifyAppReady()` in your app code as shown in the [quickstart](/docs/getting-started/quickstart)
* Check that your device is connected to the internet and the Capgo debug logs show the update was downloaded
* Try fully closing and reopening the app, as updates are only applied on a fresh launch
* Look for any errors in the native logs that might indicate a problem applying the update
Refer to the [deploying live updates](/docs/getting-started/deploy) guide for more details on the update process. If youâre still stuck, use the `npx @capgo/cli@latest app debug` command and native logs to get more visibility into whatâs happening.
### Common update failure codes
[Section titled âCommon update failure codesâ](#common-update-failure-codes)
If your logs show backend errors such as `disable_auto_update_to_major`, `semver_error`, or `cannot_update_via_private_channel`, use the dedicated guide:
* [Common Update Problems](/docs/plugins/updater/commonproblems/)
It explains what each common code means, why it happens, and how to fix it.
## SDK Installation
[Section titled âSDK Installationâ](#sdk-installation)
If youâre having trouble installing the Capgo SDK, make sure:
* Your app is using a supported version of Capacitor (4.0 or newer)
* Youâve followed the [quickstart](/docs/getting-started/quickstart) steps in order, including syncing your app after installing the SDK
## CI/CD Integration
[Section titled âCI/CD Integrationâ](#cicd-integration)
For issues with triggering Capgo uploads from your CI/CD pipeline:
* Double check your Capgo authentication token is set up correctly
* Make sure youâre running the upload command after your web assets are built
* Check that the upload command is using the correct channel name for your target environment
See the [CI/CD integration](/docs/getting-started/cicd-integration/) docs for more troubleshooting tips. You can also use the `npx @capgo/cli@latest app debug` command to confirm if your CI/CD-triggered updates are being received by the app.
# Wrapping up
> Wrap up your Capgo journey with a concise overview of key concepts and next steps, ensuring a solid foundation for future exploration and mastery.
Now that you have completed the quickstart guide, you should have a basic understanding of the key concepts of Capgo! The key concepts you have learned in this guide are:
1. Adding an app to your Capgo account
2. Integrating Capgo with your CI/CD pipeline
3. Triggering bundle uploads to Capgo on new commits
4. Configuring your app to enable live updates with the Capgo SDK
5. Deploying live updates to your app from the Capgo dashboard
But thereâs still more to learn about Capgo! Continue exploring the docs or check out some of these key topics:
[ CI/CD Integration](/docs/getting-started/cicd-integration/)
[Already have a CI/CD pipeline? Learn how to incorporate Capgo into your existing workflow.](/docs/getting-started/cicd-integration/)
[ Live Updates](/docs/live-updates/)
[Dive deeper into Capgoâs live update features and best practices.](/docs/live-updates/)
[ FAQ](/docs/faq/)
[Find answers to common questions about Capgo.](/docs/faq/)
[ Troubleshooting](/docs/getting-started/troubleshooting/)
[Get help with common issues that can come up while using Capgo.](/docs/getting-started/troubleshooting/)
# How to
> A comprehensive guide to Capgo, offering detailed tutorials, insightful tips, and advanced techniques to enhance your effective usage of the platform
[How version works in Capgo ](https://capgo.app/blog/how-version-work-in-capgo/)capgo.app
[How to release major version in Capgo ](https://capgo.app/blog/how-to-release-major-version-in-capgo/)capgo.app
[How to send specific update to one user or a group ](https://capgo.app/blog/how-to-send-specific-version-to-users/)capgo.app
## CI / CD
[Section titled âCI / CDâ](#ci--cd)
[Automatic build and release with GitHub Actions ](https://capgo.app/blog/automatic-build-and-release-with-github-actions/)capgo.app
[Manage development and production build with GitHub Actions ](https://capgo.app/blog/automatic-build-and-release-with-github-actions/)capgo.app
## Contributing
[Section titled âContributingâ](#contributing)
[Contributing to Capgo open source ](https://github.com/Cap-go/capgo/blob/main/CONTRIBUTING.md)github.com
# Overview
> Discover how Capgo's Live Updates enable seamless JavaScript bundle updates, allowing you to push changes directly to users without app store delays.
Use Capgoâs Live Updates feature to update the JavaScript bundles of your app remotely, in real-time. Push JS updates directly to your users on iOS, Android, and Electron without going through store-level review cycles to fix bugs and ship new features faster.
Note
Live Updates are limited to JavaScript bundle changes. If you need to update native code, such as adding or removing a plugin or changing native project configuration, youâll need to submit a new binary build through the usual platform distribution process.
Public Asset Model
Unencrypted bundles uploaded to Capgo should be treated as public delivery assets. Channels determine which devices are offered an update, but channel privacy does not make the underlying bundle confidential. Encryption adds protection in storage and transit and stops third parties from producing valid encrypted updates, but it does not make shipped web assets impossible to inspect because the app contains the public key needed for decryption. See [end-to-end encryption](/docs/live-updates/encryption/) for the exact threat model.
## How Live Updates Work
[Section titled âHow Live Updates Workâ](#how-live-updates-work)
Capgoâs Live Update system has two key components:
1. The Capgo SDK, which you install in your app. The SDK checks for available updates and downloads them in the background.
2. Channels, which let you target updates to specific groups of users. You can use channels to manage different release tracks, such as `Production`, `Staging`, and `Dev`.
When you upload a new JS bundle to Capgo and assign it to a channel, the Capgo SDK in apps configured for that channel will detect the update and download it. The next time the app restarts, the new bundle will be loaded.
## Why Capgo Logs Matter (marketing view)
[Section titled âWhy Capgo Logs Matter (marketing view)â](#why-capgo-logs-matter-marketing-view)
* **Instant x-ray of every rollout**: Per-device timelines show checks, downloads, installs, policy blocks, and rollbacks, so you know exactly what happenedâno guesswork or âit works on my phoneâ debates.
* **Faster incident response**: Alert-like codes (e.g., rate limits, checksum fails, notifyAppReady misses) surface before users start flooding support, letting you ship a fix or rollback in minutes.
* **Channel policy proof**: Logs verify that guardrails (block majors, disable emulators/dev builds, platform limits) are actively protecting production.
* **Revenue & reputation protection**: See when updates stall on poor networks or hit plan limits, so you can intervene before conversions, sessions, or reviews drop.
* **Single source of truth**: Product, QA, and Support share the same cloud log streamâno digging through Xcode/Android Studio or DMâing engineers for native logs.
## Getting Started
[Section titled âGetting Startedâ](#getting-started)
To start using Live Updates, follow these steps:
1. Complete the [Capgo Quickstart](/docs/getting-started/quickstart) to set up your app in Capgo and install the Capgo SDK.
2. In your app code, call `CapacitorUpdater.notifyAppReady()` after your app has finished initializing. This tells the Capgo SDK that your app is ready to receive updates.
3. Build your JS bundle and upload it to Capgo:
```shell
npm run build
npx @capgo/cli@latest bundle upload --channel=production
```
4. Open your app and wait for the update to download. You can check the status with:
```shell
npx @capgo/cli@latest app debug
```
5. Once the update is downloaded, close and reopen your app to load the new bundle.
See the [Deploying Live Updates](/docs/getting-started/deploy) guide for more details.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
[ Update Types](/docs/live-updates/update-types/)
[Reference of all OTA update types: apply timing, delay conditions, version blocking, and delivery.](/docs/live-updates/update-types/)
[ Channels](/docs/live-updates/channels/)
[Learn how to use channels to manage different release tracks and target updates to specific users.](/docs/live-updates/channels/)
[ Rollbacks](/docs/live-updates/rollbacks/)
[Discover how to roll back to a previous JS bundle version if an update causes issues.](/docs/live-updates/rollbacks/)
[ Update Behavior](/docs/live-updates/update-behavior/)
[Customize how and when updates are downloaded and applied in your app.](/docs/live-updates/update-behavior/)
[ Fast Updates](/docs/live-updates/differentials/)
[Learn how to use fast updates to speed up the update process.](/docs/live-updates/differentials/)
# Breaking Changes
> How to handle breaking changes with versioned channels
This documentation explains how to handle breaking changes in your app using versioned channels. This approach allows you to maintain different versions of your app while ensuring users receive compatible updates.
## Example Scenario
[Section titled âExample Scenarioâ](#example-scenario)
Letâs say you have:
* App version 1.2.3 (old version) - uses production channel
* App version 2.0.0 (new version with breaking changes) - uses v2 channel
* Live update 1.2.4 (compatible with 1.2.3)
* Live update 2.0.1 (compatible with 2.0.0)
## Strategy: Always Use defaultChannel for Major Versions
[Section titled âStrategy: Always Use defaultChannel for Major Versionsâ](#strategy-always-use-defaultchannel-for-major-versions)
**Recommended approach:** Set a `defaultChannel` for every major version. This ensures you can always push updates to specific user groups without relying on dynamic channel assignment.
```ts
// Version 1.x releases
defaultChannel: 'v1'
// Version 2.x releases
defaultChannel: 'v2'
// Version 3.x releases (future)
defaultChannel: 'v3'
```
Tip
**Benefits of this approach:**
* **Always have control** over which users receive updates
* **No dynamic channel switching** needed in your app code
* **Clear separation** between different app versions
* **Flexibility** to push updates to any specific version group
## 1. Create Channel for New Version
[Section titled â1. Create Channel for New Versionâ](#1-create-channel-for-new-version)
```bash
# Create channel for version 2.x
npx @capgo/cli channel create v2
```
## 2. Update Capacitor Config for Version 2.0.0
[Section titled â2. Update Capacitor Config for Version 2.0.0â](#2-update-capacitor-config-for-version-200)
Update your Capacitor config before building version 2.0.0 for the app store:
capacitor.config.ts
```ts
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'Example App',
plugins: {
CapacitorUpdater: {
// ... other options
defaultChannel: 'v2' // All 2.0.0 users will use v2 channel
}
}
};
export default config;
```
Note
**For version 1.x:** If you didnât set a `defaultChannel` initially, version 1.x users are on the `production` channel. For future major versions, always set a specific channel like `v3`, `v4`, etc.
## 3. Manage Separate Code Branches
[Section titled â3. Manage Separate Code Branchesâ](#3-manage-separate-code-branches)
Create separate git branches to maintain compatibility between app versions:
```bash
# Create and maintain a branch for version 1.x updates
git checkout -b v1-maintenance
git push origin v1-maintenance
# Your main branch continues with version 2.x development
git checkout main
```
**Critical:** Never push JavaScript bundles to older apps that expect native code/APIs they donât have. Always build updates from the appropriate branch:
* **v1-maintenance branch**: For updates to 1.x apps (production channel)
* **main branch**: For updates to 2.x apps (v2 channel)
## 4. Upload Bundles to Respective Channels
[Section titled â4. Upload Bundles to Respective Channelsâ](#4-upload-bundles-to-respective-channels)
```bash
# For 1.x updates: Build from v1-maintenance branch
git checkout v1-maintenance
# Make your 1.x compatible changes here
npx @capgo/cli bundle upload --channel production
# For 2.x updates: Build from main branch
git checkout main
# Make your 2.x changes here
npx @capgo/cli bundle upload --channel v2
```
## 5. Enable Self-Assignment
[Section titled â5. Enable Self-Assignmentâ](#5-enable-self-assignment)
```bash
# Allow apps to self-assign to v2 channel
npx @capgo/cli channel set v2 --self-assign
```
## 6. Deploy to App Store
[Section titled â6. Deploy to App Storeâ](#6-deploy-to-app-store)
Build and deploy version 2.0.0 to the app store. All users who download this version (whether new users or existing users upgrading) will automatically use the v2 channel because itâs configured in the app bundle.
Note
**No code changes needed!** Since `defaultChannel: 'v2'` is bundled with the app store version, all users downloading version 2.0.0 will automatically use the correct channel.
## Scaling to Future Versions
[Section titled âScaling to Future Versionsâ](#scaling-to-future-versions)
When you release version 3.0.0 with more breaking changes:
```bash
# Create channel for version 3.x
npx @capgo/cli channel create v3
```
```ts
// capacitor.config.ts for version 3.0.0
const config: CapacitorConfig = {
// ...
plugins: {
CapacitorUpdater: {
defaultChannel: 'v3' // Version 3.x users
}
}
};
```
Now you can push updates to any version:
* `production` channel â Version 1.x users
* `v2` channel â Version 2.x users
* `v3` channel â Version 3.x users
## 7. Cleanup (After Migration)
[Section titled â7. Cleanup (After Migration)â](#7-cleanup-after-migration)
Once all users have migrated to version 2.x (count 3-4 months):
1. Remove `defaultChannel` from your Capacitor config
2. Delete the v2 channel:
```bash
npx @capgo/cli channel delete v2
```
3. Delete the v1-maintenance branch:
```bash
git branch -d v1-maintenance
git push origin --delete v1-maintenance
```
Tip
This approach ensures users only receive updates compatible with their app version
Always test updates thoroughly in each channel before deployment
Note
You can safely delete the v2 channel in Capgo even if some users still have the channel override. They will automatically receive updates from the production channel instead.
## Maintaining Version 1.x Updates
[Section titled âMaintaining Version 1.x Updatesâ](#maintaining-version-1x-updates)
To send updates compatible with version 1.x:
1. Switch to the v1-maintenance branch:
```bash
git checkout v1-maintenance
```
2. Make your changes and commit:
```bash
# Make 1.x compatible changes
git add .
git commit -m "Fix for v1.x"
git push origin v1-maintenance
```
3. Build and upload to production channel:
```bash
npx @capgo/cli bundle upload --channel production
```
Tip
Keep your v1-maintenance branch up to date with bug fixes that are compatible with version 1.x, but never merge breaking changes from main
# Channels
> Learn how to manage and configure Live Update channels in Capgo, enabling seamless app updates by directing specific JS bundle builds to devices configured for those channels.
A Live Update channel points to a specific JS bundle build of your app that will be shared with any devices configured to listen to that channel for updates. When you [install the Capgo Live Updates SDK](/docs/getting-started/quickstart/) in your app, any native binary configured to that channel will check for available updates whenever the app is launched. You can change the build a channel points to at any time and can also roll back to previous builds if needed.
Channels Do Not Provide Confidentiality
Channels control update eligibility, not bundle secrecy. Even if a channel is private or self-assignment is disabled, any unencrypted bundle uploaded to Capgo should still be treated as a public asset delivered to clients. Encryption protects the delivery path and authenticity of updates, but shipped bundles can still be reverse engineered from the distributed app with enough effort because the public key is part of the client. See [Live Update encryption](/docs/live-updates/encryption/) for details.
## How a device picks a channel (precedence)
[Section titled âHow a device picks a channel (precedence)â](#how-a-device-picks-a-channel-precedence)
When a device checks for an update, Capgo decides which channel to use in this strict order (highest priority first):
1. **Forced device mapping (Dashboard)** â Manually pin a specific device ID to a channel. Use for urgent debugging or controlled testing with a single real user. This always wins.
2. **Cloud override (perâdevice) via Dashboard or API** â Created when you change the deviceâs channel in the dashboard or via API. Use for QA users switching between feature / PR channels or to reproduce a user issue. Reinstalling the binary does not clear it; deleting the device entry does.
Instant Channel Switching with setChannel()
**Starting from plugin version 5.34.0, 6.34.0, 7.34.0, or 8.0.0** (depending on your major version), `setChannel()` works differently: it contacts the backend to **validate** that the channel is allowed (checking if self-assignment is enabled for that channel), then stores the channel **locally on the device** as `defaultChannel`. This means the new channel takes effect **instantly** for the next update checkâno waiting for replication.
Previously, `setChannel()` saved the channel override to the backend database (like Dashboard or API changes), and devices had to wait for data replication (up to 2 minutes) before the new channel was recognized. The new behavior only reads from the backend (for validation) and stores locally, making channel switches instant.
**Note:** Even if a channel becomes disallowed after being set locally, the backend will still validate the channel during update checks, so security is maintained.
**Important:** When channel changes are made via the Dashboard or API, there is still a replication lag of up to 2 minutes before all edge servers reflect the change. For instant channel switching, use `setChannel()` from your app codeâit validates with the backend, then sets the channel locally for immediate effect.
3. **Capacitor config `defaultChannel` (test build default)** â If present in `capacitor.config.*` and no force/override exists, the app starts on this channel (e.g. `beta`, `qa`, `pr-123`). Intended for TestFlight / internal builds so testers land on a preârelease channel automatically. Production builds typically leave this unset.
4. **Cloud Default Channel (primary path \~99% of users)** â If you mark a default channel in the dashboard, all normal endâusers (no force, no override, no config defaultChannel) attach here. Change it to roll out or roll back instantlyâno new binary. If you have platform-specific defaults (for example, one iOS-only, one Android-only, one Electron-only), each device lands on the default matching its platform. Leaving the cloud default unset is allowed; in that case the device must match on steps 1â3 to receive updates.
Best practice:
* Treat 1â3 as exception / testing layers; when you set a cloud default, real users should flow into it. If you choose not to set one, be deliberate about how users attach (typically via `defaultChannel` in config or per-device overrides).
* Only configure `defaultChannel` in binaries you explicitly ship to testers. Leaving it unset keeps production logic centralized in the dashboard.
* Use `setChannel()` sparingly in productionâmainly for QA or targeted diagnostics.
If a channel is disabled for the platform (iOS/Android/Electron toggles) when it would otherwise be chosen, the selection process skips it and continues down the list.
> Summary: Force > Override > Config `defaultChannel` > Cloud Default.
## Default Channel Behavior
[Section titled âDefault Channel Behaviorâ](#default-channel-behavior)
Setting a cloud default is optional, but it usually serves as the catch-all path for new devices. Without one, only devices that match on forced mappings, overrides, or a `defaultChannel` in the Capacitor config will receive updates. When you do choose to mark defaults, keep these patterns in mind:
* **Single default (most common)** â If a channel has iOS, Android, and Electron enabled, it becomes the lone default; any device without overrides will attach here.
* **Platform-specific defaults** â If you split channels by platform (for example, `ios-production` with only iOS enabled, `android-production` with only Android enabled, and `electron-production` with only Electron enabled), mark each one as the default for its platform. iOS devices go to the iOS default, Android devices go to the Android default, and Electron apps go to the Electron default.
Remember that the cloud default and `defaultChannel` in `capacitor.config.*` both occupy the same decision layer. If you set a cloud default, you donât need to duplicate the value in your Capacitor configâleave `defaultChannel` empty for production builds. Reserve `defaultChannel` for binaries you intentionally ship to testers or QA when you want them to start on a non-production channel even if the cloud default is different.
You can change defaults at any time in the dashboard. When you swap a default, new devices obey the new routing immediately and existing devices follow the normal precedence rules the next time they check in.
## Setting up a Channel
[Section titled âSetting up a Channelâ](#setting-up-a-channel)
During onboarding you create the first channel (most teams name it âProductionâ), but nothing is lockedâyou can rename or delete any channel at any time. To add additional channels later:
1. Go to the âChannelsâ section of the Capgo dashboard
2. Click the âNew Channelâ button
3. Enter a name for the channel and click âCreateâ
Channel names can be anything youâd like. A common strategy is to match channels to your development stages, such as:
* `Development` - for testing live updates on local devices or emulators
* `QA` - for your QA team to verify updates before wider release
* `Staging` - for final testing in a production-like environment
* `Production` - for the version of your app that end users receive from the app stores
## Configuring the Channel in Your App
[Section titled âConfiguring the Channel in Your Appâ](#configuring-the-channel-in-your-app)
With your channels created, you need to configure your app to listen to the appropriate channel. In this example, weâll use the `Development` channel.
Open your `capacitor.config.ts` (or `capacitor.config.json`) file. Under the `plugins` section, optionally set `defaultChannel` for **test builds** (internal / QA). For production builds, prefer omitting it so devices use the Cloud Default unless explicitly overridden.
```ts
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
// For a QA/TestFlight build â testers start on the Development channel automatically.
defaultChannel: 'Development',
// Production builds usually omit this so users attach to the Cloud Default channel.
},
},
};
```
Next, build your web app and run `npx cap sync` to copy the updated config file to your iOS, Android, and Electron projects. If you skip this sync step, your native projects will continue to use whichever channel they were previously configured for.
Caution
Channel selection order: Force > Override (`setChannel` / dashboard) > Config `defaultChannel` > Cloud Default.
Use `defaultChannel` only in test/internal builds; leave it out for production so users follow the Cloud Default (when set) instead of duplicating the routing in native config.
You can still force (pin) a device or apply an override laterâthose immediately supersede the config value.
> Channel names are case sensitive.
## Channel Options and Strategies
[Section titled âChannel Options and Strategiesâ](#channel-options-and-strategies)
Channels have several options that control who can receive updates and how updates are delivered. The most important ones are below. You can configure these from the web app, the CLI, or the Public API.
* Default channel: Optionally mark the channel or platform-specific channels that new devices attach to. See âDefault Channel Behaviorâ for routing scenarios.
* Platform filters: Enable or disable delivery to `iOS`, `Android`, or `Electron` devices per channel.
* Disable auto downgrade under native: Prevents sending an update when the deviceâs native app version is newer than the channelâs bundle (for example, device on 1.2.3 while channel has 1.2.2).
* Allow development builds: Permit updates to development builds (useful for testing).
* Allow emulator devices: Permit updates to emulators/simulators (useful for testing).
* Allow device selfâassignment: Lets the app switch to this channel at runtime using `setChannel`. If disabled, `setChannel` will fail for this channel.
### Disable Auto Update strategies
[Section titled âDisable Auto Update strategiesâ](#disable-auto-update-strategies)
Use this to restrict which kinds of updates the channel will automatically deliver. Options:
* major: Block crossâmajor updates (0.0.0 â 1.0.0). Minor and patch updates still allowed.
* minor: Block crossâminor updates (e.g., 1.1.0 â 1.2.0) and majors. Patch updates still allowed. Note: does not block 0.1.0 â 1.1.0.
* patch: Very strict. Allows only increasing patch versions within the same major and minor. Examples: 0.0.311 â 0.0.314 â , 0.1.312 â 0.0.314 â, 1.0.312 â 0.0.314 â.
* metadata: Require a minimum update version metadata on each bundle. Configure via CLI using `--min-update-version` or `--auto-min-update-version`. If missing, the channel is marked misconfigured and updates will be rejected until set.
* none: Allow all updates according to semver compatibility.
Learn more details and examples in Disable updates strategy at /docs/cli/commands/#disable-updates-strategy.
Example (CLI):
```bash
# Block major updates on the Production channel
npx @capgo/cli@latest channel set production com.example.app \
--disable-auto-update major
# Allow devices to self-assign to the Beta channel
npx @capgo/cli@latest channel set beta com.example.app --self-assign
```
### Using setChannel() from Your App
[Section titled âUsing setChannel() from Your Appâ](#using-setchannel-from-your-app)
The `setChannel()` method allows your app to programmatically switch channels at runtime. This is particularly useful for:
* QA/debug menus where testers can switch between channels
* Beta program opt-in flows
* Feature flag implementations
* A/B testing scenarios
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater';
// Switch to the beta channel
await CapacitorUpdater.setChannel({ channel: 'beta' });
// Optionally trigger an immediate update check after switching
await CapacitorUpdater.setChannel({
channel: 'beta',
triggerAutoUpdate: true
});
```
How setChannel() Works (v5.34.0+ / v6.34.0+ / v7.34.0+ / v8.0.0+)
When `setChannel()` is called:
1. **Backend validation (read-only)**: A request is sent to the Capgo backend to validate the channel is allowed (checking self-assignment permissions)
2. **Local storage update**: If validation passes, the channel is saved to the deviceâs local storage as `defaultChannel`
3. **Instant effect**: The next update check uses the new channel immediately (no waiting for replication)
**Why this matters:** In older versions, `setChannel()` saved the channel override to the backend database (same as Dashboard or API changes). Devices had to wait for backend replication (up to 2 minutes) before the channel change took effect. Now, `setChannel()` only reads from the backend (for validation) and stores locally, making channel switches instant.
**Security note:** Even if a channelâs permissions change after being set locally (e.g., self-assignment is disabled), the backend will still validate the channel during update checks, ensuring security is maintained.
**Comparison of channel change methods:**
| Method | Effect Time | Persisted Where | Use Case |
| -------------------------- | ----------- | ------------------- | -------------------------------------------- |
| `setChannel()` from plugin | **Instant** | Device only (local) | User-initiated channel switching in-app |
| Dashboard device override | Up to 2 min | Backend database | Admin-initiated changes for specific devices |
| API channel assignment | Up to 2 min | Backend database | Automated backend integrations |
For the best user experience when building channel-switching UIs, always use the pluginâs `setChannel()` method.
Minimum versions for local-only channel switching: **5.34.0**, **6.34.0**, **7.34.0**, or **8.0.0** (depending on your major version). Each minor version number corresponds to the same feature set across all major versions (e.g., X.34.0 includes the same features whether X is 5, 6, 7, or 8). See [plugin installation](/docs/getting-started/add-an-app/) for version tags.
## Assigning a Bundle to a Channel
[Section titled âAssigning a Bundle to a Channelâ](#assigning-a-bundle-to-a-channel)
To deploy a live update, you need to upload a new JS bundle build and assign it to a channel. You can do this in one step with the Capgo CLI:
```shell
npx @capgo/cli@latest bundle upload --channel=Development
```
This will upload your built web assets and set the new bundle as the active build for the `Development` channel. Any apps configured to listen to that channel will receive the update the next time they check for one.
You can also assign builds to channels from the âBundlesâ section of the Capgo dashboard. Click the menu icon next to a build and select âAssign to Channelâ to choose the channel for that build.
## Bundle Versioning and Channels
[Section titled âBundle Versioning and Channelsâ](#bundle-versioning-and-channels)
Itâs important to note that bundles in Capgo are global to your app, not specific to individual channels. The same bundle can be assigned to multiple channels.
When versioning your bundles, we recommend using semantic versioning [semver](https://semver.org/) with pre-release identifiers for channel-specific builds. For example, a beta release might be versioned as `1.2.3-beta.1`.
This approach has several benefits:
* It clearly communicates the relationship between builds. `1.2.3-beta.1` is obviously a pre-release of `1.2.3`.
* It allows for reusing version numbers across channels, reducing confusion.
* It enables clear rollback paths. If you need to roll back from `1.2.3`, you know `1.2.2` is the previous stable release.
Hereâs an example of how you might align your bundle versions with a typical channel setup:
* `Development` channel: `1.2.3-dev.1`, `1.2.3-dev.2`, etc.
* `QA` channel: `1.2.3-qa.1`, `1.2.3-qa.2`, etc.
* `Staging` channel: `1.2.3-rc.1`, `1.2.3-rc.2`, etc.
* `Production` channel: `1.2.3`, `1.2.4`, etc.
Using semver with pre-release identifiers is a recommended approach, but not strictly required. The key is to find a versioning scheme that clearly communicates the relationships between your builds and aligns with your teamâs development process.
## Rolling Back a Live Update
[Section titled âRolling Back a Live Updateâ](#rolling-back-a-live-update)
If you deploy a live update that introduces a bug or otherwise needs to be reverted, you can easily roll back to a previous build. From the âChannelsâ section of the dashboard:
1. Click the name of the channel you want to roll back
2. Find the build you want to revert to and click the crown icon 
3. Confirm the action
The selected build will immediately become the active build for that channel again. Apps will receive the rolled back version the next time they check for an update.
## Automating Deployments
[Section titled âAutomating Deploymentsâ](#automating-deployments)
For more advanced workflows, you can automate your live update deployments as part of your CI/CD pipeline. By integrating Capgo into your build process, you can automatically upload new bundles and assign them to channels whenever you push to certain branches or create new releases.
Check out the [CI/CD Integration](/docs/getting-started/cicd-integration/) docs to learn more about automating Capgo live updates.
## Deploying to a Device
[Section titled âDeploying to a Deviceâ](#deploying-to-a-device)
Now that you understand channels, youâre ready to start deploying live updates to real devices. The basic process is:
1. Install the Capgo SDK in your app
2. Configure the app to listen to your desired channel
3. Upload a build and assign it to that channel
4. Launch the app and wait for the update!
For a more detailed walkthrough, see the [Deploying Live Updates](/docs/getting-started/deploy/) guide. Happy updating!
## Advanced Channel Usage: User Segmentation
[Section titled âAdvanced Channel Usage: User Segmentationâ](#advanced-channel-usage-user-segmentation)
Channels can be used for more than just development stages. Theyâre a powerful tool for user segmentation, enabling features like:
* Feature flags for different user tiers
* A/B testing
* Gradual feature rollouts
* Beta testing programs
Learn how to implement these advanced use cases in our guide: [How to Segment Users by Plan and Channels for Feature Flags and A/B Testing](/blog/how-to-segment-users-by-plan-and-channels/).
# Using Capgo in China
> Learn how to configure Capgo Live Updates to work in China by using regional OST URLs for optimal performance and reliability.
If youâre deploying your app to users in China, youâll need to configure Capgo to use regional OST (Object Storage Technology) URLs to ensure reliable and fast updates.
## Why Use China-Specific URLs?
[Section titled âWhy Use China-Specific URLs?â](#why-use-china-specific-urls)
Due to network infrastructure and regulations in China (the Great Firewall), direct connections to international servers can be slow or unreliable. Capgo provides dedicated OST URLs with data located in Hong Kong to minimize latency and ensure your users receive updates as quickly and reliably as possible.
## Configuration
[Section titled âConfigurationâ](#configuration)
To configure Capgo for China, you need to set three specific URLs in your Capacitor configuration file. These URLs point to Capgoâs Hong Kong-based infrastructure.
1. Open your `capacitor.config.ts` file
2. Add the following configuration to the `CapacitorUpdater` plugin section:
```typescript
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
updateUrl: 'https://updater.capgo.com.cn/updates',
statsUrl: 'https://updater.capgo.com.cn/stats',
channelUrl: 'https://updater.capgo.com.cn/channel_self',
},
},
};
export default config;
```
3. Rebuild your app to apply the changes:
```shell
npm run build
npx cap sync
```
## Configuration Details
[Section titled âConfiguration Detailsâ](#configuration-details)
Hereâs what each URL does:
* **updateUrl**: `https://updater.capgo.com.cn/updates` - Used to check for and download available updates for your app
* **statsUrl**: `https://updater.capgo.com.cn/stats` - Used to report analytics and usage statistics back to Capgo
* **channelUrl**: `https://updater.capgo.com.cn/channel_self` - Used to retrieve channel configuration and determine which updates to apply
Tip
All three URLs must be configured together to ensure full functionality of the Capgo updater in China.
## Recommended Settings for China
[Section titled âRecommended Settings for Chinaâ](#recommended-settings-for-china)
Due to network performance limitations caused by the Great Firewall of China, we have specific recommendations for apps deployed in mainland China:
### Disable Direct Updates
[Section titled âDisable Direct Updatesâ](#disable-direct-updates)
We **strongly recommend disabling `directUpdate`** for apps in China. Network connectivity in China is less performant than in other regions, and direct updates (which apply immediately) can lead to a poor user experience if downloads are interrupted or slow.
Instead, use the default update behavior where updates download in the background and apply when the app backgrounds or restarts. This provides a more reliable experience for your users.
```typescript
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
directUpdate: false, // Recommended for China
updateUrl: 'https://updater.capgo.com.cn/updates',
statsUrl: 'https://updater.capgo.com.cn/stats',
channelUrl: 'https://updater.capgo.com.cn/channel_self',
},
},
};
```
Caution
While our Hong Kong-based infrastructure helps minimize latency and improve reliability, network performance to mainland China can still be affected by the Great Firewall. Disabling `directUpdate` helps ensure updates complete successfully without disrupting the user experience.
## Complete Configuration Example
[Section titled âComplete Configuration Exampleâ](#complete-configuration-example)
Hereâs a complete example with recommended settings for apps deployed in China:
```typescript
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'My App',
webDir: 'dist',
plugins: {
CapacitorUpdater: {
autoUpdate: true,
directUpdate: false, // Recommended: disable for better reliability in China
updateUrl: 'https://updater.capgo.com.cn/updates',
statsUrl: 'https://updater.capgo.com.cn/stats',
channelUrl: 'https://updater.capgo.com.cn/channel_self',
},
},
};
export default config;
```
## Testing Your Configuration
[Section titled âTesting Your Configurationâ](#testing-your-configuration)
After configuring the China-specific URLs, you can verify that updates are working correctly:
1. Upload a new bundle to Capgo:
```shell
npx @capgo/cli@latest bundle upload --channel=production
```
2. Install your app on a test device in China
3. Monitor the update process:
```shell
npx @capgo/cli@latest app debug
```
4. Check that updates are being downloaded from the China OST URLs
Note
The update behavior and timing remain the same as with standard Capgo configuration. See the [Update Behavior](/docs/live-updates/update-behavior/) documentation for details on how and when updates are applied.
## Multi-Region Deployment
[Section titled âMulti-Region Deploymentâ](#multi-region-deployment)
If your app serves users both inside and outside China, you can use the Chinese domain configuration for all users worldwide. The `updater.capgo.com.cn` domain is resolved globally thanks to Alibaba DNS infrastructure, making it accessible both inside China and everywhere else in the world.
### Using Chinese Domains Globally
[Section titled âUsing Chinese Domains Globallyâ](#using-chinese-domains-globally)
The Chinese domain URLs work seamlessly for multi-region apps:
```typescript
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
directUpdate: false, // Recommended for China users
updateUrl: 'https://updater.capgo.com.cn/updates',
statsUrl: 'https://updater.capgo.com.cn/stats',
channelUrl: 'https://updater.capgo.com.cn/channel_self',
},
},
};
```
This single configuration will work for:
* Users in mainland China (using Hong Kong-based infrastructure)
* Users outside China (accessing the same infrastructure via Alibaba DNS)
**Performance Considerations:**
While the `.cn` domain is resolved globally through Alibaba DNS and works everywhere, itâs slightly less performant for users outside China compared to the standard domain (`api.capgo.app`), which is resolved directly by Cloudflare where our backend is hosted. However, DNS resolution is fast, so the performance difference is minimal and wonât significantly impact the user experience.
Tip
Using the `.cn` domain for all users simplifies your deployment and ensures consistent update behavior across all regions. You donât need separate builds or environment-based configurations. The small performance trade-off outside China is typically worth the simplified deployment.
### Alternative: Region-Specific Configurations
[Section titled âAlternative: Region-Specific Configurationsâ](#alternative-region-specific-configurations)
If you prefer to optimize differently for each region, you can also consider:
* Building separate app variants with different configurations
* Using environment-based configuration to dynamically set the URLs
* Creating different release channels for different regions
If you need assistance with multi-region deployment strategies, please contact us at or join our [Discord community](https://discord.capgo.app) for help.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
If you experience issues with updates in China:
1. **Verify your configuration** - Double-check that all three URLs are correctly set in your `capacitor.config.ts`
2. **Check network connectivity** - Ensure your device can reach the `updater.capgo.com.cn` domain
3. **Review logs** - Use `npx @capgo/cli@latest app debug` to check for error messages
4. **Test updates** - Try uploading a new bundle and monitoring the download process
5. **Contact support** - If issues persist, reach out to us at or join our [Discord community](https://discord.capgo.app) for assistance
Caution
Make sure to use the `.cn` domain (`updater.capgo.com.cn`) and not the standard international domain when configuring for China.
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Update Behavior](/docs/live-updates/update-behavior/) to customize when updates are applied
* Explore [Channels](/docs/live-updates/channels/) to manage different release tracks
* Review [Encryption](/docs/live-updates/encryption/) to secure your updates
# Compliance
> Learn about Capgo's privacy practices, data collection, security compliance, and how we protect your users' information during live updates.
Capgo is designed with privacy, security, and compliance in mind. This document explains what data is collected, how itâs used, and what measures are in place to protect your usersâ privacy and ensure regulatory compliance when using Capgoâs live update service.
## Data Collection Overview
[Section titled âData Collection Overviewâ](#data-collection-overview)
Capgo collects minimal data necessary to provide the live update service effectively. The data collection is focused on operational requirements rather than user tracking or analytics.
### What Data is Collected
[Section titled âWhat Data is Collectedâ](#what-data-is-collected)
Capgo collects only the data that is necessary to provide the live updates feature. When your app checks for updates or downloads new bundles, the following information is collected:
* **App ID**: A unique identifier for your app that is used to associate the app with the correct account
* **App Version Code**: The version code of the app that is used to determine which updates are compatible with the app
* **App Version Name**: The version name of the app that is used for display purposes
* **Platform**: The platform (iOS, Android, Electron) of the app that is used to determine which updates are compatible with the app
* **Device ID**: A unique identifier for the device that is used to deliver updates to a specific device and for billing purposes. This identifier is a random string that is created when the app is started for the first time. **Starting from plugin version v5.10.0, v6.25.0 and v7.25.0**, the device ID now persists across app reinstalls (stored securely in Keychain on iOS, EncryptedSharedPreferences on Android, and Electron secure storage) to provide better device tracking while maintaining compliance with app store guidelines. Prior to these versions, the device ID was reset with every app installation
* **Bundle ID**: The unique identifier for the bundle that is currently installed on the device
* **Channel Name**: The name of the channel that is selected to receive updates
* **OS Version**: The version of the operating system that is used to determine which updates are compatible with the device
* **Plugin Version**: The version of the @capgo/capacitor-updater plugin that is used to deliver updates to the device
**Additional Technical Data:**
* Update check timestamps
* Download success/failure status
* Bundle installation status
* Rollback events and reasons
* IP address (for geolocation and CDN optimization)
Note
You can verify the data that is collected by inspecting the source code of the @capgo/capacitor-updater plugin, which is open-source and available on [GitHub](https://github.com/Cap-go/capacitor-updater). Capgo does not collect personally identifiable information (PII) such as names, email addresses, phone numbers, or persistent device identifiers that can be used to track individual users across apps.
### What Data is NOT Collected
[Section titled âWhat Data is NOT Collectedâ](#what-data-is-not-collected)
Capgo explicitly does not collect:
* Personal user information or credentials
* App usage analytics or user behavior data
* Content from your app or user-generated data
* Location data beyond general geographic region
* Persistent device identifiers for tracking
* Biometric or sensitive personal data
## Data Usage and Purpose
[Section titled âData Usage and Purposeâ](#data-usage-and-purpose)
The data collected by Capgo is used exclusively for:
### Service Operation
[Section titled âService Operationâ](#service-operation)
* Determining which updates are available for specific app versions
* Optimizing content delivery through geographic CDN selection
* Ensuring compatibility between updates and device capabilities
* Managing update rollouts and channel assignments
### Service Improvement
[Section titled âService Improvementâ](#service-improvement)
* Monitoring update success rates and identifying issues
* Optimizing download performance and reliability
* Improving the overall update delivery system
* Debugging and troubleshooting update failures
### Security and Integrity
[Section titled âSecurity and Integrityâ](#security-and-integrity)
* Preventing abuse and ensuring service availability
* Validating update authenticity and integrity
* Protecting against malicious or corrupted updates
* Maintaining service security and stability
## Data Storage and Retention
[Section titled âData Storage and Retentionâ](#data-storage-and-retention)
### Storage Location
[Section titled âStorage Locationâ](#storage-location)
* Update bundles and metadata are stored on secure cloud infrastructure
* Data is distributed across multiple geographic regions for performance
* All data transmission is encrypted using industry-standard protocols (HTTPS/TLS)
### Data Retention
[Section titled âData Retentionâ](#data-retention)
* Update check logs are retained for operational purposes (typically 30-90 days)
* Bundle files are retained as long as theyâre assigned to active channels
* Aggregated, non-personal metrics may be retained longer for service improvement
* Personal data, if any, is deleted according to applicable data protection laws
### Data Security
[Section titled âData Securityâ](#data-security)
* All data is encrypted in transit and at rest
* Access to data is restricted to authorized personnel only
* Regular security audits and monitoring are performed
* Industry-standard security practices are followed
* **SOC 2 Certification**: Capgo is currently SOC 2 Type II certified, ensuring the highest standards of security, availability, and confidentiality. View our compliance status at [trust.capgo.app](https://trust.capgo.app)
* **Continuous Code Auditing**: Every commit is automatically audited by [SonarCloud](https://sonarcloud.io/summary/overall?id=Cap-go_capacitor-updater\&branch=main) for the [plugin](https://sonarcloud.io/summary/overall?id=Cap-go_capgo\&branch=main) and [backend](https://sonarcloud.io/summary/overall?id=Cap-go_capgo\&branch=main), ensuring code quality, security vulnerabilities detection, and maintainability
* **Vulnerability Scanning**: Additional security scanning is performed by [Snyk](https://snyk.io/test/github/Cap-go/capgo) to detect and remediate security vulnerabilities in dependencies
* **Infrastructure Security**: Our hosting infrastructure is continuously monitored and verified through [hosting security checks](https://hosting-checker.net/websites/api.capgo.app)
* **AI-Powered Code Review**: Every pull request is reviewed by CodeRabbit AI to catch potential issues, security concerns, and maintain code quality standards
## Privacy Controls
[Section titled âPrivacy Controlsâ](#privacy-controls)
### For App Developers
[Section titled âFor App Developersâ](#for-app-developers)
As a Capgo user, you have control over:
* **Channel Management**: Control which updates are distributed to which users
* **Data Minimization**: Configure what device information is shared
* **Geographic Controls**: Manage where your updates are distributed
* **Retention Settings**: Control how long update data is retained
### For End Users
[Section titled âFor End Usersâ](#for-end-users)
Your app users benefit from:
* **Minimal Data Collection**: Only essential data for update delivery is collected
* **No Tracking**: No cross-app or persistent user tracking
* **Transparency**: This privacy policy explains exactly what data is collected
* **Security**: All data transmission is encrypted and secure
## Compliance and Legal
[Section titled âCompliance and Legalâ](#compliance-and-legal)
### Data Protection Regulations
[Section titled âData Protection Regulationsâ](#data-protection-regulations)
Capgo is designed to comply with major data protection regulations including:
* **GDPR** (General Data Protection Regulation)
* **CCPA** (California Consumer Privacy Act)
* **COPPA** (Childrenâs Online Privacy Protection Act)
* Other applicable regional privacy laws
### App Store Compliance
[Section titled âApp Store Complianceâ](#app-store-compliance)
Capgo strictly adheres to app store guidelines and policies:
* **Apple App Store**: Complies with [App Store Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) section 3.3.2, ensuring that live updates only modify the appâs behavior in ways that are consistent with the submitted app
* **Google Play Store**: Follows [Google Play Developer Policy](https://play.google.com/about/developer-content-policy/) requirements for dynamic code loading and app updates
* **Content Restrictions**: Live updates cannot introduce functionality that wasnât present in the original app submission or violate platform-specific content policies
* **Security Requirements**: All updates maintain the same security posture and permissions as the original app
### Your Responsibilities
[Section titled âYour Responsibilitiesâ](#your-responsibilities)
As an app developer using Capgo, you should:
* Include appropriate privacy disclosures in your appâs privacy policy
* Inform users about the use of live update services
* Ensure compliance with applicable laws in your jurisdiction
* Implement appropriate consent mechanisms if required
Tip
**No Additional Privacy Implementation Required**: Capgo is designed to be privacy-compliant by default. You donât need to implement any additional privacy controls or data handling mechanisms in your app code. The minimal data collection and privacy-by-design approach means that integrating Capgo typically doesnât require changes to your existing privacy declarations or policies.
## Privacy by Design
[Section titled âPrivacy by Designâ](#privacy-by-design)
Capgo follows privacy-by-design principles:
### Data Minimization
[Section titled âData Minimizationâ](#data-minimization)
* Only collect data that is absolutely necessary for service operation
* Avoid collecting personal or sensitive information
* Use aggregated and anonymized data where possible
### Purpose Limitation
[Section titled âPurpose Limitationâ](#purpose-limitation)
* Use collected data only for the stated purposes
* Do not repurpose data for unrelated activities
* Maintain clear boundaries on data usage
### Transparency
[Section titled âTransparencyâ](#transparency)
* Provide clear information about data collection and usage
* Make privacy practices easily accessible and understandable
* Regularly update privacy documentation
## Contact and Questions
[Section titled âContact and Questionsâ](#contact-and-questions)
If you have questions about Capgoâs privacy practices or need to report a privacy concern:
* Review our full Privacy Policy at [capgo.app/privacy](https://capgo.app/privacy)
* View our security and compliance status at [capgo.app/trust](https://capgo.app/trust)
* Contact our privacy team through the support channels
* Report any privacy-related issues through our security contact
Tip
Remember to update your own appâs privacy policy to reflect the use of Capgoâs live update service and any data collection that may occur as part of the update process.
## Best Practices for Privacy
[Section titled âBest Practices for Privacyâ](#best-practices-for-privacy)
When implementing Capgo in your app:
1. **Be Transparent**: Inform users about the live update functionality
2. **Minimize Data**: Only enable data collection features you actually need
3. **Secure Implementation**: Follow security best practices in your integration
4. **Regular Reviews**: Periodically review your privacy practices and update policies
5. **User Control**: Consider providing users with options to control update behavior
By following these practices and understanding Capgoâs privacy approach, you can provide your users with a secure, privacy-respecting live update experience.
# Custom Storage
> Learn how to use custom storage solutions with Capgo Live Updates, including external URLs, S3 integration, and bundle encryption for secure deployments.
Capgo supports custom storage solutions for your app bundles, allowing you to host your updates on your own infrastructure or third-party storage services. This is particularly useful for organizations with specific security requirements, compliance needs, or existing storage infrastructure.
## Overview
[Section titled âOverviewâ](#overview)
Custom storage in Capgo works by uploading your bundle to an external location and providing Capgo with the URL to access it. The Capgo SDK will then download updates directly from your custom storage location instead of Capgoâs default cloud storage.
Tip
Custom storage is ideal for:
* Organizations with strict data residency requirements
* Teams with existing CDN or storage infrastructure
* Applications requiring additional security layers
* Cost optimization for large bundle sizes
## External URL Upload
[Section titled âExternal URL Uploadâ](#external-url-upload)
The simplest way to use custom storage is by uploading your bundle to any publicly accessible URL and providing that URL to Capgo.
### Basic External URL Upload
[Section titled âBasic External URL Uploadâ](#basic-external-url-upload)
```shell
npx @capgo/cli@latest bundle upload --external https://your-domain.com/bundles/v1.2.3.zip
```
This command tells Capgo to reference the bundle at the specified URL instead of uploading it to Capgoâs cloud storage.
### With Encryption
[Section titled âWith Encryptionâ](#with-encryption)
For secure external storage, you can encrypt your bundle and provide the decryption keys:
```shell
npx @capgo/cli@latest bundle upload --external https://your-domain.com/bundles/v1.2.3.zip --iv-session-key YOUR_IV_SESSION_KEY
```
## S3 Integration
[Section titled âS3 Integrationâ](#s3-integration)
Capgo provides built-in support for Amazon S3 and S3-compatible storage services. The CLI can automatically upload your bundle to S3 and configure Capgo to use the S3 URL.
### S3 Upload Options
[Section titled âS3 Upload Optionsâ](#s3-upload-options)
```shell
npx @capgo/cli@latest bundle upload \
--s3-region us-east-1 \
--s3-apikey YOUR_ACCESS_KEY \
--s3-apisecret YOUR_SECRET_KEY \
--s3-bucket-name your-bucket-name
```
### Complete S3 Configuration
[Section titled âComplete S3 Configurationâ](#complete-s3-configuration)
For S3-compatible services or custom endpoints:
```shell
npx @capgo/cli@latest bundle upload \
--s3-region us-east-1 \
--s3-apikey YOUR_ACCESS_KEY \
--s3-apisecret YOUR_SECRET_KEY \
--s3-endpoint https://s3.your-provider.com \
--s3-bucket-name your-bucket-name \
--s3-port 443 \
--no-s3-ssl # Only if your endpoint doesn't support SSL
```
### S3 Configuration Parameters
[Section titled âS3 Configuration Parametersâ](#s3-configuration-parameters)
| Parameter | Description | Required |
| ------------------ | ----------------------------- | -------- |
| `--s3-region` | AWS region for your S3 bucket | Yes |
| `--s3-apikey` | S3 access key ID | Yes |
| `--s3-apisecret` | S3 secret access key | Yes |
| `--s3-bucket-name` | Name of your S3 bucket | Yes |
| `--s3-endpoint` | Custom S3 endpoint URL | No |
| `--s3-port` | Port for S3 endpoint | No |
| `--no-s3-ssl` | Disable SSL for S3 upload | No |
## Bundle Preparation and Encryption
[Section titled âBundle Preparation and Encryptionâ](#bundle-preparation-and-encryption)
When using custom storage, especially with encryption, you need to prepare your bundles properly. This involves creating a zip file and optionally encrypting it.
### Step 1: Create a Zip Bundle
[Section titled âStep 1: Create a Zip Bundleâ](#step-1-create-a-zip-bundle)
First, create a zip file of your app bundle:
```shell
npx @capgo/cli@latest bundle zip com.example.app --path ./dist
```
The zip command will return the checksum of the zip file. You can use this checksum to encrypt the zip file if needed. Use the `--json` option to get structured output including the checksum.
#### Zip Command Options
[Section titled âZip Command Optionsâ](#zip-command-options)
```shell
npx @capgo/cli@latest bundle zip [appId] \
--path ./dist \
--bundle 1.2.3 \
--name myapp-v1.2.3 \
--json \
--no-code-check \
--key-v2 \
--package-json ../../package.json,./package.json
```
| Option | Description |
| ----------------- | -------------------------------------------------------------------- |
| `--path` | Path to the folder to zip (defaults to webDir from capacitor.config) |
| `--bundle` | Bundle version number to name the zip file |
| `--name` | Custom name for the zip file |
| `--json` | Output results in JSON format (includes checksum) |
| `--no-code-check` | Skip checking for notifyAppReady() call and index file |
| `--key-v2` | Use encryption v2 |
| `--package-json` | Paths to package.json files for monorepos (comma separated) |
### Step 2: Encrypt the Bundle (Optional)
[Section titled âStep 2: Encrypt the Bundle (Optional)â](#step-2-encrypt-the-bundle-optional)
For enhanced security, encrypt your zip bundle before uploading:
```shell
# Using default local key
npx @capgo/cli@latest bundle encrypt ./myapp.zip CHECKSUM
# Using custom key file
npx @capgo/cli@latest bundle encrypt ./myapp.zip CHECKSUM --key ./path/to/.capgo_key_v2
# Using key data directly
npx @capgo/cli@latest bundle encrypt ./myapp.zip CHECKSUM --key-data "PRIVATE_KEY_CONTENT"
```
The `CHECKSUM` parameter is required and should be the checksum of your zip file. You can get the checksum from the zip command output (use `--json` option for structured output).
By default, the encrypt command will use your local private signing key. You can specify a custom key using the `--key` or `--key-data` options.
The encrypt command will return the `ivSessionKey` needed for upload or decryption.
#### Encryption Command Options
[Section titled âEncryption Command Optionsâ](#encryption-command-options)
| Option | Description |
| ------------ | ------------------------------------------------------------------------- |
| `zipPath` | Path to the zip file to encrypt (required) |
| `checksum` | Checksum of the zip file (required) - get it from zip command |
| `--key` | Custom path for private signing key (optional, uses local key by default) |
| `--key-data` | Private signing key data directly (optional) |
| `--json` | Output results in JSON format |
Caution
The encrypt command will output an `ivSessionKey` that youâll need to provide when uploading with the `--iv-session-key` option.
## Complete Workflow Examples
[Section titled âComplete Workflow Examplesâ](#complete-workflow-examples)
### Example 1: External URL with Encryption
[Section titled âExample 1: External URL with Encryptionâ](#example-1-external-url-with-encryption)
1. **Build your app:**
```shell
npm run build
```
2. **Create a zip bundle:**
```shell
npx @capgo/cli@latest bundle zip com.example.app --path ./dist --bundle 1.2.3
```
Note the checksum returned by this command.
3. **Encrypt the bundle:**
```shell
npx @capgo/cli@latest bundle encrypt ./com.example.app-1.2.3.zip CHECKSUM_FROM_STEP_2
```
Note the `ivSessionKey` from the output.
4. **Upload to your storage:** Upload the encrypted zip file to your hosting service.
5. **Register with Capgo:**
```shell
npx @capgo/cli@latest bundle upload \
--external https://your-cdn.com/bundles/com.example.app-1.2.3.zip \
--iv-session-key IV_SESSION_KEY_FROM_STEP_3
```
### Example 2: Direct S3 Upload
[Section titled âExample 2: Direct S3 Uploadâ](#example-2-direct-s3-upload)
1. **Build your app:**
```shell
npm run build
```
2. **Upload directly to S3:**
```shell
npx @capgo/cli@latest bundle upload \
--s3-region us-west-2 \
--s3-apikey YOUR_ACCESS_KEY \
--s3-apisecret YOUR_SECRET_KEY \
--s3-bucket-name your-app-bundles \
--channel Production
```
### Example 3: S3 with Encryption
[Section titled âExample 3: S3 with Encryptionâ](#example-3-s3-with-encryption)
1. **Build and zip:**
```shell
npm run build
npx @capgo/cli@latest bundle zip com.example.app --path ./dist --key-v2
```
2. **Encrypt the bundle:**
```shell
npx @capgo/cli@latest bundle encrypt ./com.example.app.zip CHECKSUM
```
3. **Upload to S3 with encryption:**
```shell
npx @capgo/cli@latest bundle upload \
--s3-region us-west-2 \
--s3-apikey YOUR_ACCESS_KEY \
--s3-apisecret YOUR_SECRET_KEY \
--s3-bucket-name your-app-bundles \
--iv-session-key IV_SESSION_KEY_FROM_STEP_2 \
--channel Production
```
## Security Considerations
[Section titled âSecurity Considerationsâ](#security-considerations)
When using custom storage, consider these security best practices:
### Access Control
[Section titled âAccess Controlâ](#access-control)
* Ensure your storage URLs are accessible to your app users but not publicly discoverable
* Use signed URLs or token-based authentication when possible
* Implement proper CORS headers for web-based apps
### Encryption
[Section titled âEncryptionâ](#encryption)
* Always encrypt sensitive bundles using the Capgo encryption tools
* Store encryption keys securely and rotate them regularly
* Use HTTPS for all bundle URLs (required for mobile and Electron apps)
### Monitoring
[Section titled âMonitoringâ](#monitoring)
* Monitor access logs to detect unusual download patterns
* Set up alerts for failed bundle downloads
* Regularly audit your storage permissions
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Common Issues
[Section titled âCommon Issuesâ](#common-issues)
**Bundle not downloading:**
* Verify the URL is publicly accessible and uses HTTPS (required for mobile and Electron apps)
* Check CORS headers for web apps
* Ensure the bundle format is correct
**Encryption errors:**
* Verify the `ivSessionKey` matches the encrypted bundle
* Check that the bundle was encrypted with the correct key
* Ensure encryption v2 is used for new bundles
**S3 upload failures:**
* Verify your S3 credentials and permissions
* Check bucket policies and CORS configuration
* Ensure the specified region is correct
### Debug Commands
[Section titled âDebug Commandsâ](#debug-commands)
Check bundle status:
```shell
npx @capgo/cli@latest app debug
```
Verify bundle integrity:
```shell
npx @capgo/cli@latest bundle list
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Channels](/docs/live-updates/channels/) to manage different deployment environments
* Explore [Update Behavior](/docs/live-updates/update-behavior/) to customize how updates are applied
* Set up [CI/CD Integration](/docs/getting-started/cicd-integration/) to automate your custom storage workflow
# Delta updates
> Learn how Capgo's Delta (manifest) updates optimize data transfer by only sending changed files, enhancing performance on slower networks.
Capgoâs Live Update system can deliver updates faster and more efficiently by only sending the changed files, rather than the entire JS bundle.
This is especially beneficial for users on slower or metered network connections, as it minimizes the amount of data that needs to be downloaded.
A second benefit is when the app have large assets who change rarely, like images or videos, compare to zipped JS files it will be downloaded only once.
## How Delta (Manifest) Updates Work
[Section titled âHow Delta (Manifest) Updates Workâ](#how-delta-manifest-updates-work)
Delta (manifest) updates in Capgo are handled by the Capgo plugin installed in your app. When you upload a new version of your app using the `--delta` flag, Capgo does the following:
1. Each file in your build is uploaded individually
2. Checksums are generated for each file
3. A new json manifest is created, listing all files and their checksums
4. This manifest is uploaded to the Capgo database
When a device running your app checks for an update, the Capgo plugin receives the new manifest from the server. It compares this manifest to the one it currently has, identifying which files have changed based on the checksums and file paths.
The plugin then downloads only the changed files, rather than the entire JS bundle. It reconstructs the new version of the app by combining these downloaded files with the unchanged files it already has.
Manifest
In case of Delta (manifest) updates, the device stores all downloaded files in a common cache. Capgo never cleans it, but the OS can at any time.
## Enabling Delta (Manifest) Updates
[Section titled âEnabling Delta (Manifest) Updatesâ](#enabling-delta-manifest-updates)
To enable Delta (manifest) updates for your Capgo app, simply use the `--delta` flag when uploading a new version:
```shell
npx @capgo/cli@latest bundle upload --delta
```
If `directUpdate` is enabled in your `capacitor.config`, the CLI detects it. In non-interactive environments it sends Delta (manifest) updates automatically, and in interactive environments it prompts you to confirm before uploading. Use `--no-delta` to force a full bundle upload.
## Enforcing Delta (Manifest) Updates
[Section titled âEnforcing Delta (Manifest) Updatesâ](#enforcing-delta-manifest-updates)
If you want to ensure that all uploads are Delta (manifest) updates and prevent any accidental full bundle uploads, you can use the `--delta-only` flag:
```shell
npx @capgo/cli@latest bundle upload --delta-only
```
When `--delta-only` is used, Capgo will only upload individual files and generate a manifest. Any device that does not support Delta (manifest) updates will not be able to download the update.
You might want to use `--delta-only` if:
* You always want to use Delta (manifest) updates and never want to allow full bundle uploads
* Youâre setting up a CI/CD pipeline and want to ensure all automated uploads are Delta (manifest)
* Your app is large and bandwidth is constrained, so you need to minimize upload/download sizes
If you need to do a full bundle upload while `--delta-only` is set, simply run the upload command without `--delta-only`. This will override the setting for that single upload, allowing you to push a complete bundle when needed.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
If Delta (manifest) updates donât seem to be working (i.e. devices are always downloading the full JS bundle even for small changes), double check that:
* Youâre using the `--delta` flag every time you upload a new version
* If using `--delta-only`, make sure you havenât accidentally omitted the `--delta` flag
* Your device is running the latest version of the Capgo plugin
* Your device has a stable network connection and can reach the Capgo servers
You can also use the Capgo webapp to check the details of your last upload:
1. Go to the [webapp](https://app.capgo.io)
2. Click on your app
3. Click on the bundles number of the stats bar.
4. Select the last bundle
5. Check the `Partial` field 
If you continue to have trouble, please reach out to Capgo support for further assistance. They can check the server logs to confirm that your Delta (manifest) uploads are being processed correctly and that devices are receiving the updated manifests.
Thatâs it! The `--delta` flag tells Capgo to perform the individual file uploads and manifest generation needed for Delta (manifest) updates.
Note that you need to use `--delta` every time you upload a new version that you want to be delivered as a Delta (manifest) update. If you omit the flag, Capgo will upload the entire JS bundle as a single file, and devices will download the whole bundle even if only a small part has changed.
# Encryption
> Learn how Capgo's end-to-end encryption secures your app bundles during transmission and storage, protecting your code and user data.
Capgo provides robust end-to-end encryption for your app bundles, ensuring that your JavaScript code and assets are protected during transmission and storage. This encryption system is designed to give you complete control over your appâs security while maintaining the convenience of live updates.
## Overview
[Section titled âOverviewâ](#overview)
Capgoâs encryption system uses industry-standard cryptographic methods to protect your bundles from unauthorized access. When encryption is enabled, your bundles are encrypted before leaving your development environment and remain encrypted until theyâre decrypted by your app on the userâs device.
**What Encryption Actually Protects**: Unlike OTA systems that only sign updates, Capgo encrypts the uploaded bundle before storage and delivery. This protects the bundle contents from casual access in storage or transit and ensures only someone with your private key can produce a valid encrypted update. It does **not** make shipped web assets impossible to reverse engineer: the public key used by the client to decrypt updates is distributed in the app, so a determined attacker can still extract it and inspect bundle contents with enough effort.
When You Need Encryption
If you upload a bundle without encryption, treat it as a public asset. Private channels limit which devices receive an update, but they do not make the uploaded bundle confidential. Encryption is useful when you want better protection in storage and transit and when you want only holders of the private key to be able to publish valid encrypted updates. It does not guarantee that shipped JavaScript, HTML, or CSS can never be inspected.
Threat Model
Capgo encryption protects against bundle disclosure by Capgo, storage providers, CDNs, or anyone who only sees the encrypted delivery artifact. It also prevents third parties from generating valid encrypted updates without your private key. Because the public key is embedded in the distributed app so the client can decrypt updates, someone who has your app binary and enough motivation can still recover the key material needed to inspect the bundle.
Tip
Encryption is particularly important for:
* Apps handling sensitive data or business logic
* Enterprise applications with compliance requirements
* Apps deployed in regulated industries
* Organizations with strict security policies
## How Encryption Works
[Section titled âHow Encryption Worksâ](#how-encryption-works)
Capgo uses a hybrid encryption approach that combines RSA and AES encryption for optimal security and performance:

### 1. Key Generation
[Section titled â1. Key Generationâ](#1-key-generation)
* **Private Key**: Generated and stored securely in your development environment (used for encryption)
* **Public Key**: Derived from your private key and stored in your appâs Capacitor config (used for decryption)
* **Session Keys**: Random AES keys generated for each bundle upload
### 2. Encryption Process
[Section titled â2. Encryption Processâ](#2-encryption-process)
1. A random AES session key is generated for each bundle upload
2. Your bundle is encrypted using the AES session key
3. The bundle checksum is calculated
4. Both the AES session key and checksum are encrypted together using your RSA private key (creating the âsignatureâ)
5. The encrypted bundle and encrypted signature are stored
The checksum is encrypted alongside the AES key to prevent tampering. Since only your RSA private key can create this signature, and only the corresponding public key can decrypt it, this ensures that both the AES session key and the expected checksum are authentic and havenât been modified by an attacker.
### 3. Decryption Process
[Section titled â3. Decryption Processâ](#3-decryption-process)
1. Your app downloads the encrypted bundle and encrypted signature
2. The Capgo SDK uses your RSA public key (stored in the app) to decrypt the signature
3. This reveals the AES session key and the original checksum
4. The AES session key is used to decrypt the bundle
5. A checksum of the decrypted bundle is calculated and compared with the original checksum for integrity verification
This process ensures that even if an attacker intercepts the encrypted bundle, they cannot modify the AES session key or provide a fake checksum, because they would need your private key to create a valid signature that the public key can decrypt.
Tip
RSA cannot encrypt large amounts of data efficiently, so AES is used for the actual bundle encryption while RSA secures the AES key and provides integrity verification through checksum signing.
## Capgo vs Other Platforms
[Section titled âCapgo vs Other Platformsâ](#capgo-vs-other-platforms)
| Feature | Capgo | Other OTA Platforms |
| ------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------- |
| **Bundle Content** | Encrypted in storage/transit; still inspectable by a determined reverse engineer with the app binary | Publicly readable |
| **Security Method** | True end-to-end encryption | Code signing only |
| **Privacy Level** | Strong delivery/storage protection; not anti-reverse-engineering | Platform can access your code |
| **Protection** | Content + integrity + authenticity | Integrity + authenticity only |
**Why This Matters:**
* **Code signing** only verifies that updates havenât been tampered with and come from the right source
* **Capgo encryption** protects the bundle while it is stored and delivered and makes forged encrypted updates much harder because the attacker would need your private key
* **Reverse engineering is still possible** after the app ships, because the client contains the public key needed to decrypt and load the update
## Encryption Methods
[Section titled âEncryption Methodsâ](#encryption-methods)
Capgo uses Encryption V2 as the standard encryption method:
### Encryption V2 (Current Standard)
[Section titled âEncryption V2 (Current Standard)â](#encryption-v2-current-standard)
* Uses RSA-4096 for enhanced security
* AES-256-GCM for authenticated encryption
* Provides integrity verification
* Better performance and security
### Encryption V1 (Deprecated)
[Section titled âEncryption V1 (Deprecated)â](#encryption-v1-deprecated)
* Uses RSA-2048 for key encryption
* AES-256-CBC for bundle encryption
* **No longer available in the current CLI**
* Legacy apps using V1 must migrate to V2
Danger
Encryption V1 is no longer supported in the current Capgo CLI. If youâre using V1 encryption, you must migrate to V2. See the [migration guide](/docs/cli/migrations/encryption/) for detailed instructions.
## Setting Up Encryption
[Section titled âSetting Up Encryptionâ](#setting-up-encryption)
### Step 1: Generate Encryption Keys
[Section titled âStep 1: Generate Encryption Keysâ](#step-1-generate-encryption-keys)
First, generate your encryption keys using the Capgo CLI:
```shell
# Generate new encryption keys (creates files in current directory)
npx @capgo/cli@latest key create
```
This creates:
* `.capgo_key_v2`: Your private key (keep this secure!)
* `.capgo_key_v2.pub`: Your public key (used by your app)
These files are created in the current directory where you run the command.
Caution
**Important Storage Notes:**
* **Private Key (`.capgo_key_v2`)**: Never commit this to version control. This file should be kept secure and used only for encryption during bundle uploads.
* **Public Key (`.capgo_key_v2.pub`)**: This is safe to commit to version control as itâs a backup of your public key.
* **File Location**: Keys are created in the current directory where you run the `key create` command.
* **Public Key in Config**: You must run `key save` to store the public key in your Capacitor config for the mobile app to use.
For production use, store the private key securely (environment variables, key management services) and remove it from your local project after setup.
### Step 2: Save Your Public Key to Capacitor Config (Required)
[Section titled âStep 2: Save Your Public Key to Capacitor Config (Required)â](#step-2-save-your-public-key-to-capacitor-config-required)
You **must** save your public key to the Capacitor config so your mobile app can decrypt bundles:
```shell
# Save public key from file to Capacitor config (required)
npx @capgo/cli@latest key save --key ./.capgo_key_v2.pub
# Or save public key data directly
npx @capgo/cli@latest key save --key-data "$CAPGO_PUBLIC_KEY"
```
### Step 3: Sync Capacitor Platform (Required)
[Section titled âStep 3: Sync Capacitor Platform (Required)â](#step-3-sync-capacitor-platform-required)
After saving the public key, you **must** sync the Capacitor platform to copy the updated config to the native layer:
```shell
# Sync the platform to copy config to native
npx cap sync
```
Caution
**Required Steps**:
1. The `key save` command stores the public key in your Capacitor config
2. `npx cap sync` copies this config to the native layer where the mobile app can access it
3. Without both steps, your app wonât be able to decrypt encrypted updates
## Encrypting Bundles
[Section titled âEncrypting Bundlesâ](#encrypting-bundles)
### Method 1: Encrypt During Upload
[Section titled âMethod 1: Encrypt During Uploadâ](#method-1-encrypt-during-upload)
The simplest way is to encrypt during the upload process:
```shell
# Upload with automatic encryption
npx @capgo/cli@latest bundle upload --key-v2
# For external storage, you must encrypt first (see Manual Encryption Workflow below)
```
### Method 2: Manual Encryption Workflow
[Section titled âMethod 2: Manual Encryption Workflowâ](#method-2-manual-encryption-workflow)
For more control, you can manually encrypt bundles:
1. **Create a zip bundle:**
```shell
npx @capgo/cli@latest bundle zip com.example.app --path ./dist --key-v2
```
2. **Encrypt the bundle:**
```shell
npx @capgo/cli@latest bundle encrypt ./com.example.app.zip CHECKSUM_FROM_STEP_1
```
3. **Upload to your storage (e.g., S3) and register with Capgo:**
```shell
# First upload the encrypted bundle to your storage (e.g., AWS S3)
aws s3 cp ./encrypted-bundle.zip s3://your-bucket/encrypted-bundle.zip
# Then register with Capgo using the external URL
npx @capgo/cli@latest bundle upload --external https://your-storage.com/encrypted-bundle.zip --iv-session-key IV_SESSION_KEY_FROM_STEP_2
```
## Key Management
[Section titled âKey Managementâ](#key-management)
### Storing Keys Securely
[Section titled âStoring Keys Securelyâ](#storing-keys-securely)
**Private Key Options:**
1. **File-based (local development):**
```shell
# Key stored as .capgo_key_v2 file in project root
npx @capgo/cli@latest bundle upload --key-v2
```
2. **Environment variable (CI/CD):**
```shell
# Store in environment variable for CI
export CAPGO_PRIVATE_KEY="$(cat .capgo_key_v2)"
npx @capgo/cli@latest bundle upload --key-data-v2 "$CAPGO_PRIVATE_KEY"
```
**Public Key Setup (Required):**
```shell
# Must save public key to Capacitor config for mobile app
npx @capgo/cli@latest key save --key ./.capgo_key_v2.pub
```
**Production Environment:**
* Store private keys in secure key management services (AWS KMS, Azure Key Vault, etc.)
* Use CI/CD secret management for private keys
* Never commit private keys to version control
**Key Usage:**
* **Private Key**: Used by CLI for encryption during bundle upload (keep secure)
* **Public Key**: Stored in app configuration for decryption on device (safe to commit)
### Key Rotation
[Section titled âKey Rotationâ](#key-rotation)
Regularly rotate your encryption keys for enhanced security:
1. **Generate new keys:**
```shell
# Navigate to desired directory first, then create keys
mkdir ./new-keys && cd ./new-keys
npx @capgo/cli@latest key create
```
2. **Save the new public key to Capacitor config:**
```shell
npx @capgo/cli@latest key save --key ./new-keys/.capgo_key_v2.pub
```
3. **Update your app configuration** with the new public key
4. **Deploy the updated app** before uploading encrypted bundles with the new key
## Security Best Practices
[Section titled âSecurity Best Practicesâ](#security-best-practices)
### Key Security
[Section titled âKey Securityâ](#key-security)
* **Never share private keys** between environments or team members
* **Use different keys** for different environments (dev, staging, production)
* **Rotate keys regularly** (recommended: every 6-12 months)
* **Store keys securely** using proper key management systems
### Bundle Security
[Section titled âBundle Securityâ](#bundle-security)
* **Always verify** bundle integrity after decryption
* **Monitor** for unusual download patterns or failures
* **Use HTTPS** for all bundle URLs (required for mobile apps)
* **Implement** proper error handling for decryption failures
### Access Control
[Section titled âAccess Controlâ](#access-control)
* **Limit access** to encryption keys to authorized personnel only
* **Use role-based access** for key management operations
* **Audit** key usage and access regularly
* **Implement** proper backup and recovery procedures
## Troubleshooting Encryption
[Section titled âTroubleshooting Encryptionâ](#troubleshooting-encryption)
### Common Issues
[Section titled âCommon Issuesâ](#common-issues)
**Decryption failures:**
* Verify the private key matches the public key used for encryption
* Check that the `ivSessionKey` is correct
* Ensure youâre using Encryption V2 (V1 is no longer supported)
**Key-related errors:**
* Confirm the private key format is correct (PEM format)
* Verify the key hasnât been corrupted during storage/transfer
* Check that the key has proper permissions in your app configuration
**Performance issues:**
* Large bundles may take longer to encrypt/decrypt
* Consider using Delta (manifest) updates to reduce bundle sizes
* Monitor device performance during decryption
### Debug Commands
[Section titled âDebug Commandsâ](#debug-commands)
Check encryption status:
```shell
npx @capgo/cli@latest app debug
```
Test encryption/decryption workflow:
```shell
# Test the complete workflow: zip â encrypt â decrypt â unzip
npx @capgo/cli@latest bundle zip com.example.app --key-v2
npx @capgo/cli@latest bundle encrypt ./com.example.app.zip CHECKSUM --json
npx @capgo/cli@latest bundle decrypt ./encrypted-bundle.zip IV_SESSION_KEY
```
## Compliance and Standards
[Section titled âCompliance and Standardsâ](#compliance-and-standards)
Capgoâs encryption implementation follows industry standards:
* **AES-256**: FIPS 140-2 approved encryption algorithm
* **RSA-4096**: Strong asymmetric encryption for key protection
* **GCM Mode**: Provides both confidentiality and authenticity
* **Secure Random**: Cryptographically secure random number generation
This makes Capgo suitable for applications requiring compliance with:
* GDPR (General Data Protection Regulation)
* HIPAA (Health Insurance Portability and Accountability Act)
* SOC 2 (Service Organization Control 2)
* ISO 27001 (Information Security Management)
## Performance Considerations
[Section titled âPerformance Considerationsâ](#performance-considerations)
### Encryption Overhead
[Section titled âEncryption Overheadâ](#encryption-overhead)
* **Bundle size**: Encrypted bundles are slightly larger (\~1-2% overhead)
* **Processing time**: Encryption/decryption adds minimal latency
* **Memory usage**: Temporary increase during encryption/decryption operations
### Optimization Tips
[Section titled âOptimization Tipsâ](#optimization-tips)
* Use Delta (manifest) updates to minimize encrypted data transfer
* Optimize your bundle size by converting images to WebP format
* Minimize JavaScript and CSS files before bundling
* Remove unused dependencies and code
* Monitor device performance on older/slower devices
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Custom Storage](/docs/live-updates/custom-storage/) to use encryption with your own infrastructure
* Explore [Channels](/docs/live-updates/channels/) to manage encrypted bundles across environments
* Set up [CI/CD Integration](/docs/getting-started/cicd-integration/) to automate encrypted deployments
# Features
> Complete reference of all Capgo Live Update capabilities, from core update system to advanced deployment controls, analytics, and team collaboration features.
This page provides a comprehensive overview of all features available in Capgo Live Updates. Each feature includes a brief description and links to detailed documentation.
## Core Update System
[Section titled âCore Update Systemâ](#core-update-system)
### Over-the-Air (OTA) Updates
[Section titled âOver-the-Air (OTA) Updatesâ](#over-the-air-ota-updates)
Deploy JavaScript, HTML, CSS, and asset updates directly to users without app store approval. Updates are downloaded in the background and applied on next app restart.
**Key capabilities:**
* Background downloads
* Automatic installation
* No user interruption
* Cross-platform support (iOS, Android, Electron)
[Learn more about update behavior â](/docs/live-updates/update-behavior/)
***
### Delta Updates (Differential Updates)
[Section titled âDelta Updates (Differential Updates)â](#delta-updates-differential-updates)
Only download files that have changed between versions, reducing bandwidth usage by up to 95% and speeding up update delivery.
**Key capabilities:**
* Automatic file-level diffing
* Checksum-based verification
* Manifest comparison
* Intelligent fallback to full updates when needed
[Learn more about delta updates â](/docs/live-updates/differentials/)
***
### Automatic Rollback
[Section titled âAutomatic Rollbackâ](#automatic-rollback)
If an update fails to load or causes crashes, the system automatically reverts to the last known working version.
**Key capabilities:**
* Crash detection
* Timeout detection
* Automatic reversion
* No user intervention required
[Learn more about rollbacks â](/docs/live-updates/rollbacks/)
***
### Checksum Validation & Fallback
[Section titled âChecksum Validation & Fallbackâ](#checksum-validation--fallback)
Verifies bundle integrity via checksums and automatically falls back to the last known working version if corruption is detected.
**Key capabilities:**
* Checksum validation on download
* Corruption detection
* Automatic fallback to last working bundle
* Manual recovery tools available
***
### Breaking Update Detection
[Section titled âBreaking Update Detectionâ](#breaking-update-detection)
Prevents incompatible updates from being applied to devices running older native code versions.
**Key capabilities:**
* Native version compatibility checking
* Plugin dependency validation
* Automatic blocking of incompatible updates
* Clear error messaging
[Learn more about version targeting â](/docs/live-updates/version-targeting/)
***
## Deployment Control
[Section titled âDeployment Controlâ](#deployment-control)
### Channel System
[Section titled âChannel Systemâ](#channel-system)
Organize and manage updates across different environments and user segments with flexible channel configurations.
**Key capabilities:**
* Unlimited custom channels (production, staging, beta, etc.)
* Per-channel bundle assignments
* Channel-specific targeting rules
* Device self-assignment
* Channel override per device
[Learn more about channels â](/docs/live-updates/channels/)
***
### Device Targeting
[Section titled âDevice Targetingâ](#device-targeting)
Target specific devices, versions, or user segments for phased rollouts and controlled deployments.
**Key capabilities:**
* Version-based targeting
* Device-specific overrides
* Platform filtering (iOS, Android, Electron)
* Custom metadata filtering
* Emulator/dev build blocking
***
### Channel Policies
[Section titled âChannel Policiesâ](#channel-policies)
Configure rules and restrictions for how updates are delivered on each channel.
**Key capabilities:**
* Disable auto-updates
* Block major version updates
* Disable updates on emulators
* Disable updates in development builds
* Platform-specific policies (iOS-only, Android-only, Electron-only)
[Learn more about channel policies â](/docs/live-updates/channels/#channel-policies)
***
## Developer Tools
[Section titled âDeveloper Toolsâ](#developer-tools)
### Bundle Preview
[Section titled âBundle Previewâ](#bundle-preview)
Preview bundles in a live web environment before deploying to devices, accessible from the web dashboard.
**Location:** Web Dashboard â App â Bundle â Preview tab
***
### Live Debugging
[Section titled âLive Debuggingâ](#live-debugging)
Real-time monitoring of update events for specific devices via CLI, showing check, download, install, and error events.
**Usage:**
```bash
npx @capgo/cli app debug [appId]
```
**Shows:**
* Update checks
* Download progress
* Installation status
* Error messages
* Policy blocks
***
### Bundle Manifest Viewer
[Section titled âBundle Manifest Viewerâ](#bundle-manifest-viewer)
Inspect the complete manifest of any bundle including file list, checksums, and metadata.
**Location:** Web Dashboard â App â Bundle â Manifest tab
**Shows:**
* File list with checksums
* Bundle metadata
* Native version compatibility
* Plugin dependencies
***
### Native Plugin Dependencies
[Section titled âNative Plugin Dependenciesâ](#native-plugin-dependencies)
View all native Capacitor plugins included in each bundle to track dependency changes across versions.
**Location:** Web Dashboard â App â Bundle â Dependencies tab
**Shows:**
* Plugin names and versions
* Dependency additions/removals
* Compatibility warnings
***
### CLI Integration
[Section titled âCLI Integrationâ](#cli-integration)
Comprehensive command-line interface for automated deployments and CI/CD integration.
**Key commands:**
* `bundle upload` - Upload new bundles
* `bundle list` - List all bundles
* `bundle delete` - Delete bundles
* `bundle cleanup` - Clean up old bundles
* `channel set` - Configure channels
* `app debug` - Live debugging
[View full CLI reference â](/docs/cli/commands/)
***
### Bundle Encryption
[Section titled âBundle Encryptionâ](#bundle-encryption)
End-to-end encryption for bundles with AES-256 encryption, protecting your code in transit and at rest.
**Key capabilities:**
* RSA key pair generation
* AES-256 bundle encryption
* Code signature verification
* Encryption key management
[Learn more about encryption â](/docs/live-updates/encryption/)
***
### Bundle Cleanup & Retention
[Section titled âBundle Cleanup & Retentionâ](#bundle-cleanup--retention)
Automatically clean up old bundles based on retention policies to manage storage usage.
**Key capabilities:**
* Configurable retention count
* Automatic cleanup via CLI
* Scheduled cleanup jobs
* Storage usage tracking
**Usage:**
```bash
npx @capgo/cli bundle cleanup --keep=10
```
***
## Analytics & Monitoring
[Section titled âAnalytics & Monitoringâ](#analytics--monitoring)
### Update Statistics
[Section titled âUpdate Statisticsâ](#update-statistics)
Track update adoption rates, success rates, and deployment progress across your user base.
**Metrics available:**
* Download success rate
* Installation success rate
* Error rates by type
* Update adoption over time
* Version distribution
**Location:** Web Dashboard â App â Statistics
***
### Device Logs
[Section titled âDevice Logsâ](#device-logs)
Per-device event logs showing complete update lifecycle from check to installation.
**Event types:**
* Update checks
* Download start/complete/fail
* Install start/complete/fail
* Rollback events
* Policy blocks
**Location:**
* Web Dashboard â App â Device â Logs
* Web Dashboard â App â Logs (all devices)
[Learn more about logs â](/docs/webapp/logs/)
***
### Bundle Usage Analytics
[Section titled âBundle Usage Analyticsâ](#bundle-usage-analytics)
Detailed analytics on which bundles are active, download counts, and storage usage.
**Metrics:**
* Active installations per bundle
* Download counts
* Storage usage per bundle
* Bandwidth usage
***
### Channel Statistics
[Section titled âChannel Statisticsâ](#channel-statistics)
Track performance and adoption metrics per channel.
**Metrics:**
* Devices per channel
* Update success rates per channel
* Deployment history
* Error rates by channel
**Location:** Web Dashboard â App â Channel â Statistics
***
### Deployment History
[Section titled âDeployment Historyâ](#deployment-history)
Complete audit trail of all bundle deployments, channel assignments, and configuration changes.
**Tracked events:**
* Bundle uploads
* Channel assignments
* Policy changes
* Device overrides
**Location:** Web Dashboard â App â Channel â History
***
## Security & Compliance
[Section titled âSecurity & Complianceâ](#security--compliance)
### End-to-End Encryption
[Section titled âEnd-to-End Encryptionâ](#end-to-end-encryption)
Encrypt bundles at rest and in transit with industry-standard AES-256 encryption.
[Learn more about encryption â](/docs/live-updates/encryption/)
***
### Code Signing
[Section titled âCode Signingâ](#code-signing)
Verify bundle integrity with cryptographic signatures to prevent tampering.
***
### SOC 2 Type II Compliance
[Section titled âSOC 2 Type II Complianceâ](#soc-2-type-ii-compliance)
Infrastructure and processes certified to SOC 2 Type II standards for enterprise security.
***
### App Store Compliance
[Section titled âApp Store Complianceâ](#app-store-compliance)
Fully compliant with Apple App Store and Google Play Store policies for OTA updates.
[Learn more about compliance â](/docs/live-updates/compliance/)
***
### 2FA Enforcement (Organization-level)
[Section titled â2FA Enforcement (Organization-level)â](#2fa-enforcement-organization-level)
Require two-factor authentication for all organization members to access the dashboard and API.
**Location:** Web Dashboard â Organization â Security
[Learn more about 2FA â](/docs/webapp/2fa-enforcement/)
***
### Encrypted Bundles Enforcement
[Section titled âEncrypted Bundles Enforcementâ](#encrypted-bundles-enforcement)
Require all bundles to be encrypted at the organization level.
**Location:** Web Dashboard â Organization â Security
***
## Team Collaboration
[Section titled âTeam Collaborationâ](#team-collaboration)
### Role-Based Access Control (RBAC)
[Section titled âRole-Based Access Control (RBAC)â](#role-based-access-control-rbac)
Granular permissions for organization and app-level access control.
**Organization roles:**
* `org_super_admin` - Full organization control
* `org_admin` - Organization administration (no billing/deletion)
* `org_billing_admin` - Billing-only access
* `org_member` - Read-only organization access
**App roles:**
* `app_admin` - Full control of one app
* `app_developer` - Upload bundles, manage devices
* `app_uploader` - Upload bundles only
* `app_reader` - Read-only access
**Location:**
* Web Dashboard â Organization â Members
* Web Dashboard â App â Access
[Learn more about RBAC â](/docs/webapp/organization-system/#roles-overview)
***
### Audit Logs
[Section titled âAudit Logsâ](#audit-logs)
Complete audit trail of all organization and app activities for compliance and security.
**Logged events:**
* User actions (login, logout, permission changes)
* Bundle operations (upload, delete, assign)
* Channel operations (create, update, delete)
* Organization changes (settings, members)
**Location:** Web Dashboard â Organization â Audit Logs
***
### Webhooks
[Section titled âWebhooksâ](#webhooks)
Receive real-time notifications about events in your apps via HTTP webhooks.
**Supported events:**
* `apps` - App created/updated/deleted
* `app_versions` - Bundle uploaded/deleted
* `channels` - Channel created/updated/deleted
* `org_users` - Member added/removed
* `orgs` - Organization updated
**Features:**
* Custom webhook URLs
* Event filtering
* Delivery logs
* Retry mechanism
* Test functionality
**Location:** Web Dashboard â Organization â Webhooks
***
### Multi-User Collaboration
[Section titled âMulti-User Collaborationâ](#multi-user-collaboration)
Invite team members to your organization with specific roles and permissions.
**Features:**
* Email invitations
* Role assignment
* Member management
* Access revocation
**Location:** Web Dashboard â Organization â Members
***
### API Key Management
[Section titled âAPI Key Managementâ](#api-key-management)
Create, manage, and revoke API keys with optional expiration dates and hashed storage.
**Key capabilities:**
* Per-app or per-organization keys
* Optional expiration dates
* Hashed storage (irreversible)
* Key rotation support
**Location:** Web Dashboard â API Keys
[Learn more about API keys â](/docs/public-api/#authentication)
***
### Password Policies
[Section titled âPassword Policiesâ](#password-policies)
Organization-level password requirements to enforce security standards.
**Configurable policies:**
* Minimum length
* Require uppercase
* Require numbers
* Require special characters
**Location:** Web Dashboard â Organization â Security
***
## Platform Support
[Section titled âPlatform Supportâ](#platform-support)
### Multi-Platform Support
[Section titled âMulti-Platform Supportâ](#multi-platform-support)
Support for iOS, Android, and Electron apps with a single SDK.
**Supported platforms:**
* iOS (Capacitor 5, 6, 7, 8)
* Android (Capacitor 5, 6, 7, 8)
* Electron (NEW in 2025)
***
### Long-Term Support
[Section titled âLong-Term Supportâ](#long-term-support)
Continued support for older Capacitor versions to maintain compatibility with legacy apps.
**Currently supported:**
* Capacitor 8 (latest)
* Capacitor 7
* Capacitor 6
* Capacitor 5
***
### Custom Storage Backends
[Section titled âCustom Storage Backendsâ](#custom-storage-backends)
Use your own storage infrastructure (S3, R2, etc.) instead of Capgoâs default storage.
[Learn more about custom storage â](/docs/live-updates/custom-storage/)
***
### China Configuration
[Section titled âChina Configurationâ](#china-configuration)
Special configuration for apps distributed in mainland China to comply with local regulations.
[Learn more about China configuration â](/docs/live-updates/china-configuration/)
***
## Advanced Features
[Section titled âAdvanced Featuresâ](#advanced-features)
### Custom Update Behavior
[Section titled âCustom Update Behaviorâ](#custom-update-behavior)
Configure when and how updates are checked and applied via the SDK.
**Configurable options:**
* Check interval (`periodCheckDelay` - minimum 600 seconds)
* Direct update timing (`directUpdate` - atInstall, onLaunch, always)
* Auto-update enable/disable (`autoUpdate`)
* Network requirements (Android only - via WorkManager)
[Learn more about update behavior â](/docs/live-updates/update-behavior/)
***
### Update Types
[Section titled âUpdate Typesâ](#update-types)
Different update types for different use cases, from instant updates to user-controlled installations.
**Available types:**
* Background updates (default)
* Immediate updates
* User-prompted updates
* Conditional updates
[Learn more about update types â](/docs/live-updates/update-types/)
***
### Credit System
[Section titled âCredit Systemâ](#credit-system)
Usage-based billing with credits for bandwidth, storage, and other resources.
**Features:**
* Credit usage tracking
* Usage alerts
* Top-up via Stripe
* Credit ledger
**Location:** Web Dashboard â Organization â Credits
***
## Getting Started
[Section titled âGetting Startedâ](#getting-started)
Ready to start using these features? Follow our [Quickstart Guide](/docs/getting-started/quickstart/) to set up your first app with Capgo Live Updates.
## Need Help?
[Section titled âNeed Help?â](#need-help)
* [Join our Discord](https://discord.capgo.app) for community support
* [Check the FAQ](/docs/faq/) for common questions
* [Browse API documentation](/docs/public-api/) for API integration
* [Contact support](https://capgo.app/consulting/) for enterprise assistance
# CI/CD Integrations
> Integrate Capgo Live Updates with your favorite CI/CD platform for automated deployment workflows.
Automate your Capgo Live Updates deployment process by integrating with popular CI/CD platforms. These integrations allow you to automatically deploy app updates whenever you push code changes, test feature branches, and manage multiple deployment environments.
## Available Integrations
[Section titled âAvailable Integrationsâ](#available-integrations)
Choose your CI/CD platform to get started with automated deployments:
[Azure DevOps ](/docs/live-updates/integrations/azure-devops/)Integrate with Azure DevOps Pipelines for automated builds, testing, and deployment workflows.
[GitLab CI/CD ](/docs/live-updates/integrations/gitlab-ci/)Set up GitLab CI/CD pipelines to automatically deploy your app updates with comprehensive environment management.
[GitHub Actions ](/docs/live-updates/integrations/github-actions/)Use GitHub Actions for powerful automation with multi-channel deployments and environment protection.
[Bitbucket Pipelines ](/docs/live-updates/integrations/bitbucket-pipeline/)Deploy with Bitbucket Pipelines using simple or advanced configurations for multiple environments.
## What Youâll Get
[Section titled âWhat Youâll Getâ](#what-youll-get)
All integration guides include:
* **Simple Setup**: Basic configuration to get started quickly
* **Advanced Workflows**: Multi-environment deployments with staging and production
* **Feature Branch Testing**: Automatic deployment of feature branches to test channels
* **Security Best Practices**: Secure secret management and environment protection
* **Monitoring**: Notifications and logging for deployment status
Tip
**New to CI/CD?** Start with the simple configuration for your platform, then gradually add more advanced features like multi-channel deployments and automated testing as your needs grow.
## Common Features
[Section titled âCommon Featuresâ](#common-features)
Each integration supports:
* **Automated Builds**: Trigger deployments on code changes
* **Multi-Channel Support**: Deploy to different channels (development, staging, production)
* **Pull Request/Merge Request Testing**: Test changes in isolated environments
* **Encryption Support**: Secure deployments with Capgoâs encryption feature
* **Environment Protection**: Manual approvals and restricted access for production
* **Notifications**: Slack, email, and other notification integrations
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
Before setting up any integration, ensure you have:
* A Capgo account with an app configured
* Your appâs source code in a Git repository
* A Capgo API token from [console.capgo.app/apikeys](https://console.capgo.app/apikeys)
* Node.js and npm/yarn configured in your project
## Related Documentation
[Section titled âRelated Documentationâ](#related-documentation)
* [Channels](/docs/live-updates/channels/) - Learn how to manage different deployment environments
* [Encryption](/docs/live-updates/encryption/) - Secure your deployments with end-to-end encryption
* [Update Behavior](/docs/live-updates/update-behavior/) - Customize how updates are applied to your apps
Choose your CI/CD platform above to start automating your Capgo deployments!
# Azure DevOps Integration
> Learn how to integrate Capgo Live Updates with Azure DevOps Pipelines for automated deployment of your app updates.
Integrate Capgo Live Updates with Azure DevOps Pipelines to automatically deploy your app updates whenever you push code changes. This guide covers setting up automated builds, testing, and deployment workflows.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
Before setting up Azure DevOps integration, ensure you have:
* An Azure DevOps organization and project
* A Capgo account with an app configured
* Your appâs source code in an Azure Repos Git repository
* Node.js and npm/yarn configured in your project
## Setting Up Azure DevOps Pipeline
[Section titled âSetting Up Azure DevOps Pipelineâ](#setting-up-azure-devops-pipeline)
### Step 1: Create Pipeline Variables
[Section titled âStep 1: Create Pipeline Variablesâ](#step-1-create-pipeline-variables)
First, set up the necessary variables in your Azure DevOps project:
1. Navigate to your Azure DevOps project
2. Go to **Pipelines** â **Library** â **Variable groups**
3. Create a new variable group named `Capgo-Variables`
4. Add the following variables:
| Variable Name | Value | Secure |
| ------------- | -------------------- | ------ |
| `CAPGO_TOKEN` | Your Capgo API token | â Yes |
Tip
Get your Capgo API token from [console.capgo.app/apikeys](https://console.capgo.app/apikeys). Your app ID is already configured in your `capacitor.config.ts` file.
## Simple
[Section titled âSimpleâ](#simple)
Basic configuration that deploys to production on every push to the main branch:
```yaml
# Simple Azure DevOps Pipeline for Capgo Live Updates
trigger:
branches:
include:
- main
variables:
- group: Capgo-Variables
jobs:
- job: BuildAndDeploy
displayName: 'Build and Deploy to Capgo'
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
displayName: 'Setup Node.js'
inputs:
versionSpec: '22.x'
- script: |
npm ci
npm run test
npm run build
displayName: 'Install, test and build'
- script: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --channel production
displayName: 'Deploy to Capgo'
```
## Advanced
[Section titled âAdvancedâ](#advanced)
### Feature Branch Deployments
[Section titled âFeature Branch Deploymentsâ](#feature-branch-deployments)
Deploy feature branches to test channels for review and testing:
```yaml
# Feature branch deployment
trigger:
branches:
include:
- feature/*
variables:
- group: Capgo-Variables
jobs:
- job: DeployFeature
displayName: 'Deploy Feature Branch'
pool:
vmImage: 'ubuntu-latest'
condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/feature/')
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- script: |
npm ci
npm run test
npm run build
displayName: 'Install, test and build'
- script: |
BRANCH_NAME=$(echo "$(Build.SourceBranchName)" | sed 's/[^a-zA-Z0-9-]/-/g')
CHANNEL_NAME="feature-$BRANCH_NAME"
npm install -g @capgo/cli
npx @capgo/cli channel create $CHANNEL_NAME --apikey $(CAPGO_TOKEN) || true
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --channel $CHANNEL_NAME
displayName: 'Deploy to Feature Channel'
```
Tip
**Testing with Channels**: After deploying to a feature channel, you can test the update in your app by configuring it to use that specific channel. Learn more about [configuring channels in your app](/docs/live-updates/channels/#configuring-the-channel-in-your-app).
### Using Encryption
[Section titled âUsing Encryptionâ](#using-encryption)
If youâre using [Capgoâs encryption feature](/docs/live-updates/encryption/), youâll need to store your private key securely in your CI/CD environment.
After [setting up encryption keys](/docs/live-updates/encryption/#setting-up-encryption) locally, add your private key to Azure DevOps variables:
```shell
# Display your private key content (copy this output)
cat .capgo_key_v2
```
Add this content as `CAPGO_PRIVATE_KEY` in your Azure DevOps variable group (mark as secret), then use it in pipelines:
```yaml
# Deploy with encryption
- script: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --key-data-v2 "$(CAPGO_PRIVATE_KEY)" --channel production
displayName: 'Deploy to Capgo with Encryption'
```
Caution
**Security Best Practices:**
* Never commit the `.capgo_key_v2` file to version control
* Store the private key only in secure CI/CD secret management
* Use different keys for different environments
### Multi-Channel Configuration
[Section titled âMulti-Channel Configurationâ](#multi-channel-configuration)
For comprehensive information about setting up and managing multiple deployment channels, see the [Channels documentation](/docs/live-updates/channels/).
Complete configuration with multiple environments and pull request deployments:
```yaml
# Advanced Azure DevOps Pipeline with Multiple Channels
trigger:
branches:
include:
- main
- develop
pr:
branches:
include:
- main
- develop
variables:
- group: Capgo-Variables
stages:
# Build stage
- stage: Build
jobs:
- job: BuildApp
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- script: |
npm ci
npm run test
npm run build
displayName: 'Install, test and build'
- task: PublishBuildArtifacts@1
inputs:
pathToPublish: 'dist'
artifactName: 'app-build'
# Deploy to development
- stage: DeployDev
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))
jobs:
- deployment: DeployDevelopment
environment: development
pool:
vmImage: 'ubuntu-latest'
strategy:
runOnce:
deploy:
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- task: DownloadBuildArtifacts@0
inputs:
artifactName: 'app-build'
downloadPath: '$(Pipeline.Workspace)'
- script: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --channel development --path $(Pipeline.Workspace)/app-build
displayName: 'Deploy to Development'
# Deploy PR to test channel
- stage: DeployPR
condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
jobs:
- job: DeployPRChannel
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- task: DownloadBuildArtifacts@0
inputs:
artifactName: 'app-build'
downloadPath: '$(Pipeline.Workspace)'
- script: |
CHANNEL_NAME="pr-$(System.PullRequest.PullRequestNumber)"
npm install -g @capgo/cli
npx @capgo/cli channel create $CHANNEL_NAME --apikey $(CAPGO_TOKEN) || true
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --channel $CHANNEL_NAME --path $(Pipeline.Workspace)/app-build
displayName: 'Deploy to PR Channel'
# Deploy to production
- stage: DeployProd
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
jobs:
- deployment: DeployProduction
environment: production
pool:
vmImage: 'ubuntu-latest'
strategy:
runOnce:
deploy:
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- task: DownloadBuildArtifacts@0
inputs:
artifactName: 'app-build'
downloadPath: '$(Pipeline.Workspace)'
- script: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey $(CAPGO_TOKEN) --channel production --path $(Pipeline.Workspace)/app-build
displayName: 'Deploy to Production'
```
### Multi-Environment Deployment
[Section titled âMulti-Environment Deploymentâ](#multi-environment-deployment)
For complex scenarios with multiple environments:
```yaml
# Extended pipeline with multiple environments
parameters:
- name: deployEnvironment
displayName: 'Deploy Environment'
type: string
default: 'staging'
values:
- staging
- production
variables:
- group: Capgo-Variables
- name: channelName
${{ if eq(parameters.deployEnvironment, 'production') }}:
value: 'production'
${{ else }}:
value: 'staging'
stages:
# Build stage
- stage: Build
jobs:
- job: BuildApp
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- script: |
npm ci
npm run test
npm run build
displayName: 'Install, test and build'
- task: PublishBuildArtifacts@1
inputs:
pathToPublish: 'dist'
artifactName: 'app-build'
- stage: DeployStaging
displayName: 'Deploy to Staging'
dependsOn: Build
condition: and(succeeded(), eq('${{ parameters.deployEnvironment }}', 'staging'))
jobs:
- deployment: DeployStaging
displayName: 'Deploy to Staging Channel'
pool:
vmImage: 'ubuntu-latest'
environment: 'staging'
strategy:
runOnce:
deploy:
steps:
- template: deploy-steps.yml
parameters:
channel: 'staging'
- stage: DeployProduction
displayName: 'Deploy to Production'
dependsOn: Build
condition: and(succeeded(), eq('${{ parameters.deployEnvironment }}', 'production'))
jobs:
- deployment: DeployProduction
displayName: 'Deploy to Production Channel'
pool:
vmImage: 'ubuntu-latest'
environment: 'production'
strategy:
runOnce:
deploy:
steps:
- template: deploy-steps.yml
parameters:
channel: 'production'
```
### Deployment Template (deploy-steps.yml)
[Section titled âDeployment Template (deploy-steps.yml)â](#deployment-template-deploy-stepsyml)
Create a reusable template file `deploy-steps.yml`:
deploy-steps.yml
```yaml
parameters:
- name: channel
type: string
steps:
- task: NodeTool@0
displayName: 'Install Node.js'
inputs:
versionSpec: '22.x'
- task: DownloadBuildArtifacts@0
displayName: 'Download build artifacts'
inputs:
artifactName: 'app-build'
downloadPath: '$(System.ArtifactsDirectory)'
- script: |
npm install -g @capgo/cli
displayName: 'Install Capgo CLI'
- script: |
npx @capgo/cli bundle upload \
--apikey $(CAPGO_TOKEN) \
--channel ${{ parameters.channel }} \
--path $(System.ArtifactsDirectory)/app-build
displayName: 'Upload to Capgo (${{ parameters.channel }})'
```
### Branch-Based Deployment Strategy
[Section titled âBranch-Based Deployment Strategyâ](#branch-based-deployment-strategy)
Configure different deployment strategies based on Git branches:
```yaml
trigger:
branches:
include:
- main
- develop
- feature/*
variables:
- group: Capgo-Variables
- name: targetChannel
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
value: 'production'
${{ elseif eq(variables['Build.SourceBranch'], 'refs/heads/develop') }}:
value: 'staging'
${{ else }}:
value: 'development'
stages:
- stage: Build
jobs:
- job: BuildApp
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
inputs:
versionSpec: '22.x'
- script: |
npm ci
npm run test
npm run build
displayName: 'Install, test and build'
- task: PublishBuildArtifacts@1
inputs:
pathToPublish: 'dist'
artifactName: 'app-build'
- stage: Deploy
displayName: 'Deploy to $(targetChannel)'
dependsOn: Build
condition: succeeded()
jobs:
- deployment: DeployJob
displayName: 'Deploy to $(targetChannel) Channel'
pool:
vmImage: 'ubuntu-latest'
environment: '$(targetChannel)'
strategy:
runOnce:
deploy:
steps:
- template: deploy-steps.yml
parameters:
channel: '$(targetChannel)'
```
## Security Best Practices
[Section titled âSecurity Best Practicesâ](#security-best-practices)
### Secure Variable Management
[Section titled âSecure Variable Managementâ](#secure-variable-management)
1. **Use Variable Groups**: Store sensitive data in Azure DevOps variable groups
2. **Mark as Secret**: Always mark API tokens and keys as secret variables
3. **Scope Access**: Limit variable group access to specific pipelines and users
4. **Rotate Keys**: Regularly rotate your Capgo API tokens
## Monitoring and Notifications
[Section titled âMonitoring and Notificationsâ](#monitoring-and-notifications)
### Teams Integration
[Section titled âTeams Integrationâ](#teams-integration)
Add Microsoft Teams notifications to your pipeline:
```yaml
- task: ms-teams-deploy-card@1.4.1
displayName: 'Notify Teams on Success'
condition: succeeded()
inputs:
webhookUri: '$(TEAMS_WEBHOOK_URL)'
title: 'Capgo Deployment Successful'
text: 'App deployed to $(targetChannel) channel'
themeColor: '00FF00'
- task: ms-teams-deploy-card@1.4.1
displayName: 'Notify Teams on Failure'
condition: failed()
inputs:
webhookUri: '$(TEAMS_WEBHOOK_URL)'
title: 'Capgo Deployment Failed'
text: 'Deployment to $(targetChannel) failed'
themeColor: 'FF0000'
```
### Email Notifications
[Section titled âEmail Notificationsâ](#email-notifications)
Configure email notifications for deployment status:
```yaml
- task: EmailReport@1
displayName: 'Send Email Report'
condition: always()
inputs:
sendMailConditionConfig: 'Always'
subject: 'Capgo Deployment Report - $(Build.BuildNumber)'
to: 'team@yourcompany.com'
body: |
Deployment Status: $(Agent.JobStatus)
Channel: $(targetChannel)
Build: $(Build.BuildNumber)
Commit: $(Build.SourceVersion)
```
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Common Issues
[Section titled âCommon Issuesâ](#common-issues)
**Pipeline fails with âCapgo CLI not foundâ:**
```yaml
# Ensure global installation
- script: |
npm install -g @capgo/cli
which capgo || echo "Capgo CLI not found in PATH"
displayName: 'Install and verify Capgo CLI'
```
**Authentication errors:**
```yaml
# Verify token is correctly set
- script: |
echo "Token length: ${#CAPGO_TOKEN}"
if [ -z "$CAPGO_TOKEN" ]; then
echo "CAPGO_TOKEN is not set"
exit 1
fi
displayName: 'Verify Capgo token'
env:
CAPGO_TOKEN: $(CAPGO_TOKEN)
```
**Build artifacts not found:**
```yaml
# List available artifacts for debugging
- script: |
ls -la $(System.ArtifactsDirectory)
find $(System.ArtifactsDirectory) -name "*.js" -o -name "*.html"
displayName: 'Debug artifacts'
```
### Debug Pipeline
[Section titled âDebug Pipelineâ](#debug-pipeline)
Add debugging steps to troubleshoot issues:
```yaml
- script: |
echo "Build.SourceBranch: $(Build.SourceBranch)"
echo "Build.BuildNumber: $(Build.BuildNumber)"
echo "Target Channel: $(targetChannel)"
displayName: 'Debug Pipeline Variables'
- script: |
npx @capgo/cli app debug --apikey $(CAPGO_TOKEN)
displayName: 'Debug Capgo App Status'
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Channels](/docs/live-updates/channels/) to manage different deployment environments
* Explore [Custom Storage](/docs/live-updates/custom-storage/) for advanced deployment scenarios
* Set up [Encryption](/docs/live-updates/encryption/) for secure deployments
* Configure [Update Behavior](/docs/live-updates/update-behavior/) to customize how updates are applied
With Azure DevOps integration, you can automate your Capgo deployments and ensure consistent, reliable updates to your mobile app users.
# Bitbucket Pipelines Integration
> Learn how to integrate Capgo Live Updates with Bitbucket Pipelines for automated deployment of your app updates.
Integrate Capgo Live Updates with Bitbucket Pipelines to automatically deploy your app updates whenever you push code changes. This guide covers setting up automated builds, testing, and deployment workflows.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
Before setting up Bitbucket Pipelines integration, ensure you have:
* A Bitbucket account with a repository
* A Capgo account with an app configured
* Node.js and npm/yarn configured in your project
## Setting Up Bitbucket Pipelines
[Section titled âSetting Up Bitbucket Pipelinesâ](#setting-up-bitbucket-pipelines)
### Step 1: Configure Repository Variables
[Section titled âStep 1: Configure Repository Variablesâ](#step-1-configure-repository-variables)
First, set up the necessary variables in your Bitbucket repository:
1. Navigate to your Bitbucket repository
2. Go to **Repository settings** â **Pipelines** â **Repository variables**
3. Add the following variables:
| Variable Name | Value | Secured |
| ------------- | -------------------- | ------- |
| `CAPGO_TOKEN` | Your Capgo API token | â Yes |
Tip
Get your Capgo API token from [console.capgo.app/apikeys](https://console.capgo.app/apikeys). Your app ID is already configured in your `capacitor.config.ts` file.
## Simple
[Section titled âSimpleâ](#simple)
Basic configuration that deploys to production on every push to the main branch:
```yaml
# bitbucket-pipelines.yml - Simple Configuration
image: node:22
pipelines:
branches:
main:
- step:
name: Build and Deploy to Production
script:
- npm ci
- npm run test
- npm run build
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
artifacts:
- dist/**
```
## Advanced
[Section titled âAdvancedâ](#advanced)
### Feature Branch Deployments
[Section titled âFeature Branch Deploymentsâ](#feature-branch-deployments)
Deploy feature branches to test channels for review and testing:
```yaml
# Feature branch deployment
pipelines:
branches:
feature/*:
- step:
name: Deploy Feature Branch
script:
- npm ci
- npm run test
- npm run build
- BRANCH_NAME=$(echo $BITBUCKET_BRANCH | sed 's/[^a-zA-Z0-9-]/-/g')
- CHANNEL_NAME="feature-$BRANCH_NAME"
- npm install -g @capgo/cli
- npx @capgo/cli channel create $CHANNEL_NAME --apikey $CAPGO_TOKEN || true
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
artifacts:
- dist/**
```
Tip
**Testing with Channels**: After deploying to a feature channel, you can test the update in your app by configuring it to use that specific channel. Learn more about [configuring channels in your app](/docs/live-updates/channels/#configuring-the-channel-in-your-app).
### Using Encryption
[Section titled âUsing Encryptionâ](#using-encryption)
If youâre using [Capgoâs encryption feature](/docs/live-updates/encryption/), youâll need to store your private key securely in your CI/CD environment.
After [setting up encryption keys](/docs/live-updates/encryption/#setting-up-encryption) locally, add your private key to Bitbucket variables:
```shell
# Display your private key content (copy this output)
cat .capgo_key_v2
```
Add this content as `CAPGO_PRIVATE_KEY` in your Bitbucket repository variables (mark as secured), then use it in pipelines:
```yaml
# Deploy with encryption
- step:
name: Deploy to Capgo with Encryption
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --key-data-v2 "$CAPGO_PRIVATE_KEY" --channel production
```
Caution
**Security Best Practices:**
* Never commit the `.capgo_key_v2` file to version control
* Store the private key only in secure CI/CD secret management
* Use different keys for different environments
### Multi-Channel Configuration
[Section titled âMulti-Channel Configurationâ](#multi-channel-configuration)
For comprehensive information about setting up and managing multiple deployment channels, see the [Channels documentation](/docs/live-updates/channels/).
Complete configuration with multiple environments and pull request deployments:
```yaml
# bitbucket-pipelines.yml - Advanced Multi-Channel Configuration
image: node:22
definitions:
steps:
- step: &build-step
name: Build Application
script:
- npm ci
- npm run test
- npm run build
artifacts:
- dist/**
- step: &deploy-step
name: Deploy to Capgo
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
pipelines:
branches:
main:
- step:
<<: *build-step
- step:
<<: *deploy-step
name: Deploy to Production
deployment: production
trigger: manual
script:
- export CHANNEL_NAME=production
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
develop:
- step:
<<: *build-step
- step:
<<: *deploy-step
name: Deploy to Development
deployment: development
script:
- export CHANNEL_NAME=development
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
pull-requests:
'**':
- step:
<<: *build-step
- step:
name: Deploy PR to Test Channel
script:
- CHANNEL_NAME="pr-$BITBUCKET_PR_ID"
- npm install -g @capgo/cli
- npx @capgo/cli channel create $CHANNEL_NAME --apikey $CAPGO_TOKEN || true
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
artifacts:
- dist/**
```
### Multi-Environment Pipeline
[Section titled âMulti-Environment Pipelineâ](#multi-environment-pipeline)
For complex deployment scenarios with staging and production environments:
```yaml
# Multi-environment pipeline
image: node:22
pipelines:
branches:
main:
- step:
name: Build
script:
- npm ci
- npm run test
- npm run build
artifacts:
- dist/**
- step:
name: Deploy to Staging
deployment: staging
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel staging
- step:
name: Deploy to Production
deployment: production
trigger: manual
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
develop:
- step:
name: Build and Deploy to Development
script:
- npm ci
- npm run test
- npm run build
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel development
artifacts:
- dist/**
```
### Branch-Based Deployment Strategy
[Section titled âBranch-Based Deployment Strategyâ](#branch-based-deployment-strategy)
Automatically deploy different branches to appropriate channels:
```yaml
# Dynamic channel deployment
image: node:22
definitions:
scripts:
- script: &determine-channel |
if [ "$BITBUCKET_BRANCH" = "main" ]; then
export CHANNEL_NAME="production"
elif [ "$BITBUCKET_BRANCH" = "develop" ]; then
export CHANNEL_NAME="staging"
else
export CHANNEL_NAME="development"
fi
echo "Deploying to channel: $CHANNEL_NAME"
pipelines:
default:
- step:
name: Build and Deploy
script:
- npm ci
- npm run test
- npm run build
- *determine-channel
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
artifacts:
- dist/**
```
### Parallel Pipeline Execution
[Section titled âParallel Pipeline Executionâ](#parallel-pipeline-execution)
Optimize build times with parallel steps:
```yaml
# Parallel execution pipeline
image: node:22
pipelines:
branches:
main:
- parallel:
- step:
name: Run Tests
script:
- npm ci
- npm run test
- step:
name: Lint Code
script:
- npm ci
- npm run lint
- step:
name: Build Application
script:
- npm ci
- npm run build
artifacts:
- dist/**
- step:
name: Deploy to Production
deployment: production
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
```
## Security Best Practices
[Section titled âSecurity Best Practicesâ](#security-best-practices)
### Repository Variables
[Section titled âRepository Variablesâ](#repository-variables)
1. **Secured Variables**: Always mark API tokens as secured
2. **Environment Variables**: Use deployment-specific variables when needed
3. **Access Control**: Limit repository access to authorized team members
4. **Token Rotation**: Regularly rotate your Capgo API tokens
### Deployment Environments
[Section titled âDeployment Environmentsâ](#deployment-environments)
Configure deployment environments for better security:
```yaml
# Deployment with environment restrictions
pipelines:
branches:
main:
- step:
name: Deploy to Production
deployment: production
trigger: manual
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
```
## Monitoring and Notifications
[Section titled âMonitoring and Notificationsâ](#monitoring-and-notifications)
### Slack Integration
[Section titled âSlack Integrationâ](#slack-integration)
Add Slack notifications to your pipeline:
```yaml
# Pipeline with Slack notifications
pipelines:
branches:
main:
- step:
name: Build and Deploy
script:
- npm ci
- npm run test
- npm run build
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
after-script:
- |
if [ $BITBUCKET_EXIT_CODE -eq 0 ]; then
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"â Capgo deployment successful for '$BITBUCKET_BRANCH'"}' \
$SLACK_WEBHOOK_URL
else
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"â Capgo deployment failed for '$BITBUCKET_BRANCH'"}' \
$SLACK_WEBHOOK_URL
fi
```
### Email Notifications
[Section titled âEmail Notificationsâ](#email-notifications)
Configure email notifications through Bitbucketâs built-in features or using external services:
```yaml
# Email notification step
- step:
name: Send Notification
script:
- |
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"to": "team@yourcompany.com",
"subject": "Capgo Deployment Status",
"body": "Deployment of '$BITBUCKET_BRANCH' completed with status: '$BITBUCKET_EXIT_CODE'"
}' \
$EMAIL_SERVICE_URL
condition:
result: [successful, failed]
```
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Common Issues
[Section titled âCommon Issuesâ](#common-issues)
**Pipeline fails with âCapgo CLI not foundâ:**
```yaml
# Debug CLI installation
- step:
name: Debug CLI
script:
- npm install -g @capgo/cli
- which capgo || echo "Capgo CLI not found"
- npx @capgo/cli --version
```
**Authentication errors:**
```yaml
# Verify token configuration
- step:
name: Debug Auth
script:
- |
if [ -z "$CAPGO_TOKEN" ]; then
echo "CAPGO_TOKEN is not set"
exit 1
fi
echo "Token length: ${#CAPGO_TOKEN}"
```
**Build artifacts not found:**
```yaml
# List build outputs
- step:
name: Debug Build
script:
- ls -la dist/
- find dist/ -type f -name "*.js" -o -name "*.html"
```
### Debug Pipeline
[Section titled âDebug Pipelineâ](#debug-pipeline)
Add debugging information to troubleshoot issues:
```yaml
# Debug pipeline
pipelines:
branches:
main:
- step:
name: Debug Information
script:
- echo "Branch: $BITBUCKET_BRANCH"
- echo "Commit: $BITBUCKET_COMMIT"
- echo "Build: $BITBUCKET_BUILD_NUMBER"
- env | grep BITBUCKET_ | sort
- step:
name: Build and Deploy
script:
- npm ci
- npm run test
- npm run build
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
```
### Pipeline Validation
[Section titled âPipeline Validationâ](#pipeline-validation)
Enable pipeline validation to catch configuration errors:
```yaml
# Enable pipeline validation
options:
docker: true
size: 2x
pipelines:
branches:
main:
- step:
name: Validate Pipeline
script:
- echo "Pipeline validation successful"
- step:
name: Build and Deploy
script:
# ... deployment steps
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Channels](/docs/live-updates/channels/) to manage different deployment environments
* Explore [Custom Storage](/docs/live-updates/custom-storage/) for advanced deployment scenarios
* Set up [Encryption](/docs/live-updates/encryption/) for secure deployments
* Configure [Update Behavior](/docs/live-updates/update-behavior/) to customize how updates are applied
With Bitbucket Pipelines integration, you can automate your Capgo deployments and ensure consistent, reliable updates to your mobile app users.
# GitHub Actions Integration
> Learn how to integrate Capgo Live Updates with GitHub Actions for automated deployment of your app updates.
Integrate Capgo Live Updates with GitHub Actions to automatically deploy your app updates whenever you push code changes. This guide covers setting up automated builds, testing, and deployment workflows using GitHubâs powerful CI/CD platform.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
Before setting up GitHub Actions integration, ensure you have:
* A GitHub repository with your appâs source code
* A Capgo account with an app configured
* Node.js and npm/yarn configured in your project
* GitHub Actions enabled for your repository
## Setting Up GitHub Secrets
[Section titled âSetting Up GitHub Secretsâ](#setting-up-github-secrets)
### Step 1: Configure Repository Secrets
[Section titled âStep 1: Configure Repository Secretsâ](#step-1-configure-repository-secrets)
Set up the necessary secrets in your GitHub repository:
1. Navigate to your GitHub repository
2. Go to **Settings** â **Secrets and variables** â **Actions**
3. Click **New repository secret** and add the following:
| Secret Name | Value |
| ------------- | -------------------- |
| `CAPGO_TOKEN` | Your Capgo API token |
Tip
Get your Capgo API token from [console.capgo.app/apikeys](https://console.capgo.app/apikeys). Your app ID is already configured in your `capacitor.config.ts` file.
## Simple Production Deployment
[Section titled âSimple Production Deploymentâ](#simple-production-deployment)
Start with this basic configuration that deploys to production on every push to the main branch:
```yaml
# Simple GitHub Actions Workflow for Capgo Live Updates
name: Deploy to Capgo
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'npm'
- name: Install, test and build
run: |
npm ci
npm run test
npm run build
- name: Deploy to Capgo
run: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --channel production
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
# For encrypted uploads, add: --key-data-v2 "${{ secrets.CAPGO_PRIVATE_KEY }}"
```
## Advanced Multi-Channel Configuration
[Section titled âAdvanced Multi-Channel Configurationâ](#advanced-multi-channel-configuration)
### Feature Branch Deployments
[Section titled âFeature Branch Deploymentsâ](#feature-branch-deployments)
Deploy feature branches to temporary channels for testing:
```yaml
# Feature branch deployment
name: Deploy Feature Branch to Capgo
on:
push:
branches:
- 'feature/**'
jobs:
deploy-feature:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'npm'
- run: |
npm ci
npm run test
npm run build
- name: Deploy to feature channel
run: |
CHANNEL_NAME=$(echo "${{ github.ref_name }}" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]')
npm install -g @capgo/cli
npx @capgo/cli channel create $CHANNEL_NAME --apikey ${{ secrets.CAPGO_TOKEN }} || true
npx @capgo/cli bundle upload --apikey ${{ secrets.CAPGO_TOKEN }} --channel $CHANNEL_NAME
```
### Using Encryption
[Section titled âUsing Encryptionâ](#using-encryption)
If youâre using [Capgoâs encryption feature](/docs/live-updates/encryption/), youâll need to store your private key securely in your CI/CD environment.
After [setting up encryption keys](/docs/live-updates/encryption/#setting-up-encryption) locally, add your private key to GitHub secrets:
```shell
# Display your private key content (copy this output)
cat .capgo_key_v2
```
Add this content as `CAPGO_PRIVATE_KEY` in your GitHub repository secrets, then use it in workflows:
```yaml
# Deploy with encryption
- name: Deploy to Capgo with Encryption
run: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey ${{ secrets.CAPGO_TOKEN }} --key-data-v2 "${{ secrets.CAPGO_PRIVATE_KEY }}" --channel production
```
Caution
**Security Best Practices:**
* Never commit the `.capgo_key_v2` file to version control
* Store the private key only in secure CI/CD secret management
* Use different keys for different environments
### Multi-Channel Configuration
[Section titled âMulti-Channel Configurationâ](#multi-channel-configuration)
For comprehensive information about setting up and managing multiple deployment channels, see the [Channels documentation](/docs/live-updates/channels/).
Complete workflow with development, pull requests, and production deployments:
```yaml
# Complete multi-environment workflow
name: Deploy to Capgo
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'npm'
- run: |
npm ci
npm run test
npm run build
- uses: actions/upload-artifact@v6
with:
name: dist
path: dist/
deploy-development:
if: github.ref == 'refs/heads/develop'
needs: build
runs-on: ubuntu-latest
environment: development
steps:
- uses: actions/setup-node@v6
with:
node-version: '24'
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- run: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey ${{ secrets.CAPGO_TOKEN }} --channel development
deploy-pr:
if: github.event_name == 'pull_request'
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v6
with:
node-version: '24'
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Deploy to PR channel
run: |
CHANNEL_NAME="pr-${{ github.event.number }}"
npm install -g @capgo/cli
npx @capgo/cli channel create $CHANNEL_NAME --apikey ${{ secrets.CAPGO_TOKEN }} || true
npx @capgo/cli bundle upload --apikey ${{ secrets.CAPGO_TOKEN }} --channel $CHANNEL_NAME
- name: Comment PR
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `đ This PR has been deployed to Capgo channel: \`pr-${{ github.event.number }}\`\n\nTo test this update in your app, configure it to use this channel. [Learn how to configure channels â](/docs/live-updates/channels/#configuring-the-channel-in-your-app)`
})
deploy-production:
if: github.ref == 'refs/heads/main'
needs: build
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/setup-node@v6
with:
node-version: '24'
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- run: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload --apikey ${{ secrets.CAPGO_TOKEN }} --channel production
```
Tip
**Testing with Channels**: After deploying to a PR or development channel, you can test the update in your app by configuring it to use that specific channel. Learn more about [configuring channels in your app](/docs/live-updates/channels/#configuring-the-channel-in-your-app).
### Cleanup Feature Channels
[Section titled âCleanup Feature Channelsâ](#cleanup-feature-channels)
Automatically clean up feature channels when branches are deleted:
```yaml
name: Cleanup Feature Channels
on:
delete:
jobs:
cleanup:
runs-on: ubuntu-latest
if: github.event.ref_type == 'branch' && startsWith(github.event.ref, 'feature/')
steps:
- uses: actions/setup-node@v6
with:
node-version: '24'
- name: Delete Capgo channel
run: |
CHANNEL_NAME=$(echo "${{ github.event.ref }}" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]')
npm install -g @capgo/cli
npx @capgo/cli channel delete $CHANNEL_NAME --apikey ${{ secrets.CAPGO_TOKEN }} || true
```
## Security and Best Practices
[Section titled âSecurity and Best Practicesâ](#security-and-best-practices)
### Environment Protection Rules
[Section titled âEnvironment Protection Rulesâ](#environment-protection-rules)
Set up environment protection rules in GitHub:
1. Go to **Settings** â **Environments** in your repository
2. Create environments: `development`, `staging`, `production`
3. For production environment, add:
* **Required reviewers**: Add team members who must approve deployments
* **Wait timer**: Add a delay before deployment (optional)
* **Deployment branches**: Restrict to `main` branch only
### Secure Secrets Management
[Section titled âSecure Secrets Managementâ](#secure-secrets-management)
Use environment-specific secrets:
```yaml
# Use different secrets per environment
deploy-production:
environment: production
steps:
- name: Deploy to Production
run: |
npx @capgo/cli bundle upload \
--apikey ${{ secrets.CAPGO_PROD_TOKEN }} \
--app ${{ secrets.CAPGO_PROD_APP_ID }} \
--channel production
```
## Monitoring and Notifications
[Section titled âMonitoring and Notificationsâ](#monitoring-and-notifications)
### Slack Integration
[Section titled âSlack Integrationâ](#slack-integration)
Add Slack notifications to your workflow:
```yaml
name: Deploy with Notifications
jobs:
deploy:
runs-on: ubuntu-latest
steps:
# ... deployment steps
- name: Notify Slack on Success
if: success()
uses: 8398a7/action-slack@v3
with:
status: success
text: 'â Capgo deployment successful!'
fields: repo,message,commit,author,action,eventName,ref,workflow
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
- name: Notify Slack on Failure
if: failure()
uses: 8398a7/action-slack@v3
with:
status: failure
text: 'â Capgo deployment failed!'
fields: repo,message,commit,author,action,eventName,ref,workflow
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
```
### Discord Integration
[Section titled âDiscord Integrationâ](#discord-integration)
Send notifications to Discord:
```yaml
- name: Discord notification
if: always()
uses: Ilshidur/action-discord@master
with:
args: |
Capgo deployment ${{ job.status }}!
App: ${{ secrets.CAPGO_APP_ID }}
Channel: ${{ github.ref_name }}
Commit: ${{ github.sha }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
```
### Email Notifications
[Section titled âEmail Notificationsâ](#email-notifications)
Configure email notifications:
```yaml
- name: Send email notification
if: failure()
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.gmail.com
server_port: 465
username: ${{ secrets.EMAIL_USERNAME }}
password: ${{ secrets.EMAIL_PASSWORD }}
subject: 'Capgo Deployment Failed - ${{ github.repository }}'
to: team@yourcompany.com
from: ci-cd@yourcompany.com
body: |
Deployment failed for ${{ github.repository }}
Branch: ${{ github.ref_name }}
Commit: ${{ github.sha }}
Workflow: ${{ github.workflow }}
```
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Debug Workflow
[Section titled âDebug Workflowâ](#debug-workflow)
Add debugging steps to troubleshoot issues:
```yaml
- name: Debug environment
run: |
echo "Node version: $(node --version)"
echo "NPM version: $(npm --version)"
echo "Working directory: $(pwd)"
echo "Files in dist/: $(ls -la dist/ || echo 'No dist directory')"
echo "Environment variables:"
env | grep -E "(GITHUB_|CAPGO_)" | sort
- name: Test Capgo CLI
run: |
npx @capgo/cli --version
npx @capgo/cli app debug --apikey ${{ secrets.CAPGO_TOKEN }} --app ${{ secrets.CAPGO_APP_ID }}
```
### Common Issues and Solutions
[Section titled âCommon Issues and Solutionsâ](#common-issues-and-solutions)
**Workflow fails with âCAPGO\_TOKEN not foundâ:**
```yaml
- name: Verify secrets
run: |
if [ -z "${{ secrets.CAPGO_TOKEN }}" ]; then
echo "ERROR: CAPGO_TOKEN secret is not set"
exit 1
fi
echo "CAPGO_TOKEN is set (length: ${#CAPGO_TOKEN})"
env:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
```
**Build artifacts not found:**
```yaml
- name: Debug artifacts
run: |
echo "Checking for build artifacts..."
ls -la dist/ || echo "No dist directory found"
find . -name "*.js" -o -name "*.html" | head -10
```
**Network connectivity issues:**
```yaml
- name: Test connectivity
run: |
ping -c 3 api.capgo.io || echo "Ping failed"
curl -I https://api.capgo.io/health || echo "Health check failed"
```
## Reusable Workflows
[Section titled âReusable Workflowsâ](#reusable-workflows)
Create reusable workflows for consistency across projects:
.github/workflows/reusable-capgo-deploy.yml
```yaml
name: Reusable Capgo Deploy
on:
workflow_call:
inputs:
environment:
required: true
type: string
channel:
required: true
type: string
secrets:
CAPGO_TOKEN:
required: true
CAPGO_APP_ID:
required: true
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'npm'
- name: Install and build
run: |
npm ci
npm run build
- name: Deploy to Capgo
run: |
npm install -g @capgo/cli
npx @capgo/cli bundle upload \
--apikey ${{ secrets.CAPGO_TOKEN }} \
--app ${{ secrets.CAPGO_APP_ID }} \
--channel ${{ inputs.channel }}
```
Use the reusable workflow:
.github/workflows/deploy.yml
```yaml
name: Deploy App
on:
push:
branches: [main, develop]
jobs:
deploy-dev:
if: github.ref == 'refs/heads/develop'
uses: ./.github/workflows/reusable-capgo-deploy.yml
with:
environment: development
channel: development
secrets:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
CAPGO_APP_ID: ${{ secrets.CAPGO_APP_ID }}
deploy-prod:
if: github.ref == 'refs/heads/main'
uses: ./.github/workflows/reusable-capgo-deploy.yml
with:
environment: production
channel: production
secrets:
CAPGO_TOKEN: ${{ secrets.CAPGO_TOKEN }}
CAPGO_APP_ID: ${{ secrets.CAPGO_APP_ID }}
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Channels](/docs/live-updates/channels/) to manage different deployment environments
* Explore [Custom Storage](/docs/live-updates/custom-storage/) for advanced deployment scenarios
* Set up [Encryption](/docs/live-updates/encryption/) for secure deployments
* Configure [Update Behavior](/docs/live-updates/update-behavior/) to customize how updates are applied
With GitHub Actions integration, you can leverage GitHubâs powerful CI/CD platform to create sophisticated deployment workflows with built-in security, monitoring, and collaboration features for your Capgo Live Updates.
# GitLab CI/CD Integration
> Learn how to integrate Capgo Live Updates with GitLab CI/CD for automated deployment of your app updates.
Integrate Capgo Live Updates with GitLab CI/CD to automatically deploy your app updates whenever you push code changes. This guide covers setting up automated builds, testing, and deployment workflows.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
Before setting up GitLab CI/CD integration, ensure you have:
* A GitLab account with a project repository
* A Capgo account with an app configured
* Node.js and npm/yarn configured in your project
## Setting Up GitLab CI/CD
[Section titled âSetting Up GitLab CI/CDâ](#setting-up-gitlab-cicd)
### Step 1: Configure Environment Variables
[Section titled âStep 1: Configure Environment Variablesâ](#step-1-configure-environment-variables)
First, set up the necessary variables in your GitLab project:
1. Navigate to your GitLab project
2. Go to **Settings** â **CI/CD** â **Variables**
3. Add the following variables:
| Variable Name | Value | Protected | Masked |
| ------------- | -------------------- | --------- | ------ |
| `CAPGO_TOKEN` | Your Capgo API token | â Yes | â Yes |
Tip
Get your Capgo API token from [console.capgo.app/apikeys](https://console.capgo.app/apikeys). Your app ID is already configured in your `capacitor.config.ts` file.
## Simple
[Section titled âSimpleâ](#simple)
Basic configuration that deploys to production on every push to the main branch:
```yaml
# .gitlab-ci.yml - Simple Configuration
image: node:22
stages:
- build
- deploy
variables:
npm_config_cache: "$CI_PROJECT_DIR/.npm"
build:
stage: build
script:
- npm ci
- npm run test
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 hour
only:
- main
deploy_production:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
# For encrypted uploads, add: --key-data-v2 "$CAPGO_PRIVATE_KEY"
dependencies:
- build
only:
- main
```
## Advanced
[Section titled âAdvancedâ](#advanced)
### Feature Branch Deployments
[Section titled âFeature Branch Deploymentsâ](#feature-branch-deployments)
Deploy feature branches to test channels for review and testing:
```yaml
# Feature branch deployment
deploy_feature:
stage: deploy
script:
- npm install -g @capgo/cli
- CHANNEL_NAME="feature-$(echo $CI_COMMIT_REF_NAME | sed 's/[^a-zA-Z0-9-]/-/g')"
- npx @capgo/cli channel create $CHANNEL_NAME --apikey $CAPGO_TOKEN || true
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
dependencies:
- build
only:
- /^feature\/.*$/
environment:
name: feature/$CI_COMMIT_REF_NAME
url: https://your-app.com/channels/$CHANNEL_NAME
```
Tip
**Testing with Channels**: After deploying to a feature channel, you can test the update in your app by configuring it to use that specific channel. Learn more about [configuring channels in your app](/docs/live-updates/channels/#configuring-the-channel-in-your-app).
### Using Encryption
[Section titled âUsing Encryptionâ](#using-encryption)
If youâre using [Capgoâs encryption feature](/docs/live-updates/encryption/), youâll need to store your private key securely in your CI/CD environment.
After [setting up encryption keys](/docs/live-updates/encryption/#setting-up-encryption) locally, add your private key to GitLab variables:
```shell
# Display your private key content (copy this output)
cat .capgo_key_v2
```
Add this content as `CAPGO_PRIVATE_KEY` in your GitLab project variables (mark as protected and masked), then use it in pipelines:
```yaml
# Deploy with encryption
deploy_production:
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --key-data-v2 "$CAPGO_PRIVATE_KEY" --channel production
```
Caution
**Security Best Practices:**
* Never commit the `.capgo_key_v2` file to version control
* Store the private key only in secure CI/CD secret management
* Use different keys for different environments
### Multi-Channel Configuration
[Section titled âMulti-Channel Configurationâ](#multi-channel-configuration)
For comprehensive information about setting up and managing multiple deployment channels, see the [Channels documentation](/docs/live-updates/channels/).
Complete configuration with multiple environments and merge request deployments:
```yaml
# .gitlab-ci.yml - Advanced Multi-Channel Configuration
image: node:22
stages:
- build
- deploy
variables:
npm_config_cache: "$CI_PROJECT_DIR/.npm"
# Build stage
build:
stage: build
script:
- npm ci
- npm run test
- npm run build
artifacts:
paths:
- dist/
expire_in: 24 hours
# Deploy to development channel
deploy_development:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel development
dependencies:
- build
only:
- develop
environment:
name: development
# Deploy merge requests to test channels
deploy_mr:
stage: deploy
script:
- npm install -g @capgo/cli
- CHANNEL_NAME="mr-$CI_MERGE_REQUEST_IID"
- npx @capgo/cli channel create $CHANNEL_NAME --apikey $CAPGO_TOKEN || true
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL_NAME
dependencies:
- build
only:
- merge_requests
environment:
name: review/$CI_MERGE_REQUEST_IID
url: https://your-app.com/channels/mr-$CI_MERGE_REQUEST_IID
on_stop: cleanup_mr
# Cleanup MR channels when MR is closed
cleanup_mr:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli channel delete mr-$CI_MERGE_REQUEST_IID --apikey $CAPGO_TOKEN || true
when: manual
environment:
name: review/$CI_MERGE_REQUEST_IID
action: stop
only:
- merge_requests
# Deploy to staging
deploy_staging:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel staging
dependencies:
- build
only:
- develop
environment:
name: staging
# Deploy to production
deploy_production:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
dependencies:
- build
only:
- main
environment:
name: production
```
### Multi-Environment with Manual Approval
[Section titled âMulti-Environment with Manual Approvalâ](#multi-environment-with-manual-approval)
For production deployments requiring manual approval:
```yaml
deploy_production:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
dependencies:
- build
only:
- main
when: manual
environment:
name: production
```
### Branch-Based Deployment Strategy
[Section titled âBranch-Based Deployment Strategyâ](#branch-based-deployment-strategy)
Deploy different branches to appropriate channels automatically:
```yaml
# Dynamic channel deployment based on branch
deploy:
stage: deploy
script:
- npm install -g @capgo/cli
- |
if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
CHANNEL="production"
elif [ "$CI_COMMIT_REF_NAME" = "develop" ]; then
CHANNEL="staging"
else
CHANNEL="development"
fi
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel $CHANNEL
dependencies:
- build
environment:
name: $CHANNEL
```
## Security Best Practices
[Section titled âSecurity Best Practicesâ](#security-best-practices)
### Protected Variables
[Section titled âProtected Variablesâ](#protected-variables)
1. **Mark Sensitive Variables**: Always mark API tokens as protected and masked
2. **Branch Protection**: Use protected variables for production deployments
3. **Access Control**: Limit variable access to maintainers only
4. **Regular Rotation**: Rotate API tokens regularly
### Secure Pipeline Configuration
[Section titled âSecure Pipeline Configurationâ](#secure-pipeline-configuration)
```yaml
# Use protected variables for production
deploy_production:
stage: deploy
script:
- npm install -g @capgo/cli
- npx @capgo/cli bundle upload --apikey $CAPGO_TOKEN --channel production
only:
refs:
- main
variables:
- $CI_COMMIT_REF_PROTECTED == "true"
```
## Monitoring and Notifications
[Section titled âMonitoring and Notificationsâ](#monitoring-and-notifications)
### Slack Integration
[Section titled âSlack Integrationâ](#slack-integration)
Add Slack notifications to your pipeline:
```yaml
notify_success:
stage: .post
image: alpine:latest
before_script:
- apk add --no-cache curl
script:
- |
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"â Capgo deployment successful for '"$CI_COMMIT_REF_NAME"'"}' \
$SLACK_WEBHOOK_URL
when: on_success
notify_failure:
stage: .post
image: alpine:latest
before_script:
- apk add --no-cache curl
script:
- |
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"â Capgo deployment failed for '"$CI_COMMIT_REF_NAME"'"}' \
$SLACK_WEBHOOK_URL
when: on_failure
```
### Email Notifications
[Section titled âEmail Notificationsâ](#email-notifications)
Configure email notifications in your GitLab project settings or use the API:
```yaml
notify_email:
stage: .post
script:
- |
curl --request POST \
--header "PRIVATE-TOKEN: $GITLAB_API_TOKEN" \
--form "to=team@yourcompany.com" \
--form "subject=Capgo Deployment Status" \
--form "body=Deployment of $CI_COMMIT_REF_NAME completed with status: $CI_JOB_STATUS" \
"https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/emails"
when: always
```
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Common Issues
[Section titled âCommon Issuesâ](#common-issues)
**Pipeline fails with âCapgo CLI not foundâ:**
```yaml
# Debug CLI installation
debug_cli:
script:
- npm install -g @capgo/cli
- which capgo || echo "Capgo CLI not found"
- npx @capgo/cli --version
```
**Authentication errors:**
```yaml
# Verify token configuration
debug_auth:
script:
- |
if [ -z "$CAPGO_TOKEN" ]; then
echo "CAPGO_TOKEN is not set"
exit 1
fi
echo "Token length: ${#CAPGO_TOKEN}"
```
**Build artifacts not found:**
```yaml
# List build outputs
debug_build:
script:
- ls -la dist/
- find dist/ -type f -name "*.js" -o -name "*.html"
```
### Debug Pipeline
[Section titled âDebug Pipelineâ](#debug-pipeline)
Add debugging information to troubleshoot issues:
```yaml
debug:
stage: build
script:
- echo "Branch: $CI_COMMIT_REF_NAME"
- echo "Commit: $CI_COMMIT_SHA"
- echo "Build: $CI_PIPELINE_ID"
- env | grep CI_ | sort
only:
- branches
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* Learn about [Channels](/docs/live-updates/channels/) to manage different deployment environments
* Explore [Custom Storage](/docs/live-updates/custom-storage/) for advanced deployment scenarios
* Set up [Encryption](/docs/live-updates/encryption/) for secure deployments
* Configure [Update Behavior](/docs/live-updates/update-behavior/) to customize how updates are applied
With GitLab CI/CD integration, you can automate your Capgo deployments and ensure consistent, reliable updates to your mobile app users.
# Rollbacks
> Learn how to manage rollbacks in Capgo, allowing you to revert to previous app versions seamlessly when needed.
While Capgoâs live updates allow you to quickly deliver improvements and fixes to your users, there may be situations where you need to roll back to a previous version of your app. Perhaps a new update introduced an unexpected critical issue, or maybe you want to revert a specific change while you work on a fix.
Capgo provides several ways to manage a channelâs builds and control the version of your app that users receive, including both manual rollback options and automatic safety mechanisms.
## Automatic Rollback Protection
[Section titled âAutomatic Rollback Protectionâ](#automatic-rollback-protection)
Capgo includes a built-in safety mechanism to protect your users from broken updates. If a JavaScript error occurs before the `notifyAppReady()` method is called, the plugin will automatically roll back to the previous working version.
### How Automatic Rollback Works
[Section titled âHow Automatic Rollback Worksâ](#how-automatic-rollback-works)
When a new update is downloaded and applied, Capgo expects your app to call `notifyAppReady()` within a configurable timeframe to confirm that the update loaded successfully. This method signals that:
* The JavaScript bundle loaded without critical errors
* Your appâs core functionality is working
* The update is safe to keep
If `notifyAppReady()` is not called due to a JavaScript crash or critical error, Capgo will:
1. Detect that the update failed to initialize properly
2. Automatically revert to the previous working bundle
3. Mark the problematic update as failed to prevent it from being applied again
Tip
Make sure to call `notifyAppReady()` in your appâs initialization code after your core components have loaded successfully. This ensures the automatic rollback protection works as intended.
```javascript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
// Call this after your app has successfully initialized
await CapacitorUpdater.notifyAppReady()
```
This automatic protection helps ensure that even if you accidentally push a broken update, your users wonât be stuck with a non-functional app.
### Configuring the Timeout
[Section titled âConfiguring the Timeoutâ](#configuring-the-timeout)
You can configure how long Capgo waits for `notifyAppReady()` to be called by setting the `appReadyTimeout` in your Capacitor configuration:
```json
{
"plugins": {
"CapacitorUpdater": {
"appReadyTimeout": 10000
}
}
}
```
The `appReadyTimeout` value is specified in milliseconds. The default timeout is typically 10 seconds, but you can adjust this based on your appâs initialization requirements. If your app takes longer to load due to complex initialization processes, you may want to increase this value.
## Rolling Back to a Previous Bundle
[Section titled âRolling Back to a Previous Bundleâ](#rolling-back-to-a-previous-bundle)
Every time you upload a new build and assign it to a channel, Capgo keeps a history of those builds. If you need to revert a specific update, you can select one of these previous builds to redeploy to the channel.

The primary way to roll back is through the rollback interface, which is located in the 4th tab (History) when viewing a channel in the Capgo Dashboard. This tab provides a comprehensive view of all available builds for the channel, allowing you to easily select and revert to any previous version.
To roll back using the History tab:
1. Log in to the [Capgo Dashboard](https://app.capgo.io).
2. Navigate to the âChannelsâ section.
3. Click the name of the channel you want to roll back.
4. Go to the 4th tab (History) in the channel view.
5. Find the build you want to revert to in the build history.
6. Select that build to make it the active build for the channel.
7. Confirm that you want to roll back to this build.
### Alternative Method: Using the Crown Icon
[Section titled âAlternative Method: Using the Crown Iconâ](#alternative-method-using-the-crown-icon)
As a second way, you can also roll back directly from the first tab by clicking the crown icon next to any build in the channelâs build history:
1. In the first tab of the channel view, find the build you want to revert to.
2. Click the crown icon next to that build to make it the active build for the channel. 
3. Confirm that you want to roll back to this build.
Note
Rolling back to a previous build only affects the selected channel. If you have multiple channels (e.g. Production, Staging, etc.), youâll need to repeat the rollback process for each affected channel.
After rolling back, devices configured to listen to the updated channel will receive the previous build the next time they check for an update. The rolled-back build will be treated as a new update, so the usual update flow and conditions apply.
## Unlinking a Channel
[Section titled âUnlinking a Channelâ](#unlinking-a-channel)
If you want to temporarily halt updates on a channel while you investigate an issue, you can unlink the channel from its current build.
To unlink a channel:
1. Navigate to the channel in the Capgo Dashboard.
2. Click the âUnlinkâ button next to the current build.
3. Confirm that you want to unlink the channel.
Once a channel is unlinked, it will not distribute any new updates. Devices configured to that channel will stay on their current build until the channel is linked to a build again.
This is useful if youâve identified a problem with an update but arenât yet sure which build you want to roll back to. Unlinking the channel gives you time to investigate without pushing out further updates.
## Forcing the Built-In Bundle
[Section titled âForcing the Built-In Bundleâ](#forcing-the-built-in-bundle)
In more severe situations, you may want to revert all devices on a channel back to the web build that was originally packaged with your appâs native binary. This is known as the âbuilt-in bundleâ.
To force the built-in bundle on a channel:
1. Navigate to the channel in the Capgo Dashboard.
2. Click the âBuilt-in Bundleâ button.
3. Confirm that you want to force the built-in bundle.
When you force the built-in bundle, all devices configured to that channel will revert back to the original packaged web build on their next update check. This happens regardless of what build theyâre currently on.
This is a more aggressive rollback option than reverting to a specific previous build, as it discards all live updates released since the app was last published to the app stores.
Caution
Be cautious when forcing the built-in bundle, as it will affect all devices on the channel. Make sure youâve considered the impact and have a plan to move forward before taking this action.
## Monitoring and Responding to Issues
[Section titled âMonitoring and Responding to Issuesâ](#monitoring-and-responding-to-issues)
To catch issues quickly and minimize the impact of problematic updates, itâs important to have a plan for monitoring your releases and responding to problems.
Some strategies include:
* Monitoring crash reports and user feedback immediately after releasing an update
* Using phased rollouts or a staged channel system to test updates on a smaller group before wide release
* Having a clear decision process for when to roll back, unlink, or force the built-in bundle, and who has the authority to do so
* Communicating to users about the issue and the resolution, if appropriate
By combining careful monitoring with the ability to quickly manage problematic updates, you can deliver a continuously improving app experience while minimizing disruptions for your users.
# Update Behavior
> Explore the comprehensive update behavior of Capgo, designed to deliver seamless updates to your app users without interrupting their experience.
When you release an update to your Capgo app, you probably want your users to receive that update as soon as possible. But you also donât want to disrupt their experience by forcing them to wait for a download or restart the app in the middle of a session.
Capgoâs update behavior is designed to strike a balance between delivering updates quickly and minimizing disruption to your users.
## Default Update Flow
[Section titled âDefault Update Flowâ](#default-update-flow)
By default, hereâs how Capgo handles app updates:
1. On app launch, the Capgo plugin checks to see if a new update is available.
2. If an update is found, itâs downloaded in the background while the user continues using the current version of the app.
3. Once the download completes, Capgo waits for the user to either background the app or kill it entirely.
4. When the user next launches the app, theyâll be running the updated version.
This flow ensures that users are always running the latest version of your app, without ever being interrupted by update prompts or forced to wait for downloads.
Tip
Capgo also checks for updates when the app resumes from the background, so users will receive updates even if they donât fully quit the app.
## Why This Approach?
[Section titled âWhy This Approach?â](#why-this-approach)
Applying updates on a background or kill event has a few key benefits for user experience:
* Users arenât interrupted by update prompts or forced to wait for downloads in the middle of a session.
* Updates are applied seamlessly in between sessions, so the experience of launching the app is always fresh.
* You can deliver updates frequently without worrying about disrupting active users.
The main downside is that if a user backgrounds and quickly resumes your app, they may lose any unsaved state since the update was applied in between those actions.
To mitigate this, we recommend:
* Saving state frequently and restoring it gracefully when the app resumes.
* Avoiding very frequent updates that modify large parts of the app state.
* Considering customizing the update behavior for sensitive flows (see below).
## Customizing When Updates Are Applied
[Section titled âCustomizing When Updates Are Appliedâ](#customizing-when-updates-are-applied)
In some cases, you may want more control over exactly when an update is applied. For example, you might want to ensure a user completes an in-progress flow before updating, or coordinate an app update with a server-side change.
Capgo provides a `setDelay` function that lets you specify conditions that must be met before an update is installed:
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater';
await CapacitorUpdater.setMultiDelay({
delayConditions: [
{
kind: 'date',
value: '2023-06-01T00:00:00.000Z',
},
{
kind: 'background',
value: '60000',
},
],
});
```
This example would delay installing an update until after June 1, 2023 AND the app has been backgrounded for at least 60 seconds.
The available delay conditions are:
* `date`: Wait until after a specific date/time to apply the update.
* `background`: Wait a minimum duration after the app is backgrounded to apply the update.
* `nativeVersion`: Wait for a native binary with a minimum version to be installed before applying the update.
* `kill`: Wait until the next app kill event to apply the update.
You can mix and match these conditions to precisely control when an update is installed.
Danger
Note that the `kill` condition currently triggers the update after the first kill event, not the next background event like the other conditions. This inconsistency will be fixed in a future release.
## Applying Updates Immediately
[Section titled âApplying Updates Immediatelyâ](#applying-updates-immediately)
For critical updates or apps with very simple state, you may want to apply an update as soon as itâs downloaded, without waiting for a background or kill event. Capgo supports this via the `directUpdate` configuration option.
Recommended: Use Delta (Manifest) Updates with Direct Update
When using `directUpdate`, we **strongly recommend** enabling [Delta (manifest) Updates](/docs/live-updates/differentials/) to minimize download times and improve the user experience. Delta (manifest) updates only download changed files instead of the entire bundle, which is especially important when updates are applied immediately while users are actively using your app.
**Why this matters for Direct Updates:**
* **Faster updates**: Smaller downloads mean updates complete quickly, reducing the time users see loading screens
* **Better mobile experience**: Users on cellular networks or slower connections wonât face long wait times
* **Lower bandwidth usage**: Only changed files are downloaded, saving data for both you and your users
When `directUpdate` is enabled in your `capacitor.config`, the CLI detects it. In non-interactive environments it sends Delta (manifest) updates automatically, and in interactive environments it prompts you to confirm before uploading. Use `--no-delta` to force a full bundle upload.
To enable Delta (manifest) updates, simply use the `--delta` flag when uploading bundles:
```shell
npx @capgo/cli@latest bundle upload --delta
```
Learn more in the [Delta (manifest) Updates documentation](/docs/live-updates/differentials/).
`directUpdate` is set in your `capacitor.config.ts` file, not in JavaScript code. It supports three values:
* `false` (default): Never do direct updates (use default behavior: download at start, set when backgrounded)
* `'atInstall'`: Direct update only when app is installed, updated from store, otherwise act as directUpdate = false
* `'onLaunch'`: Direct update only on app installed, updated from store or after app kill, otherwise act as directUpdate = false
* `'always'`: Direct update in all previous cases (app installed, updated from store, after app kill or app resume), never act as directUpdate = false
* `true` (deprecated): Same as `'always'` for backward compatibility
```typescript
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
directUpdate: 'always', // or 'atInstall' for updates only on app install/update
autoSplashscreen: true, // NEW: Automatically handle splashscreen
keepUrlPathAfterReload: true,
},
SplashScreen: {
launchAutoHide: false, // Still required when using directUpdate
},
},
};
export default config;
```
Note
**Important**: `directUpdate` only applies updates when the app actually checks for them. By default, this happens only at app startup or when resuming from background. Note that `periodCheckDelay` is not compatible with `directUpdate`.
With `directUpdate` enabled, Capgo will immediately apply an update as soon as the download completes during an update check, even if the user is actively using the app. Without periodic checking enabled, this means updates will only be applied when the app starts or resumes from background.
Note that because `directUpdate` is a native configuration, it requires some additional handling in your JavaScript code.
Caution
When using `directUpdate`, you must set `launchAutoHide: false` in the SplashScreen configuration (as shown above) to prevent the splash screen from hiding automatically. This ensures you have full control over when the splash screen is hidden after the update process completes.
## Automatic Splashscreen Handling
[Section titled âAutomatic Splashscreen Handlingâ](#automatic-splashscreen-handling)
To make `directUpdate` easier to use, Capgo provides an `autoSplashscreen` option that automatically handles hiding the splashscreen for you (available since version 7.6.0):
```typescript
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
directUpdate: 'always', // or 'atInstall'
autoSplashscreen: true, // Automatically hide splashscreen
keepUrlPathAfterReload: true,
},
SplashScreen: {
launchAutoHide: false,
},
},
};
```
When `autoSplashscreen` is enabled:
* The plugin automatically hides the splashscreen when an update is applied
* The plugin automatically hides the splashscreen when no update is needed
* You donât need to manually listen for `appReady` events or call `SplashScreen.hide()`
### Manual Splashscreen Handling
[Section titled âManual Splashscreen Handlingâ](#manual-splashscreen-handling)
If you prefer manual control or need custom logic, you can disable `autoSplashscreen` and handle it yourself:
```js
import { CapacitorUpdater } from '@capgo/capacitor-updater';
import { SplashScreen } from '@capacitor/splash-screen';
CapacitorUpdater.addListener('appReady', () => {
// Hide splash screen
SplashScreen.hide();
});
CapacitorUpdater.notifyAppReady();
```
The `appReady` event fires once the app has finished initializing and applying any pending updates. This is the point at which itâs safe to show your appâs UI, as it ensures the user will see the latest version.
In addition to handling the `appReady` event, we recommend setting the `keepUrlPathAfterReload` configuration option to `true` when using `directUpdate`. This preserves the current URL path when the app is reloaded due to an update, helping maintain the userâs location in the app and reducing disorientation.
If you donât handle the `appReady` event and set `keepUrlPathAfterReload` when using `directUpdate`, the user may briefly see a stale version of the app, be taken back to the initial route, or see a flicker as the update is applied.
Using `directUpdate` can be useful for delivering critical bug fixes or security patches, but it comes with some tradeoffs:
* The user may see a brief flicker or loading state as the update is applied if you donât properly handle the splashscreen (either with `autoSplashscreen` or manual `appReady` event handling).
* If the update modifies the app state or UI, the user may see a disruptive change in the middle of a session.
* The userâs location in the app may be lost if `keepUrlPathAfterReload` is not set, potentially disorienting them.
* Youâll need to carefully handle saving and restoring state to ensure a smooth transition.
If you do enable `directUpdate`, we recommend:
* Using `autoSplashscreen: true` for the simplest setup, or manually handling the `appReady` event if you need custom logic.
* Setting `keepUrlPathAfterReload` to `true` to preserve the userâs location in the app.
* Saving and restoring the app state as needed to avoid losing user progress.
* Thoroughly testing your appâs update behavior to ensure there are no jarring transitions, lost state, or disorienting location changes.
In most cases, the default update behavior provides the best balance of delivering updates quickly and minimizing disruption. But for apps with specific needs, Capgo provides the flexibility to customize when and how updates are applied.
# Update Types
> A comprehensive reference of all OTA update types Capgo provides: apply timing, delay conditions, version blocking, and delivery methods.
Capgo supports several types of over-the-air (OTA) updates. This page lists and explains all of them so you can choose the right combination for your app.
## Apply Timing
[Section titled âApply Timingâ](#apply-timing)
Controls **when** an update is applied after it is downloaded.
| Type | Description | Use Case |
| ----------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------------- |
| **Default** | Download in background, apply when user backgrounds or kills the app | Most apps; minimal disruption |
| **directUpdate: `atInstall`** | Apply immediately only on fresh install or app store update | New users get latest; existing users use default flow |
| **directUpdate: `onLaunch`** | Apply immediately on install, store update, or after app kill | Balance between freshness and session stability |
| **directUpdate: `always`** | Apply immediately whenever an update is downloaded (including on resume) | Critical fixes, apps with simple state |
Configure in `capacitor.config.ts`:
```typescript
plugins: {
CapacitorUpdater: {
directUpdate: false, // default
// or: 'atInstall' | 'onLaunch' | 'always'
}
}
```
Tip
For full details and splashscreen handling, see [Update Behavior](/docs/live-updates/update-behavior/).
## Delay Conditions
[Section titled âDelay Conditionsâ](#delay-conditions)
Conditions that must be met **before** an update is installed. Use `setMultiDelay` to combine them (all conditions must be satisfied).
| Condition | Description | Example |
| ----------------- | ------------------------------------------------------ | ----------------------------------------- |
| **date** | Wait until after a specific date/time | Coordinate with server-side release |
| **background** | Wait a minimum duration (ms) after app is backgrounded | Avoid applying during quick app switches |
| **nativeVersion** | Require a minimum native binary version | Block updates on incompatible native code |
| **kill** | Wait until the next app kill event | Apply only on full restart |
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater';
await CapacitorUpdater.setMultiDelay({
delayConditions: [
{ kind: 'date', value: '2023-06-01T00:00:00.000Z' },
{ kind: 'background', value: '60000' },
],
});
```
Danger
The `kill` condition triggers after the first kill event, not the next background like the others. This will be fixed in a future release.
## Version Blocking (Channel Policy)
[Section titled âVersion Blocking (Channel Policy)â](#version-blocking-channel-policy)
Controls which **semver updates** a channel will auto-deliver. Set via `--disable-auto-update` on channels.
| Strategy | Blocks | Allows | Use Case |
| ------------ | ------------------------------------ | -------------------------------------------- | ------------------------------------------------- |
| **none** | Nothing | All updates | Default; full auto-update |
| **major** | 0.0.0 â 1.0.0 | Same major (e.g. 1.x â 1.y) | Prevent breaking changes from reaching old native |
| **minor** | 0.0.0 â 1.1.0, 1.1.0 â 1.2.0 | Same minor (e.g. 1.2.x â 1.2.y) | Stricter control within major |
| **patch** | Any change except patch bump | Only 0.0.311 â 0.0.314 | Very strict; patch-only updates |
| **metadata** | Updates without `min_update_version` | Updates with explicit compatibility metadata | Custom compatibility rules per bundle |
```bash
npx @capgo/cli channel set production --disable-auto-update major
```
Caution
`patch` and `metadata` require careful setup. See [CLI commands](/docs/cli/commands/#disable-updates-strategy) and [Version Targeting](/docs/live-updates/version-targeting/) for details.
## Delivery Types
[Section titled âDelivery Typesâ](#delivery-types)
How the **bundle is transferred** to the device.
| Type | Description | When to Use |
| -------------------- | --------------------------------- | ---------------------------------------------------------- |
| **Full bundle** | Entire JS bundle is downloaded | First install, large changes, or when delta is unavailable |
| **Delta (manifest)** | Only changed files are downloaded | Most updates; faster and bandwidth-friendly |
```bash
# Full bundle (default)
npx @capgo/cli bundle upload --channel production
# Delta updates
npx @capgo/cli bundle upload --channel production --delta
```
Tip
When using `directUpdate`, enable [Delta updates](/docs/live-updates/differentials/) to minimize download time and improve UX.
## Quick Reference
[Section titled âQuick Referenceâ](#quick-reference)
| Category | Types |
| -------------------- | --------------------------------------------- |
| **Apply timing** | Default, `atInstall`, `onLaunch`, `always` |
| **Delay conditions** | `date`, `background`, `nativeVersion`, `kill` |
| **Version blocking** | `none`, `major`, `minor`, `patch`, `metadata` |
| **Delivery** | Full bundle, Delta (manifest) |
## Related
[Section titled âRelatedâ](#related)
* [Update Behavior](/docs/live-updates/update-behavior/) â Configure apply timing and delays
* [Version Targeting](/docs/live-updates/version-targeting/) â Channel-based version routing
* [Delta (manifest) Updates](/docs/live-updates/differentials/) â Enable partial downloads
* [Channels](/docs/live-updates/channels/) â Channel configuration and precedence
# Version Targeting
> Automatically deliver compatible updates to users based on their native app version
This guide explains how to automatically deliver the latest compatible bundle to users based on their native app version, **similar to Ionic AppFlowâs approach**. This ensures simplified update management and faster rollouts while preventing compatibility issues.
Migrating from Ionic AppFlow?
If youâre coming from Ionic AppFlow, this guide is especially important for you. AppFlow automatically matched updates to native versions, and Capgo provides the same capability with even more control and flexibility. See the [AppFlow Migration Guide](/docs/upgrade/from-appflow-to-capgo) for step-by-step migration instructions.
## Overview
[Section titled âOverviewâ](#overview)
Capgoâs version targeting system allows you to:
* **Automatically deliver compatible updates** to users based on their native app version
* **Prevent breaking changes** from reaching incompatible app versions
* **Manage multiple app versions** simultaneously without complex logic
* **Seamlessly roll out updates** to specific user segments
### Why Version Targeting Matters (Especially for AppFlow Users)
[Section titled âWhy Version Targeting Matters (Especially for AppFlow Users)â](#why-version-targeting-matters-especially-for-appflow-users)
If youâre familiar with **Ionic AppFlow**, you know how critical it is to ensure users receive only compatible updates. AppFlow automatically matched live update bundles to native app versions, preventing incompatible JavaScript from being delivered to older native code.
**Capgo provides the same safety guarantees**, with additional features:
* More granular control over version matching
* Multiple strategies (channels, semver, native constraints)
* Better visibility into version distribution
* API and CLI control alongside dashboard management
This approach is particularly useful when:
* You have users on different major versions of your app (e.g., v1.x, v2.x, v3.x)
* You need to maintain backward compatibility while rolling out breaking changes
* You want to prevent newer bundles from breaking older native code
* Youâre migrating users gradually from one version to another
* **Youâre migrating from AppFlow** and want to maintain the same update safety
## How It Works
[Section titled âHow It Worksâ](#how-it-works)
Capgo uses a multi-layered approach to match users with compatible updates:
1. **Native Version Constraints**: Prevent bundles from being delivered to incompatible native versions
2. **Channel-Based Routing**: Route different app versions to different update channels
3. **Semantic Versioning Controls**: Automatically block updates across major/minor/patch boundaries
4. **Device-Level Overrides**: Target specific devices or user groups
### Version Matching Flow
[Section titled âVersion Matching Flowâ](#version-matching-flow)
```mermaid
graph TD
A[User Opens App] --> B{Check Device Override}
B -->|Override Set| C[Use Override Channel]
B -->|No Override| D{Check defaultChannel in App}
D -->|Has defaultChannel| E[Use App's defaultChannel]
D -->|No defaultChannel| F[Use Cloud Default Channel]
C --> G{Check Version Constraints}
E --> G
F --> G
G -->|Compatible| H[Deliver Update]
G -->|Incompatible| I[Skip Update]
```
## Strategy 1: Channel-Based Version Routing
[Section titled âStrategy 1: Channel-Based Version Routingâ](#strategy-1-channel-based-version-routing)
This is the **recommended approach** for managing breaking changes and major version updates. Itâs similar to AppFlowâs delivery model.
### Example Scenario
[Section titled âExample Scenarioâ](#example-scenario)
* **App v1.x** (100,000 users) â `production` channel
* **App v2.x** (50,000 users with breaking changes) â `v2` channel
* **App v3.x** (10,000 beta users) â `v3` channel
### Implementation
[Section titled âImplementationâ](#implementation)
#### Step 1: Configure Channels for Each Major Version
[Section titled âStep 1: Configure Channels for Each Major Versionâ](#step-1-configure-channels-for-each-major-version)
```typescript
// capacitor.config.ts for version 1.x builds
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'Example App',
plugins: {
CapacitorUpdater: {
autoUpdate: true,
defaultChannel: 'production', // or omit for default
}
}
};
export default config;
```
```typescript
// capacitor.config.ts for version 2.x builds
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'Example App',
plugins: {
CapacitorUpdater: {
autoUpdate: true,
defaultChannel: 'v2', // Routes v2 users automatically
}
}
};
```
```typescript
// capacitor.config.ts for version 3.x builds
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'Example App',
plugins: {
CapacitorUpdater: {
autoUpdate: true,
defaultChannel: 'v3', // Routes v3 users automatically
}
}
};
```
#### Step 2: Create Channels
[Section titled âStep 2: Create Channelsâ](#step-2-create-channels)
```bash
# Create channels for each major version
npx @capgo/cli channel create production
npx @capgo/cli channel create v2
npx @capgo/cli channel create v3
# Enable self-assignment so apps can switch channels
npx @capgo/cli channel set production --self-assign
npx @capgo/cli channel set v2 --self-assign
npx @capgo/cli channel set v3 --self-assign
```
#### Step 3: Upload Version-Specific Bundles
[Section titled âStep 3: Upload Version-Specific Bundlesâ](#step-3-upload-version-specific-bundles)
```bash
# For v1.x users (from v1-maintenance branch)
git checkout v1-maintenance
npm run build
npx @capgo/cli bundle upload --channel production
# For v2.x users (from v2-maintenance or main branch)
git checkout main
npm run build
npx @capgo/cli bundle upload --channel v2
# For v3.x users (from beta/v3 branch)
git checkout beta
npm run build
npx @capgo/cli bundle upload --channel v3
```
Automatic Routing
When users open the app, they automatically connect to their designated channel based on the `defaultChannel` in their installed app bundle. No JavaScript code changes required!
### Benefits
[Section titled âBenefitsâ](#benefits)
* **Zero code changes** - Channel routing happens automatically
* **Clear separation** - Each version has its own update pipeline
* **Flexible targeting** - Push updates to specific version groups
* **Safe rollouts** - Breaking changes never reach incompatible versions
## Strategy 2: Semantic Versioning Controls
[Section titled âStrategy 2: Semantic Versioning Controlsâ](#strategy-2-semantic-versioning-controls)
Use Capgoâs built-in semantic versioning controls to prevent updates across version boundaries.
### Disable Auto-Update Across Major Versions
[Section titled âDisable Auto-Update Across Major Versionsâ](#disable-auto-update-across-major-versions)
```bash
# Create a channel that blocks major version updates
npx @capgo/cli channel create stable --disable-auto-update major
```
This configuration means:
* Users on app version **1.2.3** will receive updates up to **1.9.9**
* Users will **NOT** receive version **2.0.0** automatically
* Prevents breaking changes from reaching older native code
### Granular Control Options
[Section titled âGranular Control Optionsâ](#granular-control-options)
```bash
# Block minor version updates (1.2.x won't get 1.3.0)
npx @capgo/cli channel set stable --disable-auto-update minor
# Block patch updates (1.2.3 won't get 1.2.4)
npx @capgo/cli channel set stable --disable-auto-update patch
# Allow all updates
npx @capgo/cli channel set stable --disable-auto-update none
```
Semantic Versioning Required
This strategy only works if you follow semantic versioning (semver) for your app versions. Ensure your version numbers follow the `MAJOR.MINOR.PATCH` format.
## Strategy 3: Native Version Constraints
[Section titled âStrategy 3: Native Version Constraintsâ](#strategy-3-native-version-constraints)
Specify minimum native version requirements for bundles to prevent delivery to incompatible devices.
### Using nativeVersion Delay Condition
[Section titled âUsing nativeVersion Delay Conditionâ](#using-nativeversion-delay-condition)
When uploading a bundle, you can specify a minimum native version:
```bash
# This bundle requires native version 2.0.0 or higher
npx @capgo/cli bundle upload \
--channel production \
--native-version "2.0.0"
```
How It Works
Devices on native version 1.x will NOT receive this bundle. Only devices on 2.0.0+ will get it. This is perfect for updates that require new native APIs or plugins.
### Use Cases
[Section titled âUse Casesâ](#use-cases)
1. **New Native Plugin Required**
```bash
# Bundle needs Camera plugin added in v2.0.0
npx @capgo/cli bundle upload --native-version "2.0.0"
```
2. **Breaking Native API Changes**
```bash
# Bundle uses new Capacitor 6 APIs
npx @capgo/cli bundle upload --native-version "3.0.0"
```
3. **Gradual Migration**
```bash
# Test bundle only on latest native version
npx @capgo/cli bundle upload \
--channel beta \
--native-version "2.5.0"
```
## Strategy 4: Auto-Downgrade Prevention
[Section titled âStrategy 4: Auto-Downgrade Preventionâ](#strategy-4-auto-downgrade-prevention)
Prevent users from receiving bundles older than their current native version.
### Enable in Channel Settings
[Section titled âEnable in Channel Settingsâ](#enable-in-channel-settings)
In the Capgo dashboard:
1. Go to **Channels** â Select your channel
2. Enable **âDisable auto downgrade under nativeâ**
3. Save changes
Or via CLI:
```bash
npx @capgo/cli channel set production --disable-downgrade
```
### Example
[Section titled âExampleâ](#example)
* Userâs device: Native version **1.2.5**
* Channel bundle: Version **1.2.3**
* **Result**: Update is blocked (would be a downgrade)
This is useful when:
* Users manually installed a newer version from the app store
* You need to ensure users always have the latest security patches
* You want to prevent regression bugs
## Strategy 5: Device-Level Targeting
[Section titled âStrategy 5: Device-Level Targetingâ](#strategy-5-device-level-targeting)
Override channel assignment for specific devices or user groups.
### Force Specific Version for Testing
[Section titled âForce Specific Version for Testingâ](#force-specific-version-for-testing)
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater'
// Force beta testers to use v3 channel
async function assignBetaTesters() {
const deviceId = await CapacitorUpdater.getDeviceId()
// Check if user is beta tester
if (isBetaTester(userId)) {
await CapacitorUpdater.setChannel({ channel: 'v3' })
}
}
```
### Dashboard Device Override
[Section titled âDashboard Device Overrideâ](#dashboard-device-override)
In the Capgo dashboard:
1. Go to **Devices** â Find device
2. Click **Set Channel** or **Set Version**
3. Override with specific channel or bundle version
4. Device will receive updates from overridden source
Testing Updates
Use device overrides to test updates on your own device before rolling out to all users.
## Complete AppFlow-Style Workflow
[Section titled âComplete AppFlow-Style Workflowâ](#complete-appflow-style-workflow)
Hereâs a complete example combining all strategies:
### 1. Initial Setup (App v1.0.0)
[Section titled â1. Initial Setup (App v1.0.0)â](#1-initial-setup-app-v100)
```bash
# Create production channel with semver controls
npx @capgo/cli channel create production \
--disable-auto-update major \
--disable-downgrade
```
capacitor.config.ts
```typescript
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
defaultChannel: 'production',
}
}
};
```
### 2. Release Breaking Change (App v2.0.0)
[Section titled â2. Release Breaking Change (App v2.0.0)â](#2-release-breaking-change-app-v200)
```bash
# Create v2 channel for new version
npx @capgo/cli channel create v2 \
--disable-auto-update major \
--disable-downgrade \
--self-assign
# Create git branch for v1 maintenance
git checkout -b v1-maintenance
git push origin v1-maintenance
```
```typescript
// capacitor.config.ts for v2.0.0
const config: CapacitorConfig = {
plugins: {
CapacitorUpdater: {
autoUpdate: true,
defaultChannel: 'v2', // New users get v2 channel
}
}
};
```
### 3. Push Updates to Both Versions
[Section titled â3. Push Updates to Both Versionsâ](#3-push-updates-to-both-versions)
```bash
# Update v1.x users (bug fix)
git checkout v1-maintenance
# Make changes
npx @capgo/cli bundle upload \
--channel production \
--native-version "1.0.0"
# Update v2.x users (new feature)
git checkout main
# Make changes
npx @capgo/cli bundle upload \
--channel v2 \
--native-version "2.0.0"
```
### 4. Monitor Version Distribution
[Section titled â4. Monitor Version Distributionâ](#4-monitor-version-distribution)
Use the Capgo dashboard to track:
* How many users are on v1 vs v2
* Bundle adoption rates per version
* Errors or crashes per version
### 5. Deprecate Old Version
[Section titled â5. Deprecate Old Versionâ](#5-deprecate-old-version)
Once v1 usage drops below threshold:
```bash
# Stop uploading to production channel
# Optional: Delete v1 maintenance branch
git branch -d v1-maintenance
# Move all remaining users to default
# (They'll need to update via app store)
```
## Channel Precedence
[Section titled âChannel Precedenceâ](#channel-precedence)
When multiple channel configurations exist, Capgo uses this precedence order:
1. **Device Override** (Dashboard or API) - Highest priority
2. **Cloud Override** via `setChannel()` call
3. **defaultChannel** in capacitor.config.ts
4. **Default Channel** (Cloud setting) - Lowest priority
Precedence Example
If a userâs app has `defaultChannel: 'v2'` but you override their device to `'beta'` in the dashboard, theyâll receive updates from the `'beta'` channel.
## Best Practices
[Section titled âBest Practicesâ](#best-practices)
### 1. Always Set defaultChannel for Major Versions
[Section titled â1. Always Set defaultChannel for Major Versionsâ](#1-always-set-defaultchannel-for-major-versions)
```typescript
// â Good: Each major version has explicit channel
// v1.x â production
// v2.x â v2
// v3.x â v3
// â Bad: Relying on dynamic channel switching
// All versions â production, switch manually
```
### 2. Use Semantic Versioning
[Section titled â2. Use Semantic Versioningâ](#2-use-semantic-versioning)
```bash
# â Good
1.0.0 â 1.0.1 â 1.1.0 â 2.0.0
# â Bad
1.0 â 1.1 â 2 â 2.5
```
### 3. Maintain Separate Branches
[Section titled â3. Maintain Separate Branchesâ](#3-maintain-separate-branches)
```bash
# â Good: Separate branches per major version
main (v3.x)
v2-maintenance (v2.x)
v1-maintenance (v1.x)
# â Bad: Single branch for all versions
```
### 4. Test Before Rollout
[Section titled â4. Test Before Rolloutâ](#4-test-before-rollout)
```bash
# Test on beta channel first
npx @capgo/cli bundle upload --channel beta
# Monitor for issues, then promote to production
npx @capgo/cli bundle upload --channel production
```
### 5. Monitor Version Distribution
[Section titled â5. Monitor Version Distributionâ](#5-monitor-version-distribution)
Regularly check your dashboard:
* Are users upgrading to newer native versions?
* Are old versions still getting high traffic?
* Should you deprecate old channels?
## Comparison with Ionic AppFlow
[Section titled âComparison with Ionic AppFlowâ](#comparison-with-ionic-appflow)
For teams migrating from **Ionic AppFlow**, hereâs how Capgoâs version targeting compares:
| Feature | Ionic AppFlow | Capgo |
| ------------------------------ | ----------------------------------------- | --------------------------------------------------------- |
| **Version-based routing** | Automatic based on native version | Automatic via `defaultChannel` + multiple strategies |
| **Semantic versioning** | Basic support | Advanced with `--disable-auto-update` (major/minor/patch) |
| **Native version constraints** | Manual configuration in AppFlow dashboard | Built-in `--native-version` flag in CLI |
| **Channel management** | Web UI + CLI | Web UI + CLI + API |
| **Device overrides** | Limited device-level control | Full control via Dashboard/API |
| **Auto-downgrade prevention** | Yes | Yes via `--disable-downgrade` |
| **Multi-version maintenance** | Manual branch/channel management | Automated with channel precedence |
| **Self-hosting** | No | Yes (full control) |
| **Version analytics** | Basic | Detailed per-version metrics |
AppFlow Parity and Beyond
Capgo provides **all the version targeting capabilities** that AppFlow offered, plus additional control mechanisms. If you relied on AppFlowâs automatic version matching, youâll find Capgo equally safe with more flexibility.
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
### Users Not Receiving Updates
[Section titled âUsers Not Receiving Updatesâ](#users-not-receiving-updates)
Check the following:
1. **Channel Assignment**: Verify device is on correct channel
```typescript
const channel = await CapacitorUpdater.getChannel()
console.log('Current channel:', channel)
```
2. **Version Constraints**: Check if bundle has native version requirements
* Dashboard â Bundles â Check âNative Versionâ column
3. **Semver Settings**: Verify channelâs `disable-auto-update` setting
```bash
npx @capgo/cli channel list
```
4. **Device Override**: Check if device has manual override
* Dashboard â Devices â Search for device â Check channel/version
### Bundle Delivered to Wrong Version
[Section titled âBundle Delivered to Wrong Versionâ](#bundle-delivered-to-wrong-version)
1. **Review defaultChannel**: Ensure correct channel in `capacitor.config.ts`
2. **Check Bundle Upload**: Verify bundle was uploaded to intended channel
3. **Inspect Native Version**: Confirm `--native-version` flag was used correctly
### Breaking Changes Affecting Old Versions
[Section titled âBreaking Changes Affecting Old Versionsâ](#breaking-changes-affecting-old-versions)
1. **Immediate Fix**: Override affected devices to safe bundle
* Dashboard â Devices â Bulk select â Set Version
2. **Long-term Fix**: Create versioned channels and maintain separate branches
3. **Prevention**: Always test updates on representative devices before rollout
## Migration from Ionic AppFlow
[Section titled âMigration from Ionic AppFlowâ](#migration-from-ionic-appflow)
If youâre migrating from **Ionic AppFlow**, version targeting works very similarly in Capgo, with improved flexibility:
### Concept Mapping
[Section titled âConcept Mappingâ](#concept-mapping)
| AppFlow Concept | Capgo Equivalent | Notes |
| ------------------------------ | ----------------------------------------------- | --------------------------------- |
| **Deploy Channel** | Capgo Channel | Same concept, more powerful |
| **Native Version Lock** | `--native-version` flag | More granular control |
| **Channel Priority** | Channel precedence (override â cloud â default) | More transparent precedence |
| **Deployment Target** | Channel + semver controls | Multiple strategies available |
| **Production Channel** | `production` channel (or any name) | Flexible naming |
| **Git-based deployment** | CLI bundle upload from branch | Same workflow |
| **Automatic version matching** | `defaultChannel` + version constraints | Enhanced with multiple strategies |
### Key Differences for AppFlow Users
[Section titled âKey Differences for AppFlow Usersâ](#key-differences-for-appflow-users)
1. **More Control**: Capgo gives you multiple strategies (channels, semver, native version) that can be combined
2. **Better Visibility**: Dashboard shows version distribution and compatibility issues
3. **API Access**: Full programmatic control over version targeting
4. **Self-Hosting**: Option to run your own update server with same version logic
### Migration Steps
[Section titled âMigration Stepsâ](#migration-steps)
1. **Map your AppFlow channels** to Capgo channels (usually 1:1)
2. **Set `defaultChannel`** in `capacitor.config.ts` for each major version
3. **Configure semver rules** if you want automatic blocking at version boundaries
4. **Upload version-specific bundles** using `--native-version` flag
5. **Monitor version distribution** in Capgo dashboard
Complete Migration Guide
For complete migration instructions including SDK replacement and API mapping, see the [AppFlow to Capgo Migration Guide](/docs/upgrade/from-appflow-to-capgo).
## Advanced Patterns
[Section titled âAdvanced Patternsâ](#advanced-patterns)
### Gradual Rollout by Version
[Section titled âGradual Rollout by Versionâ](#gradual-rollout-by-version)
```typescript
// Gradually migrate v1 users to v2
async function migrateUsers() {
const deviceId = await CapacitorUpdater.getDeviceId()
const rolloutPercentage = 10 // Start with 10%
// Hash device ID to get deterministic percentage
const hash = hashCode(deviceId) % 100
if (hash < rolloutPercentage) {
// User is in rollout group - migrate to v2
await CapacitorUpdater.setChannel({ channel: 'v2' })
}
}
```
### Feature Flags by Version
[Section titled âFeature Flags by Versionâ](#feature-flags-by-version)
```typescript
// Enable features based on native version
async function checkFeatureAvailability() {
const info = await CapacitorUpdater.getDeviceId()
const nativeVersion = info.nativeVersion
if (compareVersions(nativeVersion, '2.0.0') >= 0) {
// Enable features requiring v2.0.0+
enableNewCameraFeature()
}
}
```
### A/B Testing Across Versions
[Section titled âA/B Testing Across Versionsâ](#ab-testing-across-versions)
```typescript
// Run A/B tests within same native version
async function assignABTest() {
const nativeVersion = await getNativeVersion()
if (nativeVersion.startsWith('2.')) {
// Only A/B test on v2 users
const variant = Math.random() < 0.5 ? 'v2-test-a' : 'v2-test-b'
await CapacitorUpdater.setChannel({ channel: variant })
}
}
```
## Summary
[Section titled âSummaryâ](#summary)
Capgo provides multiple strategies for version-specific update delivery:
1. **Channel-Based Routing**: Automatic version separation via `defaultChannel`
2. **Semantic Versioning**: Prevent updates across major/minor/patch boundaries
3. **Native Version Constraints**: Require minimum native version for bundles
4. **Auto-Downgrade Prevention**: Never deliver older bundles to newer native versions
5. **Device Overrides**: Manual control for testing and targeting
By combining these strategies, you can achieve AppFlow-style automatic update delivery with even more flexibility and control. Choose the approach that best fits your appâs versioning and deployment workflow.
For more details on specific features:
* [Breaking Changes Guide](/docs/live-updates/breaking-changes) - Detailed channel versioning strategy
* [Channel Management](/docs/live-updates/channels) - Complete channel configuration reference
* [Update Behavior](/docs/live-updates/update-behavior) - Native version delays and conditions
# Functions and settings
> All available method and settings of the plugin
# Updater Plugin Config
[Section titled âUpdater Plugin Configâ](#updater-plugin-config)
CapacitorUpdater can be configured with these options:
| Prop | Type | Description | Default | Since |
| ------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------ |
| **`appReadyTimeout`** | `number` | Configure the number of milliseconds the native plugin should wait before considering an update âfailedâ. Only available for Android and iOS. | `10000 // (10 seconds)` | |
| **`responseTimeout`** | `number` | Configure the number of seconds the native plugin should wait before considering API timeout. Only available for Android and iOS. | `20 // (20 second)` | |
| **`autoDeleteFailed`** | `boolean` | Configure whether the plugin should use automatically delete failed bundles. Only available for Android and iOS. | `true` | |
| **`autoDeletePrevious`** | `boolean` | Configure whether the plugin should use automatically delete previous bundles after a successful update. Only available for Android and iOS. | `true` | |
| **`autoUpdate`** | `boolean` | Configure whether the plugin should use Auto Update via an update server. Only available for Android and iOS. | `true` | |
| **`resetWhenUpdate`** | `boolean` | Automatically delete previous downloaded bundles when a newer native app bundle is installed to the device. Setting this to false can broke the auto update flow if the user download from the store a native app bundle that is older than the current downloaded bundle. Upload will be prevented by channel setting downgrade\_under\_native. Only available for Android and iOS. | `true` | |
| **`updateUrl`** | `string` | Configure the URL / endpoint to which update checks are sent. Only available for Android and iOS. | `https://plugin.capgo.app/updates` | |
| **`channelUrl`** | `string` | Configure the URL / endpoint for channel operations. Only available for Android and iOS. | `https://plugin.capgo.app/channel_self` | |
| **`statsUrl`** | `string` | Configure the URL / endpoint to which update statistics are sent. Only available for Android and iOS. Set to "" to disable stats reporting. | `https://plugin.capgo.app/stats` | |
| **`publicKey`** | `string` | Configure the public key for end to end live update encryption Version 2 Only available for Android and iOS. | `undefined` | 6.2.0 |
| **`version`** | `string` | Configure the current version of the app. This will be used for the first update request. If not set, the plugin will get the version from the native code. Only available for Android and iOS. | `undefined` | 4.17.48 |
| **`directUpdate`** | \`boolean | âalways' | 'atInstall' | 'onLaunchâ\` |
| **`autoSplashscreen`** | `boolean` | Automatically handle splashscreen hiding when using directUpdate. When enabled, the plugin will automatically hide the splashscreen after updates are applied or when no update is needed. This removes the need to manually listen for appReady events and call SplashScreen.hide(). Only works when directUpdate is set to âatInstallâ, âalwaysâ, âonLaunchâ, or true. Requires the @capacitor/splash-screen plugin to be installed and configured with launchAutoHide: false. Requires autoUpdate and directUpdate to be enabled. Only available for Android and iOS. | `false` | 7.6.0 |
| **`autoSplashscreenLoader`** | `boolean` | Display a native loading indicator on top of the splashscreen while automatic direct updates are running. Only takes effect when {@link autoSplashscreen} is enabled. Requires the @capacitor/splash-screen plugin to be installed and configured with launchAutoHide: false. Only available for Android and iOS. | `false` | 7.19.0 |
| **`autoSplashscreenTimeout`** | `number` | Automatically hide the splashscreen after the specified number of milliseconds when using automatic direct updates. If the timeout elapses, the update continues to download in the background while the splashscreen is dismissed. Set to `0` (zero) to disable the timeout. When the timeout fires, the direct update flow is skipped and the downloaded bundle is installed on the next background/launch. Requires {@link autoSplashscreen} to be enabled. Only available for Android and iOS. | `10000 // (10 seconds)` | 7.19.0 |
| **`periodCheckDelay`** | `number` | Configure the delay period for period update check. the unit is in seconds. Only available for Android and iOS. Cannot be less than 600 seconds (10 minutes). | `0 (disabled)` | |
| **`localS3`** | `boolean` | Configure the CLI to use a local server for testing or self-hosted update server. | `undefined` | 4.17.48 |
| **`localHost`** | `string` | Configure the CLI to use a local server for testing or self-hosted update server. | `undefined` | 4.17.48 |
| **`localWebHost`** | `string` | Configure the CLI to use a local server for testing or self-hosted update server. | `undefined` | 4.17.48 |
| **`localSupa`** | `string` | Configure the CLI to use a local server for testing or self-hosted update server. | `undefined` | 4.17.48 |
| **`localSupaAnon`** | `string` | Configure the CLI to use a local server for testing. | `undefined` | 4.17.48 |
| **`localApi`** | `string` | Configure the CLI to use a local api for testing. | `undefined` | 6.3.3 |
| **`localApiFiles`** | `string` | Configure the CLI to use a local file api for testing. | `undefined` | 6.3.3 |
| **`allowModifyUrl`** | `boolean` | Allow the plugin to modify the updateUrl, statsUrl and channelUrl dynamically from the JavaScript side. | `false` | 5.4.0 |
| **`allowModifyAppId`** | `boolean` | Allow the plugin to modify the appId dynamically from the JavaScript side. | `false` | 7.14.0 |
| **`allowManualBundleError`** | `boolean` | Allow marking bundles as errored from JavaScript while using manual update flows. When enabled, {@link CapacitorUpdaterPlugin.setBundleError} can change a bundle status to `error`. | `false` | 7.20.0 |
| **`persistCustomId`** | `boolean` | Persist the customId set through {@link CapacitorUpdaterPlugin.setCustomId} across app restarts. Only available for Android and iOS. | `false (will be true by default in a future major release v8.x.x)` | 7.17.3 |
| **`persistModifyUrl`** | `boolean` | Persist the updateUrl, statsUrl and channelUrl set through {@link CapacitorUpdaterPlugin.setUpdateUrl}, {@link CapacitorUpdaterPlugin.setStatsUrl} and {@link CapacitorUpdaterPlugin.setChannelUrl} across app restarts. Only available for Android and iOS. | `false` | 7.20.0 |
| **`allowSetDefaultChannel`** | `boolean` | Allow or disallow the {@link CapacitorUpdaterPlugin.setChannel} method to modify the defaultChannel. When set to `false`, calling `setChannel()` will return an error with code `disabled_by_config`. | `true` | 7.34.0 |
| **`defaultChannel`** | `string` | Set the default channel for the app in the config. Case sensitive. This will setting will override the default channel set in the cloud, but will still respect overrides made in the cloud. This requires the channel to allow devices to self dissociate/associate in the channel settings. | `undefined` | 5.5.0 |
| **`appId`** | `string` | Configure the app id for the app in the config. | `undefined` | 6.0.0 |
| **`keepUrlPathAfterReload`** | `boolean` | Configure the plugin to keep the URL path after a reload. WARNING: When a reload is triggered, âwindow\.historyâ will be cleared. | `false` | 6.8.0 |
| **`disableJSLogging`** | `boolean` | Disable the JavaScript logging of the plugin. if true, the plugin will not log to the JavaScript console. only the native log will be done | `false` | 7.3.0 |
| **`osLogging`** | `boolean` | Enable OS-level logging. When enabled, logs are written to the system log which can be inspected in production builds. - **iOS**: Uses os\_log instead of Swift.print, logs accessible via Console.app or Instruments - **Android**: Logs to Logcat (android.util.Log) When set to false, system logging is disabled on both platforms (only JavaScript console logging will occur if enabled). This is useful for debugging production apps (App Store/TestFlight builds on iOS, or production APKs on Android). | `true` | 8.42.0 |
| **`shakeMenu`** | `boolean` | Enable shake gesture to show update menu for debugging/testing purposes | `false` | 7.5.0 |
| **`allowShakeChannelSelector`** | `boolean` | Enable the shake gesture to show a channel selector menu for switching between update channels. When enabled AND `shakeMenu` is true, the shake gesture shows a channel selector instead of the default debug menu (Go Home/Reload/Close). After selecting a channel, the app automatically checks for updates and downloads if available. Only works if channels have `allow_self_set` enabled on the backend. Only available for Android and iOS. | `false` | 8.43.0 |
## API Reference
[Section titled âAPI Referenceâ](#api-reference)
* [`notifyAppReady`](#notifyappready)
* [`setUpdateUrl`](#setupdateurl)
* [`setStatsUrl`](#setstatsurl)
* [`setChannelUrl`](#setchannelurl)
* [`download`](#download)
* [`next`](#next)
* [`set`](#set)
* [`delete`](#delete)
* [`setBundleError`](#setbundleerror)
* [`list`](#list)
* [`reset`](#reset)
* [`current`](#current)
* [`reload`](#reload)
* [`setMultiDelay`](#setmultidelay)
* [`cancelDelay`](#canceldelay)
* [`getLatest`](#getlatest)
* [`setChannel`](#setchannel)
* [`unsetChannel`](#unsetchannel)
* [`getChannel`](#getchannel)
* [`listChannels`](#listchannels)
* [`setCustomId`](#setcustomid)
* [`getBuiltinVersion`](#getbuiltinversion)
* [`getDeviceId`](#getdeviceid)
* [`getPluginVersion`](#getpluginversion)
* [`isAutoUpdateEnabled`](#isautoupdateenabled)
* [`removeAllListeners`](#removealllisteners)
* [`addListener('download')`](#addlistenerdownload-)
* [`addListener('noNeedUpdate')`](#addlistenernoneedupdate-)
* [`addListener('updateAvailable')`](#addlistenerupdateavailable-)
* [`addListener('downloadComplete')`](#addlistenerdownloadcomplete-)
* [`addListener('breakingAvailable')`](#addlistenerbreakingavailable-)
* [`addListener('majorAvailable')`](#addlistenermajoravailable-)
* [`addListener('updateFailed')`](#addlistenerupdatefailed-)
* [`addListener('set')`](#addlistenerset-)
* [`addListener('setNext')`](#addlistenersetnext-)
* [`addListener('downloadFailed')`](#addlistenerdownloadfailed-)
* [`addListener('appReloaded')`](#addlistenerappreloaded-)
* [`addListener('appReady')`](#addlistenerappready-)
* [`addListener('channelPrivate')`](#addlistenerchannelprivate-)
* [`addListener('onFlexibleUpdateStateChange')`](#addlisteneronflexibleupdatestatechange-)
* [`isAutoUpdateAvailable`](#isautoupdateavailable)
* [`getNextBundle`](#getnextbundle)
* [`getFailedUpdate`](#getfailedupdate)
* [`setShakeMenu`](#setshakemenu)
* [`isShakeMenuEnabled`](#isshakemenuenabled)
* [`setShakeChannelSelector`](#setshakechannelselector)
* [`isShakeChannelSelectorEnabled`](#isshakechannelselectorenabled)
* [`getAppId`](#getappid)
* [`setAppId`](#setappid)
* [`getAppUpdateInfo`](#getappupdateinfo)
* [`openAppStore`](#openappstore)
* [`performImmediateUpdate`](#performimmediateupdate)
* [`startFlexibleUpdate`](#startflexibleupdate)
* [`completeFlexibleUpdate`](#completeflexibleupdate)
### notifyAppReady
[Section titled ânotifyAppReadyâ](#notifyappready)
```typescript
notifyAppReady() => Promise
```
Notify the native layer that JavaScript initialized successfully.
**CRITICAL: You must call this method on every app launch to prevent automatic rollback.**
This is a simple notification to confirm that your bundleâs JavaScript loaded and executed. The native web server successfully served the bundle files and your JS runtime started. Thatâs all it checks - nothing more complex.
**What triggers rollback:**
* NOT calling this method within the timeout (default: 10 seconds)
* Complete JavaScript failure (bundle wonât load at all)
**What does NOT trigger rollback:**
* Runtime errors after initialization (API failures, crashes, etc.)
* Network request failures
* Application logic errors
**IMPORTANT: Call this BEFORE any network requests.** Donât wait for APIs, data loading, or async operations. Call it as soon as your JavaScript bundle starts executing to confirm the bundle itself is valid.
Best practices:
* Call immediately in your app entry point (main.js, app component mount, etc.)
* Donât put it after network calls or heavy initialization
* Donât wrap it in try/catch with conditions
* Adjust {@link PluginsConfig.CapacitorUpdater.appReadyTimeout} if you need more time
**Returns**
`Promise` â Always resolves successfully with current bundle info. This method never fails.
***
### setUpdateUrl
[Section titled âsetUpdateUrlâ](#setupdateurl)
```typescript
setUpdateUrl(options: UpdateUrl) => Promise
```
Set the update URL for the app dynamically at runtime.
This overrides the {@link PluginsConfig.CapacitorUpdater.updateUrl} config value. Requires {@link PluginsConfig.CapacitorUpdater.allowModifyUrl} to be set to `true`.
Use {@link PluginsConfig.CapacitorUpdater.persistModifyUrl} to persist this value across app restarts. Otherwise, the URL will reset to the config value on next app launch.
**Parameters**
| Name | Type | Description |
| --------- | ----------- | ------------------------------------------------- |
| `options` | `UpdateUrl` | Contains the URL to use for checking for updates. |
**Returns**
`Promise` â Resolves when the URL is successfully updated.
**Since:** 5.4.0
**Throws:** {Error} If `allowModifyUrl` is false or if the operation fails.
***
### setStatsUrl
[Section titled âsetStatsUrlâ](#setstatsurl)
```typescript
setStatsUrl(options: StatsUrl) => Promise
```
Set the statistics URL for the app dynamically at runtime.
This overrides the {@link PluginsConfig.CapacitorUpdater.statsUrl} config value. Requires {@link PluginsConfig.CapacitorUpdater.allowModifyUrl} to be set to `true`.
Pass an empty string to disable statistics gathering entirely. Use {@link PluginsConfig.CapacitorUpdater.persistModifyUrl} to persist this value across app restarts.
**Parameters**
| Name | Type | Description |
| --------- | ---------- | ------------------------------------------------------------------------------ |
| `options` | `StatsUrl` | Contains the URL to use for sending statistics, or an empty string to disable. |
**Returns**
`Promise` â Resolves when the URL is successfully updated.
**Since:** 5.4.0
**Throws:** {Error} If `allowModifyUrl` is false or if the operation fails.
***
### setChannelUrl
[Section titled âsetChannelUrlâ](#setchannelurl)
```typescript
setChannelUrl(options: ChannelUrl) => Promise
```
Set the channel URL for the app dynamically at runtime.
This overrides the {@link PluginsConfig.CapacitorUpdater.channelUrl} config value. Requires {@link PluginsConfig.CapacitorUpdater.allowModifyUrl} to be set to `true`.
Use {@link PluginsConfig.CapacitorUpdater.persistModifyUrl} to persist this value across app restarts. Otherwise, the URL will reset to the config value on next app launch.
**Parameters**
| Name | Type | Description |
| --------- | ------------ | ----------------------------------------------- |
| `options` | `ChannelUrl` | Contains the URL to use for channel operations. |
**Returns**
`Promise` â Resolves when the URL is successfully updated.
**Since:** 5.4.0
**Throws:** {Error} If `allowModifyUrl` is false or if the operation fails.
***
### download
[Section titled âdownloadâ](#download)
```typescript
download(options: DownloadOptions) => Promise
```
Download a new bundle from the provided URL for later installation.
The downloaded bundle is stored locally but not activated. To use it:
* Call {@link next} to set it for installation on next app backgrounding/restart
* Call {@link set} to activate it immediately (destroys current JavaScript context)
The URL should point to a zip file containing either:
* Your app files directly in the zip root, or
* A single folder containing all your app files
The bundle must include an `index.html` file at the root level.
For encrypted bundles, provide the `sessionKey` and `checksum` parameters. For multi-file delta updates, provide the `manifest` array.
**Parameters**
| Name | Type | Description |
| --------- | ----------------- | ------------------------------------------------------------- |
| `options` | `DownloadOptions` | The {@link DownloadOptions} for downloading a new bundle zip. |
**Returns**
`Promise` â The {@link BundleInfo} for the downloaded bundle.
**Throws:** {Error} If the download fails or the bundle is invalid.
**Example**
```ts
const bundle = await CapacitorUpdater.download({
url: `https://example.com/versions/${version}/dist.zip`,
version: version
});
// Bundle is downloaded but not active yet
await CapacitorUpdater.next({ id: bundle.id }); // Will activate on next background
```
***
### next
[Section titled ânextâ](#next)
```typescript
next(options: BundleId) => Promise
```
Set the next bundle to be activated when the app backgrounds or restarts.
This is the recommended way to apply updates as it doesnât interrupt the userâs current session. The bundle will be activated when:
* The app is backgrounded (user switches away), or
* The app is killed and relaunched, or
* {@link reload} is called manually
Unlike {@link set}, this method does NOT destroy the current JavaScript context immediately. Your app continues running normally until one of the above events occurs.
Use {@link setMultiDelay} to add additional conditions before the update is applied.
**Parameters**
| Name | Type | Description |
| --------- | ---------- | ------------------------------------------------------------------------------------------------- |
| `options` | `BundleId` | Contains the ID of the bundle to set as next. Use {@link BundleInfo.id} from a downloaded bundle. |
**Returns**
`Promise` â The {@link BundleInfo} for the specified bundle.
**Throws:** {Error} When there is no index.html file inside the bundle folder or the bundle doesnât exist.
***
### set
[Section titled âsetâ](#set)
```typescript
set(options: BundleId) => Promise
```
Set the current bundle and immediately reloads the app.
**IMPORTANT: This is a terminal operation that destroys the current JavaScript context.**
When you call this method:
* The entire JavaScript context is immediately destroyed
* The app reloads from a different folder with different files
* NO code after this call will execute
* NO promises will resolve
* NO callbacks will fire
* Event listeners registered after this call are unreliable and may never fire
The reload happens automatically - you donât need to do anything else. If you need to preserve state like the current URL path, use the {@link PluginsConfig.CapacitorUpdater.keepUrlPathAfterReload} config option. For other state preservation needs, save your data before calling this method (e.g., to localStorage).
**Do not** try to execute additional logic after calling `set()` - it wonât work as expected.
**Parameters**
| Name | Type | Description |
| --------- | ---------- | ------------------------------------------------------------------------- |
| `options` | `BundleId` | A {@link BundleId} object containing the new bundle id to set as current. |
**Returns**
`Promise` â A promise that will never resolve because the JavaScript context is destroyed.
**Throws:** {Error} When there is no index.html file inside the bundle folder.
***
### delete
[Section titled âdeleteâ](#delete)
```typescript
delete(options: BundleId) => Promise
```
Delete a bundle from local storage to free up disk space.
You cannot delete:
* The currently active bundle
* The `builtin` bundle (the version shipped with your app)
* The bundle set as `next` (call {@link next} with a different bundle first)
Use {@link list} to get all available bundle IDs.
**Note:** The bundle ID is NOT the same as the version name. Use the `id` field from {@link BundleInfo}, not the `version` field.
**Parameters**
| Name | Type | Description |
| --------- | ---------- | ------------------------------------------------------------- |
| `options` | `BundleId` | A {@link BundleId} object containing the bundle ID to delete. |
**Returns**
`Promise` â Resolves when the bundle is successfully deleted.
**Throws:** {Error} If the bundle is currently in use or doesnât exist.
***
### setBundleError
[Section titled âsetBundleErrorâ](#setbundleerror)
```typescript
setBundleError(options: BundleId) => Promise
```
Manually mark a bundle as failed/errored in manual update mode.
This is useful when you detect that a bundle has critical issues and want to prevent it from being used again. The bundle status will be changed to `error` and the plugin will avoid using this bundle in the future.
**Requirements:**
* {@link PluginsConfig.CapacitorUpdater.allowManualBundleError} must be set to `true`
* Only works in manual update mode (when autoUpdate is disabled)
Common use case: After downloading and testing a bundle, you discover it has critical bugs and want to mark it as failed so it wonât be retried.
**Parameters**
| Name | Type | Description |
| --------- | ---------- | ---------------------------------------------------------------------- |
| `options` | `BundleId` | A {@link BundleId} object containing the bundle ID to mark as errored. |
**Returns**
`Promise` â The updated {@link BundleInfo} with status set to `error`.
**Since:** 7.20.0
**Throws:** {Error} When the bundle does not exist or `allowManualBundleError` is false.
***
### list
[Section titled âlistâ](#list)
```typescript
list(options?: ListOptions | undefined) => Promise
```
Get all locally downloaded bundles stored in your app.
This returns all bundles that have been downloaded and are available locally, including:
* The currently active bundle
* The `builtin` bundle (shipped with your app)
* Any downloaded bundles waiting to be activated
* Failed bundles (with `error` status)
Use this to:
* Check available disk space by counting bundles
* Delete old bundles with {@link delete}
* Monitor bundle download status
**Parameters**
| Name | Type | Description |
| --------- | ------------- | ----------- |
| `options` | \`ListOptions | undefined\` |
**Returns**
`Promise` â A promise containing the array of {@link BundleInfo} objects.
**Throws:** {Error} If the operation fails.
***
### reset
[Section titled âresetâ](#reset)
```typescript
reset(options?: ResetOptions | undefined) => Promise
```
Reset the app to a known good bundle.
This method helps recover from problematic updates by reverting to either:
* The `builtin` bundle (the original version shipped with your app to App Store/Play Store)
* The last successfully loaded bundle (most recent bundle that worked correctly)
**IMPORTANT: This triggers an immediate app reload, destroying the current JavaScript context.** See {@link set} for details on the implications of this operation.
Use cases:
* Emergency recovery when an update causes critical issues
* Testing rollback functionality
* Providing users a âreset to factoryâ option
**Parameters**
| Name | Type | Description |
| --------- | -------------- | ----------- |
| `options` | \`ResetOptions | undefined\` |
**Returns**
`Promise` â A promise that may never resolve because the app will be reloaded.
**Throws:** {Error} If the reset operation fails.
***
### current
[Section titled âcurrentâ](#current)
```typescript
current() => Promise
```
Get information about the currently active bundle.
Returns:
* `bundle`: The currently active bundle information
* `native`: The version of the builtin bundle (the original app version from App/Play Store)
If no updates have been applied, `bundle.id` will be `"builtin"`, indicating the app is running the original version shipped with the native app.
Use this to:
* Display the current version to users
* Check if an update is currently active
* Compare against available updates
* Log the active bundle for debugging
**Returns**
`Promise` â A promise with the current bundle and native version info.
**Throws:** {Error} If the operation fails.
***
### reload
[Section titled âreloadâ](#reload)
```typescript
reload() => Promise
```
Manually reload the app to apply a pending update.
This triggers the same reload behavior that happens automatically when the app backgrounds. If youâve called {@link next} to queue an update, calling `reload()` will apply it immediately.
**IMPORTANT: This destroys the current JavaScript context immediately.** See {@link set} for details on the implications of this operation.
Common use cases:
* Applying an update immediately after download instead of waiting for backgrounding
* Providing a âRestart nowâ button to users after an update is ready
* Testing update flows during development
If no update is pending (no call to {@link next}), this simply reloads the current bundle.
**Returns**
`Promise` â A promise that may never resolve because the app will be reloaded.
**Throws:** {Error} If the reload operation fails.
***
### setMultiDelay
[Section titled âsetMultiDelayâ](#setmultidelay)
```typescript
setMultiDelay(options: MultiDelayConditions) => Promise
```
Configure conditions that must be met before a pending update is applied.
After calling {@link next} to queue an update, use this method to control when it gets applied. The update will only be installed after ALL specified conditions are satisfied.
Available condition types:
* `background`: Wait for the app to be backgrounded. Optionally specify duration in milliseconds.
* `kill`: Wait for the app to be killed and relaunched (**Note:** Current behavior triggers update immediately on kill, not on next background. This will be fixed in v8.)
* `date`: Wait until a specific date/time (ISO 8601 format)
* `nativeVersion`: Wait until the native app is updated to a specific version
Condition value formats:
* `background`: Number in milliseconds (e.g., `"300000"` for 5 minutes), or omit for immediate
* `kill`: No value needed
* `date`: ISO 8601 date string (e.g., `"2025-12-31T23:59:59Z"`)
* `nativeVersion`: Version string (e.g., `"2.0.0"`)
**Parameters**
| Name | Type | Description |
| --------- | ---------------------- | -------------------------------------------------------------- |
| `options` | `MultiDelayConditions` | Contains the {@link MultiDelayConditions} array of conditions. |
**Returns**
`Promise` â Resolves when the delay conditions are set.
**Since:** 4.3.0
**Throws:** {Error} If the operation fails or conditions are invalid.
**Example**
```ts
// Update after user kills app OR after 5 minutes in background
await CapacitorUpdater.setMultiDelay({
delayConditions: [
{ kind: 'kill' },
{ kind: 'background', value: '300000' }
]
});
```
**Example**
```ts
// Update after a specific date
await CapacitorUpdater.setMultiDelay({
delayConditions: [{ kind: 'date', value: '2025-12-31T23:59:59Z' }]
});
```
**Example**
```ts
// Default behavior: update on next background
await CapacitorUpdater.setMultiDelay({
delayConditions: [{ kind: 'background' }]
});
```
***
### cancelDelay
[Section titled âcancelDelayâ](#canceldelay)
```typescript
cancelDelay() => Promise
```
Cancel all delay conditions and apply the pending update immediately.
If youâve set delay conditions with {@link setMultiDelay}, this method clears them and triggers the pending update to be applied on the next app background or restart.
This is useful when:
* User manually requests to update now (e.g., clicks âUpdate nowâ button)
* Your app detects itâs a good time to update (e.g., user finished critical task)
* You want to override a time-based delay early
**Returns**
`Promise` â Resolves when the delay conditions are cleared.
**Since:** 4.0.0
**Throws:** {Error} If the operation fails.
***
### getLatest
[Section titled âgetLatestâ](#getlatest)
```typescript
getLatest(options?: GetLatestOptions | undefined) => Promise
```
Check the update server for the latest available bundle version.
This queries your configured update URL (or Capgo backend) to see if a newer bundle is available for download. It does NOT download the bundle automatically.
The response includes:
* `version`: The latest available version identifier
* `url`: Download URL for the bundle (if available)
* `breaking`: Whether this update is marked as incompatible (requires native app update)
* `message`: Optional message from the server
* `manifest`: File list for delta updates (if using multi-file downloads)
After receiving the latest version info, you can:
1. Compare it with your current version
2. Download it using {@link download}
3. Apply it using {@link next} or {@link set}
**Important: Error handling for âno new version availableâ**
When the deviceâs current version matches the latest version on the server (i.e., the device is already up-to-date), the server returns a 200 response with `error: "no_new_version_available"` and `message: "No new version available"`. **This causes `getLatest()` to throw an error**, even though this is a normal, expected condition.
You should catch this specific error to handle it gracefully:
```typescript
try {
const latest = await CapacitorUpdater.getLatest();
// New version is available, proceed with download
} catch (error) {
if (error.message === 'No new version available') {
// Device is already on the latest version - this is normal
console.log('Already up to date');
} else {
// Actual error occurred
console.error('Failed to check for updates:', error);
}
}
```
In this scenario, the server:
* Logs the request with a âNo new version availableâ message
* Sends a ânoNewâ stat action to track that the device checked for updates but was already current (done on the backend)
**Parameters**
| Name | Type | Description |
| --------- | ------------------ | ----------- |
| `options` | \`GetLatestOptions | undefined\` |
**Returns**
`Promise` â Information about the latest available bundle version.
**Since:** 4.0.0
**Throws:** {Error} Always throws when no new version is available (`error: "no_new_version_available"`), or when the request fails.
***
### setChannel
[Section titled âsetChannelâ](#setchannel)
```typescript
setChannel(options: SetChannelOptions) => Promise
```
Assign this device to a specific update channel at runtime.
Channels allow you to distribute different bundle versions to different groups of users (e.g., âproductionâ, âbetaâ, âstagingâ). This method switches the device to a new channel.
**Requirements:**
* The target channel must allow self-assignment (configured in your Capgo dashboard or backend)
* The backend may accept or reject the request based on channel settings
**When to use:**
* After the app is ready and the user has interacted (e.g., opted into beta program)
* To implement in-app channel switching (beta toggle, tester access, etc.)
* For user-driven channel changes
**When NOT to use:**
* At app boot/initialization - use {@link PluginsConfig.CapacitorUpdater.defaultChannel} config instead
* Before user interaction
**Important: Listen for the `channelPrivate` event**
When a user attempts to set a channel that doesnât allow device self-assignment, the method will throw an error AND fire a {@link addListener}(âchannelPrivateâ) event. You should listen to this event to provide appropriate feedback to users:
```typescript
CapacitorUpdater.addListener('channelPrivate', (data) => {
console.warn(`Cannot access channel "${data.channel}": ${data.message}`);
// Show user-friendly message
});
```
This sends a request to the Capgo backend linking your device ID to the specified channel.
**Parameters**
| Name | Type | Description |
| --------- | ------------------- | ------------------------------------------------------------------------------------------- |
| `options` | `SetChannelOptions` | The {@link SetChannelOptions} containing the channel name and optional auto-update trigger. |
**Returns**
`Promise` â Channel operation result with status and optional error/message.
**Since:** 4.7.0
**Throws:** {Error} If the channel doesnât exist or doesnât allow self-assignment.
***
### unsetChannel
[Section titled âunsetChannelâ](#unsetchannel)
```typescript
unsetChannel(options: UnsetChannelOptions) => Promise
```
Remove the deviceâs channel assignment and return to the default channel.
This unlinks the device from any specifically assigned channel, causing it to fall back to:
* The {@link PluginsConfig.CapacitorUpdater.defaultChannel} if configured, or
* Your backendâs default channel for this app
Use this when:
* Users opt out of beta/testing programs
* You want to reset a device to standard update distribution
* Testing channel switching behavior
**Parameters**
| Name | Type | Description |
| --------- | --------------------- | ----------- |
| `options` | `UnsetChannelOptions` | |
**Returns**
`Promise` â Resolves when the channel is successfully unset.
**Since:** 4.7.0
**Throws:** {Error} If the operation fails.
***
### getChannel
[Section titled âgetChannelâ](#getchannel)
```typescript
getChannel() => Promise
```
Get the current channel assigned to this device.
Returns information about:
* `channel`: The currently assigned channel name (if any)
* `allowSet`: Whether the channel allows self-assignment
* `status`: Operation status
* `error`/`message`: Additional information (if applicable)
Use this to:
* Display current channel to users (e.g., âYouâre on the Beta channelâ)
* Check if a device is on a specific channel before showing features
* Verify channel assignment after calling {@link setChannel}
**Returns**
`Promise` â The current channel information.
**Since:** 4.8.0
**Throws:** {Error} If the operation fails.
***
### listChannels
[Section titled âlistChannelsâ](#listchannels)
```typescript
listChannels() => Promise
```
Get a list of all channels available for this device to self-assign to.
Only returns channels where `allow_self_set` is `true`. These are channels that users can switch to using {@link setChannel} without backend administrator intervention.
Each channel includes:
* `id`: Unique channel identifier
* `name`: Human-readable channel name
* `public`: Whether the channel is publicly visible
* `allow_self_set`: Always `true` in results (filtered to only self-assignable channels)
Use this to:
* Build a channel selector UI for users (e.g., âJoin Betaâ button)
* Show available testing/preview channels
* Implement channel discovery features
**Returns**
`Promise` â List of channels the device can self-assign to.
**Since:** 7.5.0
**Throws:** {Error} If the operation fails or the request to the backend fails.
***
### setCustomId
[Section titled âsetCustomIdâ](#setcustomid)
```typescript
setCustomId(options: SetCustomIdOptions) => Promise
```
Set a custom identifier for this device.
This allows you to identify devices by your own custom ID (user ID, account ID, etc.) instead of or in addition to the deviceâs unique hardware ID. The custom ID is sent to your update server and can be used for:
* Targeting specific users for updates
* Analytics and user tracking
* Debugging and support (correlating devices with users)
* A/B testing or feature flagging
**Persistence:**
* When {@link PluginsConfig.CapacitorUpdater.persistCustomId} is `true`, the ID persists across app restarts
* When `false`, the ID is only kept for the current session
**Clearing the custom ID:**
* Pass an empty string `""` to remove any stored custom ID
**Parameters**
| Name | Type | Description |
| --------- | -------------------- | ----------------------------------------------------------------------- |
| `options` | `SetCustomIdOptions` | The {@link SetCustomIdOptions} containing the custom identifier string. |
**Returns**
`Promise` â Resolves immediately (synchronous operation).
**Since:** 4.9.0
**Throws:** {Error} If the operation fails.
***
### getBuiltinVersion
[Section titled âgetBuiltinVersionâ](#getbuiltinversion)
```typescript
getBuiltinVersion() => Promise
```
Get the builtin bundle version (the original version shipped with your native app).
This returns the version of the bundle that was included when the app was installed from the App Store or Play Store. This is NOT the currently active bundle version - use {@link current} for that.
Returns:
* The {@link PluginsConfig.CapacitorUpdater.version} config value if set, or
* The native app version from platform configs (package.json, Info.plist, build.gradle)
Use this to:
* Display the âfactoryâ version to users
* Compare against downloaded bundle versions
* Determine if any updates have been applied
* Debugging version mismatches
**Returns**
`Promise` â The builtin bundle version string.
**Since:** 5.2.0
***
### getDeviceId
[Section titled âgetDeviceIdâ](#getdeviceid)
```typescript
getDeviceId() => Promise
```
Get the unique, privacy-friendly identifier for this device.
This ID is used to identify the device when communicating with update servers. Itâs automatically generated and stored securely by the plugin.
**Privacy & Security characteristics:**
* Generated as a UUID (not based on hardware identifiers)
* Stored securely in platform-specific secure storage
* Android: Android Keystore (persists across app reinstalls on API 23+)
* iOS: Keychain with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`
* Not synced to cloud (iOS)
* Follows Apple and Google privacy best practices
* Users can clear it via system settings (Android) or keychain access (iOS)
**Persistence:** The device ID persists across app reinstalls to maintain consistent device identity for update tracking and analytics.
Use this to:
* Debug update delivery issues (check what ID the server sees)
* Implement device-specific features
* Correlate server logs with specific devices
**Returns**
`Promise` â The unique device identifier string.
**Throws:** {Error} If the operation fails.
***
### getPluginVersion
[Section titled âgetPluginVersionâ](#getpluginversion)
```typescript
getPluginVersion() => Promise
```
Get the version of the Capacitor Updater plugin installed in your app.
This returns the version of the native plugin code (Android/iOS), which is sent to the update server with each request. This is NOT your app version or bundle version.
Use this to:
* Debug plugin-specific issues (when reporting bugs)
* Verify plugin installation and version
* Check compatibility with backend features
* Display in debug/about screens
**Returns**
`Promise` â The Capacitor Updater plugin version string.
**Throws:** {Error} If the operation fails.
***
### isAutoUpdateEnabled
[Section titled âisAutoUpdateEnabledâ](#isautoupdateenabled)
```typescript
isAutoUpdateEnabled() => Promise
```
Check if automatic updates are currently enabled.
Returns `true` if {@link PluginsConfig.CapacitorUpdater.autoUpdate} is enabled, meaning the plugin will automatically check for, download, and apply updates.
Returns `false` if in manual mode, where you control the update flow using {@link getLatest}, {@link download}, {@link next}, and {@link set}.
Use this to:
* Determine which update flow your app is using
* Show/hide manual update UI based on mode
* Debug update behavior
**Returns**
`Promise` â `true` if auto-update is enabled, `false` if in manual mode.
**Throws:** {Error} If the operation fails.
***
### removeAllListeners
[Section titled âremoveAllListenersâ](#removealllisteners)
```typescript
removeAllListeners() => Promise
```
Remove all event listeners registered for this plugin.
This unregisters all listeners added via {@link addListener} for all event types:
* `download`
* `noNeedUpdate`
* `updateAvailable`
* `downloadComplete`
* `downloadFailed`
* `breakingAvailable` / `majorAvailable`
* `updateFailed`
* `appReloaded`
* `appReady`
Use this during cleanup (e.g., when unmounting components or closing screens) to prevent memory leaks from lingering event listeners.
**Returns**
`Promise` â Resolves when all listeners are removed.
**Since:** 1.0.0
***
### addListener(âdownloadâ)
[Section titled âaddListener(âdownloadâ)â](#addlistenerdownload)
```typescript
addListener(eventName: 'download', listenerFunc: (state: DownloadEvent) => void) => Promise
```
Listen for bundle download event in the App. Fires once a download has started, during downloading and when finished. This will return you all download percent during the download
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------- | ----------- |
| `eventName` | `'download'` | |
| `listenerFunc` | `(state: DownloadEvent) => void` | |
**Returns**
`Promise`
**Since:** 2.0.11
***
### addListener(ânoNeedUpdateâ)
[Section titled âaddListener(ânoNeedUpdateâ)â](#addlistenernoneedupdate)
```typescript
addListener(eventName: 'noNeedUpdate', listenerFunc: (state: NoNeedEvent) => void) => Promise
```
Listen for no need to update event, useful when you want force check every time the app is launched
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------ | ----------- |
| `eventName` | `'noNeedUpdate'` | |
| `listenerFunc` | `(state: NoNeedEvent) => void` | |
**Returns**
`Promise`
**Since:** 4.0.0
***
### addListener(âupdateAvailableâ)
[Section titled âaddListener(âupdateAvailableâ)â](#addlistenerupdateavailable)
```typescript
addListener(eventName: 'updateAvailable', listenerFunc: (state: UpdateAvailableEvent) => void) => Promise
```
Listen for available update event, useful when you want to force check every time the app is launched
**Parameters**
| Name | Type | Description |
| -------------- | --------------------------------------- | ----------- |
| `eventName` | `'updateAvailable'` | |
| `listenerFunc` | `(state: UpdateAvailableEvent) => void` | |
**Returns**
`Promise`
**Since:** 4.0.0
***
### addListener(âdownloadCompleteâ)
[Section titled âaddListener(âdownloadCompleteâ)â](#addlistenerdownloadcomplete)
```typescript
addListener(eventName: 'downloadComplete', listenerFunc: (state: DownloadCompleteEvent) => void) => Promise
```
Listen for downloadComplete events.
**Parameters**
| Name | Type | Description |
| -------------- | ---------------------------------------- | ----------- |
| `eventName` | `'downloadComplete'` | |
| `listenerFunc` | `(state: DownloadCompleteEvent) => void` | |
**Returns**
`Promise`
**Since:** 4.0.0
***
### addListener(âbreakingAvailableâ)
[Section titled âaddListener(âbreakingAvailableâ)â](#addlistenerbreakingavailable)
```typescript
addListener(eventName: 'breakingAvailable', listenerFunc: (state: BreakingAvailableEvent) => void) => Promise
```
Listen for breaking update events when the backend flags an update as incompatible with the current app. Emits the same payload as the legacy `majorAvailable` listener.
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------------- | ----------- |
| `eventName` | `'breakingAvailable'` | |
| `listenerFunc` | `(state: MajorAvailableEvent) => void` | |
**Returns**
`Promise`
**Since:** 7.22.0
***
### addListener(âmajorAvailableâ)
[Section titled âaddListener(âmajorAvailableâ)â](#addlistenermajoravailable)
```typescript
addListener(eventName: 'majorAvailable', listenerFunc: (state: MajorAvailableEvent) => void) => Promise
```
Listen for Major update event in the App, let you know when major update is blocked by setting disableAutoUpdateBreaking
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------------- | ----------- |
| `eventName` | `'majorAvailable'` | |
| `listenerFunc` | `(state: MajorAvailableEvent) => void` | |
**Returns**
`Promise`
**Since:** 2.3.0
***
### addListener(âupdateFailedâ)
[Section titled âaddListener(âupdateFailedâ)â](#addlistenerupdatefailed)
```typescript
addListener(eventName: 'updateFailed', listenerFunc: (state: UpdateFailedEvent) => void) => Promise
```
Listen for update fail event in the App, let you know when update has fail to install at next app start
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------------ | ----------- |
| `eventName` | `'updateFailed'` | |
| `listenerFunc` | `(state: UpdateFailedEvent) => void` | |
**Returns**
`Promise`
**Since:** 2.3.0
***
### addListener(âsetâ)
[Section titled âaddListener(âsetâ)â](#addlistenerset)
```typescript
addListener(eventName: 'set', listenerFunc: (state: SetEvent) => void) => Promise
```
Listen for set event in the App, let you know when a bundle has been applied successfully. This event is retained natively until JavaScript consumes it, so if the app reloads before your listener is attached, the last pending `set` event is delivered once the listener subscribes.
**Parameters**
| Name | Type | Description |
| -------------- | --------------------------- | ----------- |
| `eventName` | `'set'` | |
| `listenerFunc` | `(state: SetEvent) => void` | |
**Returns**
`Promise`
**Since:** 8.43.12
***
### addListener(âsetNextâ)
[Section titled âaddListener(âsetNextâ)â](#addlistenersetnext)
```typescript
addListener(eventName: 'setNext', listenerFunc: (state: SetNextEvent) => void) => Promise
```
Listen for set next event in the App, let you know when a bundle is queued as the next bundle to install.
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------- | ----------- |
| `eventName` | `'setNext'` | |
| `listenerFunc` | `(state: SetNextEvent) => void` | |
**Returns**
`Promise`
**Since:** 6.14.0
***
### addListener(âdownloadFailedâ)
[Section titled âaddListener(âdownloadFailedâ)â](#addlistenerdownloadfailed)
```typescript
addListener(eventName: 'downloadFailed', listenerFunc: (state: DownloadFailedEvent) => void) => Promise
```
Listen for download fail event in the App, let you know when a bundle download has failed
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------------- | ----------- |
| `eventName` | `'downloadFailed'` | |
| `listenerFunc` | `(state: DownloadFailedEvent) => void` | |
**Returns**
`Promise`
**Since:** 4.0.0
***
### addListener(âappReloadedâ)
[Section titled âaddListener(âappReloadedâ)â](#addlistenerappreloaded)
```typescript
addListener(eventName: 'appReloaded', listenerFunc: () => void) => Promise
```
Listen for reload event in the App, let you know when reload has happened
**Parameters**
| Name | Type | Description |
| -------------- | --------------- | ----------- |
| `eventName` | `'appReloaded'` | |
| `listenerFunc` | `() => void` | |
**Returns**
`Promise`
**Since:** 4.3.0
***
### addListener(âappReadyâ)
[Section titled âaddListener(âappReadyâ)â](#addlistenerappready)
```typescript
addListener(eventName: 'appReady', listenerFunc: (state: AppReadyEvent) => void) => Promise
```
Listen for app ready event in the App, let you know when app is ready to use. This event is retained natively until JavaScript consumes it, so it can still be delivered after a reload even if the listener is attached later in app startup.
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------- | ----------- |
| `eventName` | `'appReady'` | |
| `listenerFunc` | `(state: AppReadyEvent) => void` | |
**Returns**
`Promise`
**Since:** 5.1.0
***
### addListener(âchannelPrivateâ)
[Section titled âaddListener(âchannelPrivateâ)â](#addlistenerchannelprivate)
```typescript
addListener(eventName: 'channelPrivate', listenerFunc: (state: ChannelPrivateEvent) => void) => Promise
```
Listen for channel private event, fired when attempting to set a channel that doesnât allow device self-assignment.
This event is useful for:
* Informing users they donât have permission to switch to a specific channel
* Implementing custom error handling for channel restrictions
* Logging unauthorized channel access attempts
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------------- | ----------- |
| `eventName` | `'channelPrivate'` | |
| `listenerFunc` | `(state: ChannelPrivateEvent) => void` | |
**Returns**
`Promise`
**Since:** 7.34.0
***
### addListener(âonFlexibleUpdateStateChangeâ)
[Section titled âaddListener(âonFlexibleUpdateStateChangeâ)â](#addlisteneronflexibleupdatestatechange)
```typescript
addListener(eventName: 'onFlexibleUpdateStateChange', listenerFunc: (state: FlexibleUpdateState) => void) => Promise
```
Listen for flexible update state changes on Android.
This event fires during the flexible update download process, providing:
* Download progress (bytes downloaded / total bytes)
* Installation status changes
**Install status values:**
* `UNKNOWN` (0): Unknown status
* `PENDING` (1): Download pending
* `DOWNLOADING` (2): Download in progress
* `INSTALLING` (3): Installing the update
* `INSTALLED` (4): Update installed (app restart needed)
* `FAILED` (5): Update failed
* `CANCELED` (6): Update was canceled
* `DOWNLOADED` (11): Download complete, ready to install
When status is `DOWNLOADED`, you should prompt the user and call {@link completeFlexibleUpdate} to finish the installation.
**Parameters**
| Name | Type | Description |
| -------------- | -------------------------------------- | ----------- |
| `eventName` | `'onFlexibleUpdateStateChange'` | |
| `listenerFunc` | `(state: FlexibleUpdateState) => void` | |
**Returns**
`Promise`
**Since:** 8.0.0
***
### isAutoUpdateAvailable
[Section titled âisAutoUpdateAvailableâ](#isautoupdateavailable)
```typescript
isAutoUpdateAvailable() => Promise
```
Check if the auto-update feature is available (not disabled by custom server configuration).
Returns `false` when a custom `updateUrl` is configured, as this typically indicates youâre using a self-hosted update server that may not support all auto-update features.
Returns `true` when using the default Capgo backend or when the feature is available.
This is different from {@link isAutoUpdateEnabled}:
* `isAutoUpdateEnabled()`: Checks if auto-update MODE is turned on/off
* `isAutoUpdateAvailable()`: Checks if auto-update is SUPPORTED with your current configuration
**Returns**
`Promise` â `false` when custom updateUrl is set, `true` otherwise.
**Throws:** {Error} If the operation fails.
***
### getNextBundle
[Section titled âgetNextBundleâ](#getnextbundle)
```typescript
getNextBundle() => Promise
```
Get information about the bundle queued to be activated on next reload.
Returns:
* {@link BundleInfo} object if a bundle has been queued via {@link next}
* `null` if no update is pending
This is useful to:
* Check if an update is waiting to be applied
* Display âUpdate pendingâ status to users
* Show version info of the queued update
* Decide whether to show a âRestart to updateâ prompt
The queued bundle will be activated when:
* The app is backgrounded (default behavior)
* The app is killed and restarted
* {@link reload} is called manually
* Delay conditions set by {@link setMultiDelay} are met
**Returns**
`Promise` â The pending bundle info, or `null` if none is queued.
**Since:** 6.8.0
**Throws:** {Error} If the operation fails.
***
### getFailedUpdate
[Section titled âgetFailedUpdateâ](#getfailedupdate)
```typescript
getFailedUpdate() => Promise
```
Retrieve information about the most recent bundle that failed to load.
When a bundle fails to load (e.g., JavaScript errors prevent initialization, missing files), the plugin automatically rolls back and stores information about the failure. This method retrieves that failure information.
**IMPORTANT: The stored value is cleared after being retrieved once.** Calling this method multiple times will only return the failure info on the first call, then `null` on subsequent calls until another failure occurs.
Returns:
* {@link UpdateFailedEvent} with bundle info if a failure was recorded
* `null` if no failure has occurred or if it was already retrieved
Use this to:
* Show users why an update failed
* Log failure information for debugging
* Implement custom error handling/reporting
* Display rollback notifications
**Returns**
`Promise` â The failed update info (cleared after first retrieval), or `null`.
**Since:** 7.22.0
**Throws:** {Error} If the operation fails.
***
### setShakeMenu
[Section titled âsetShakeMenuâ](#setshakemenu)
```typescript
setShakeMenu(options: SetShakeMenuOptions) => Promise
```
Enable or disable the shake gesture menu for debugging and testing.
When enabled, users can shake their device to open a debug menu that shows:
* Current bundle information
* Available bundles
* Options to switch bundles manually
* Update status
This is useful during development and testing to:
* Quickly test different bundle versions
* Debug update flows
* Switch between production and test bundles
* Verify bundle installations
**Important:** Disable this in production builds or only enable for internal testers.
Can also be configured via {@link PluginsConfig.CapacitorUpdater.shakeMenu}.
**Parameters**
| Name | Type | Description |
| --------- | --------------------- | ----------- |
| `options` | `SetShakeMenuOptions` | |
**Returns**
`Promise` â Resolves when the setting is applied.
**Since:** 7.5.0
**Throws:** {Error} If the operation fails.
***
### isShakeMenuEnabled
[Section titled âisShakeMenuEnabledâ](#isshakemenuenabled)
```typescript
isShakeMenuEnabled() => Promise
```
Check if the shake gesture debug menu is currently enabled.
Returns the current state of the shake menu feature that can be toggled via {@link setShakeMenu} or configured via {@link PluginsConfig.CapacitorUpdater.shakeMenu}.
Use this to:
* Check if debug features are enabled
* Show/hide debug settings UI
* Verify configuration during testing
**Returns**
`Promise` â Object with `enabled: true` or `enabled: false`.
**Since:** 7.5.0
**Throws:** {Error} If the operation fails.
***
### setShakeChannelSelector
[Section titled âsetShakeChannelSelectorâ](#setshakechannelselector)
```typescript
setShakeChannelSelector(options: SetShakeChannelSelectorOptions) => Promise
```
Enable or disable the shake channel selector at runtime.
When enabled AND shakeMenu is true, shaking the device shows a channel selector instead of the debug menu. This allows users to switch between update channels by shaking their device.
After selecting a channel, the app automatically checks for updates and downloads if available.
Can also be configured via {@link PluginsConfig.CapacitorUpdater.allowShakeChannelSelector}.
**Parameters**
| Name | Type | Description |
| --------- | -------------------------------- | ----------- |
| `options` | `SetShakeChannelSelectorOptions` | |
**Returns**
`Promise` â Resolves when the setting is applied.
**Since:** 8.43.0
**Throws:** {Error} If the operation fails.
***
### isShakeChannelSelectorEnabled
[Section titled âisShakeChannelSelectorEnabledâ](#isshakechannelselectorenabled)
```typescript
isShakeChannelSelectorEnabled() => Promise
```
Check if the shake channel selector is currently enabled.
Returns the current state of the shake channel selector feature that can be toggled via {@link setShakeChannelSelector} or configured via {@link PluginsConfig.CapacitorUpdater.allowShakeChannelSelector}.
**Returns**
`Promise` â Object with `enabled: true` or `enabled: false`.
**Since:** 8.43.0
**Throws:** {Error} If the operation fails.
***
### getAppId
[Section titled âgetAppIdâ](#getappid)
```typescript
getAppId() => Promise
```
Get the currently configured App ID used for update server communication.
Returns the App ID that identifies this app to the update server. This can be:
* The value set via {@link setAppId}, or
* The {@link PluginsConfig.CapacitorUpdater.appId} config value, or
* The default app identifier from your native app configuration
Use this to:
* Verify which App ID is being used for updates
* Debug update delivery issues
* Display app configuration in debug screens
* Confirm App ID after calling {@link setAppId}
**Returns**
`Promise` â Object containing the current `appId` string.
**Since:** 7.14.0
**Throws:** {Error} If the operation fails.
***
### setAppId
[Section titled âsetAppIdâ](#setappid)
```typescript
setAppId(options: SetAppIdOptions) => Promise
```
Dynamically change the App ID used for update server communication.
This overrides the App ID used to identify your app to the update server, allowing you to switch between different app configurations at runtime (e.g., production vs staging app IDs, or multi-tenant configurations).
**Requirements:**
* {@link PluginsConfig.CapacitorUpdater.allowModifyAppId} must be set to `true`
**Important considerations:**
* Changing the App ID will affect which updates this device receives
* The new App ID must exist on your update server
* This is primarily for advanced use cases (multi-tenancy, environment switching)
* Most apps should use the config-based {@link PluginsConfig.CapacitorUpdater.appId} instead
**Parameters**
| Name | Type | Description |
| --------- | ----------------- | ----------- |
| `options` | `SetAppIdOptions` | |
**Returns**
`Promise` â Resolves when the App ID is successfully changed.
**Since:** 7.14.0
**Throws:** {Error} If `allowModifyAppId` is false or the operation fails.
***
### getAppUpdateInfo
[Section titled âgetAppUpdateInfoâ](#getappupdateinfo)
```typescript
getAppUpdateInfo(options?: GetAppUpdateInfoOptions | undefined) => Promise
```
Get information about the appâs availability in the App Store or Play Store.
This method checks the native app stores to see if a newer version of the app is available for download. This is different from Capgoâs OTA updates - this checks for native app updates that require going through the app stores.
**Platform differences:**
* **Android**: Uses Play Storeâs In-App Updates API for accurate update information
* **iOS**: Queries the App Store lookup API (requires country code for accurate results)
**Returns information about:**
* Current installed version
* Available version in the store (if any)
* Whether an update is available
* Update priority (Android only)
* Whether immediate/flexible updates are allowed (Android only)
Use this to:
* Check if users need to update from the app store
* Show âUpdate Availableâ prompts for native updates
* Implement version gating (require minimum native version)
* Combine with Capgo OTA updates for a complete update strategy
**Parameters**
| Name | Type | Description |
| --------- | ------------------------- | ----------- |
| `options` | \`GetAppUpdateInfoOptions | undefined\` |
**Returns**
`Promise` â Information about the current and available app versions.
**Since:** 8.0.0
**Throws:** {Error} If the operation fails or store information is unavailable.
***
### openAppStore
[Section titled âopenAppStoreâ](#openappstore)
```typescript
openAppStore(options?: OpenAppStoreOptions | undefined) => Promise
```
Open the appâs page in the App Store or Play Store.
This navigates the user to your appâs store listing where they can manually update the app. Use this as a fallback when in-app updates are not available or when the user needs to update on iOS.
**Platform behavior:**
* **Android**: Opens Play Store to the appâs page
* **iOS**: Opens App Store to the appâs page
**Customization options:**
* `appId`: Specify a custom App Store ID (iOS) - useful for opening a different appâs page
* `packageName`: Specify a custom package name (Android) - useful for opening a different appâs page
**Parameters**
| Name | Type | Description |
| --------- | --------------------- | ----------- |
| `options` | \`OpenAppStoreOptions | undefined\` |
**Returns**
`Promise` â Resolves when the store is opened.
**Since:** 8.0.0
**Throws:** {Error} If the store cannot be opened.
***
### performImmediateUpdate
[Section titled âperformImmediateUpdateâ](#performimmediateupdate)
```typescript
performImmediateUpdate() => Promise
```
Perform an immediate in-app update on Android.
This triggers Google Playâs immediate update flow, which:
1. Shows a full-screen update UI
2. Downloads and installs the update
3. Restarts the app automatically
The user cannot continue using the app until the update is complete. This is ideal for critical updates that must be installed immediately.
**Requirements:**
* Android only (throws error on iOS)
* An update must be available (check with {@link getAppUpdateInfo} first)
* The update must allow immediate updates (`immediateUpdateAllowed: true`)
**User experience:**
* Full-screen blocking UI
* Progress shown during download
* App automatically restarts after installation
**Returns**
`Promise` â Result indicating success, cancellation, or failure.
**Since:** 8.0.0
**Throws:** {Error} If not on Android, no update is available, or immediate updates not allowed.
***
### startFlexibleUpdate
[Section titled âstartFlexibleUpdateâ](#startflexibleupdate)
```typescript
startFlexibleUpdate() => Promise
```
Start a flexible in-app update on Android.
This triggers Google Playâs flexible update flow, which:
1. Downloads the update in the background
2. Allows the user to continue using the app
3. Notifies when download is complete
4. Requires calling {@link completeFlexibleUpdate} to install
Monitor the download progress using the `onFlexibleUpdateStateChange` listener.
**Requirements:**
* Android only (throws error on iOS)
* An update must be available (check with {@link getAppUpdateInfo} first)
* The update must allow flexible updates (`flexibleUpdateAllowed: true`)
**Typical flow:**
1. Call `startFlexibleUpdate()` to begin download
2. Listen to `onFlexibleUpdateStateChange` for progress
3. When status is `DOWNLOADED`, prompt user to restart
4. Call `completeFlexibleUpdate()` to install and restart
**Returns**
`Promise` â Result indicating the update was started, cancelled, or failed.
**Since:** 8.0.0
**Throws:** {Error} If not on Android, no update is available, or flexible updates not allowed.
***
### completeFlexibleUpdate
[Section titled âcompleteFlexibleUpdateâ](#completeflexibleupdate)
```typescript
completeFlexibleUpdate() => Promise
```
Complete a flexible in-app update on Android.
After a flexible update has been downloaded (status `DOWNLOADED` in `onFlexibleUpdateStateChange`), call this method to install the update and restart the app.
**Important:** This will immediately restart the app. Make sure to:
* Save any user data before calling
* Prompt the user before restarting
* Only call when the download status is `DOWNLOADED`
**Returns**
`Promise` â Resolves when the update installation begins (app will restart).
**Since:** 8.0.0
**Throws:** {Error} If not on Android or no downloaded update is pending.
***
# Capacitor Plugins by Capgo
> Explore our comprehensive collection of Capacitor plugins to extend your app's native capabilities with powerful features.
Welcome to the Capgo Capacitor Plugins collection. This landing page is generated from the live plugin registry plus the docs tree so newly documented plugins show up here automatically.
## Capgo Cloud - Live Updates
[Section titled âCapgo Cloud - Live Updatesâ](#capgo-cloud---live-updates)
[Capacitor Updater ](/docs/plugins/updater/)The core plugin powering Capgo Cloud. Deliver instant updates to your Capacitor apps without waiting for app store review.
The Updater plugin is the foundation of Capgo Cloud and lets you:
* Deploy JavaScript, HTML, CSS, and asset changes in minutes.
* Roll out updates to targeted user groups with channels.
* Monitor adoption and failure signals from the Capgo console.
* Secure releases with encryption and code signing.
## Plugin Directory
[Section titled âPlugin Directoryâ](#plugin-directory)
124 plugins currently resolve from the live Capgo registry. Dedicated docs open when available, and repository links remain visible for the rest.
[Accelerometer ](https://github.com/Cap-go/capacitor-accelerometer/)Read device accelerometer for motion detection and orientation tracking Opens the plugin repository until a dedicated docs page is available.
[AdMob ](https://github.com/Cap-go/capacitor-admob/)Monetize your app with Google AdMob banner, interstitial, and rewarded ads Opens the plugin repository until a dedicated docs page is available.
[Age Range ](https://github.com/Cap-go/capacitor-age-range/)Cross-platform age range detection using Google Play Age Signals (Android) and Apple DeclaredAgeRange (iOS) Opens the plugin repository until a dedicated docs page is available.
[Age Signals ](https://github.com/Cap-go/capacitor-android-age-signals/)Google Play Age Signals API wrapper - detect supervised accounts and verified users Opens the plugin repository until a dedicated docs page is available.
[Alarm ](https://github.com/Cap-go/capacitor-alarm/)Schedule native alarms and notifications even when app is closed Opens the plugin repository until a dedicated docs page is available.
[Android Inline Install ](https://github.com/Cap-go/capacitor-android-inline-install/)Install app updates directly within the app without leaving to Play Store Opens the plugin repository until a dedicated docs page is available.
[Android Kiosk ](https://github.com/Cap-go/capacitor-android-kiosk/)Lock Android devices into kiosk mode with launcher functionality and hardware key control Opens the plugin repository until a dedicated docs page is available.
[Android SMS Retriever ](https://github.com/Cap-go/capacitor-android-sms-retriever/)Read one app-targeted verification SMS without SMS permissions and request SIM phone number hints on Android Opens the plugin repository until a dedicated docs page is available.
[App Attest ](https://github.com/Cap-go/capacitor-app-attest/)Capacitor plugin for cross-platform device attestation using Apple App Attest and Google Play Integrity Standard Opens the plugin repository until a dedicated docs page is available.
[App Tracking Transparency ](https://github.com/Cap-go/capacitor-app-tracking-transparency/)Request and check iOS App Tracking Transparency permission for IDFA access Opens the plugin repository until a dedicated docs page is available.
[AppInsights ](https://github.com/Cap-go/capacitor-appinsights/)Track app usage, performance metrics, and user behavior with Apptopia AppInsights Opens the plugin repository until a dedicated docs page is available.
[AppsFlyer ](https://github.com/Cap-go/capacitor-appsflyer/)Add AppsFlyer attribution, analytics, deferred deep links, and OneLink support to your Capacitor app Opens the plugin repository until a dedicated docs page is available.
[Audio Recorder ](https://github.com/Cap-go/capacitor-audio-recorder/)Record audio on iOS, Android, and Web with simple controls and formats Opens the plugin repository until a dedicated docs page is available.
[Audio Session ](https://github.com/Cap-go/capacitor-audiosession/)Configure iOS audio session for background playback, mixing, and routing control Opens the plugin repository until a dedicated docs page is available.
[Autofill Save Password ](https://github.com/Cap-go/capacitor-autofill-save-password/)Prompt users to save passwords to device autofill for seamless login experience Opens the plugin repository until a dedicated docs page is available.
[Background Geolocation ](https://github.com/Cap-go/capacitor-background-geolocation/)Accurate background location tracking with native iOS and Android geofencing plus transition webhooks Opens the plugin repository until a dedicated docs page is available.
[Barometer ](https://github.com/Cap-go/capacitor-barometer/)Access device barometer for atmospheric pressure and altitude readings Opens the plugin repository until a dedicated docs page is available.
[Bluetooth Low Energy ](https://github.com/Cap-go/capacitor-bluetooth-low-energy/)Full-featured BLE plugin for scanning, connecting, reading, writing, and receiving notifications from Bluetooth devices Opens the plugin repository until a dedicated docs page is available.
[Brightness ](https://github.com/Cap-go/capacitor-brightness/)Control device screen brightness programmatically with support for app-specific and system-wide control Opens the plugin repository until a dedicated docs page is available.
[Camera Preview ](https://github.com/Cap-go/capacitor-camera-preview/)Display live camera feed as overlay with customizable controls and capture capabilities Opens the plugin repository until a dedicated docs page is available.
[Capacitor+ Core ](https://github.com/Cap-go/capacitor-plus/)Capacitor+ is an automated, always-synced fork of Capacitor with merged community PRs and rapid releases Opens the plugin repository until a dedicated docs page is available.
[Compass ](https://github.com/Cap-go/capacitor-compass/)Read device compass heading in degrees with continuous updates and permission handling Opens the plugin repository until a dedicated docs page is available.
[Contacts ](https://github.com/Cap-go/capacitor-contacts/)Access and manage device contacts with read and write capabilities Opens the plugin repository until a dedicated docs page is available.
[Contentsquare ](https://github.com/Cap-go/capacitor-contentsquare/)Integrate Contentsquare mobile analytics, consent gating, screen tracking, transactions, and session replay controls in Capacitor Opens the plugin repository until a dedicated docs page is available.
[Crisp ](https://github.com/Cap-go/capacitor-crisp/)Integrate Crisp live chat and customer support directly into your mobile app Opens the plugin repository until a dedicated docs page is available.
[Data Storage ](https://github.com/Cap-go/capacitor-data-storage-sqlite/)Store data locally using SQLite database with simple key-value API and encryption support Opens the plugin repository until a dedicated docs page is available.
[Document Scanner ](https://github.com/Cap-go/capacitor-document-scanner/)Scan documents with auto edge detection, perspective correction, and PDF export Opens the plugin repository until a dedicated docs page is available.
[Downloader ](https://github.com/Cap-go/capacitor-downloader/)Download large files in background with progress tracking and pause/resume support Opens the plugin repository until a dedicated docs page is available.
[Electron Updater ](https://github.com/Cap-go/electron-updater/)OTA live updates for Electron apps with the same API surface as capacitor-updater Opens the plugin repository until a dedicated docs page is available.
[Env ](https://github.com/Cap-go/capacitor-env/)Securely manage environment variables and configuration across different build environments Opens the plugin repository until a dedicated docs page is available.
[Facebook Analytics ](https://github.com/Cap-go/capacitor-facebook-analytics/)Meta/Facebook App Events analytics with standard events, purchase logging, currency parameters, and advertiser tracking controls Opens the plugin repository until a dedicated docs page is available.
[Fast SQL ](https://github.com/Cap-go/capacitor-fast-sql/)High-performance native SQLite with custom protocol for efficient sync operations and IndexedDB replacement Opens the plugin repository until a dedicated docs page is available.
[FFmpeg ](https://github.com/Cap-go/capacitor-ffmpeg/)Video encoding and processing powered by FFmpeg for compression and conversion Opens the plugin repository until a dedicated docs page is available.
[File ](https://github.com/Cap-go/capacitor-file/)Full-featured file system plugin for reading, writing, and managing files and directories Opens the plugin repository until a dedicated docs page is available.
[File Compressor ](https://github.com/Cap-go/capacitor-file-compressor/)Capacitor plugin for efficient image compression supporting PNG, JPEG, and WebP formats across iOS, Android, and Web platforms Opens the plugin repository until a dedicated docs page is available.
[File Picker ](https://github.com/Cap-go/capacitor-file-picker/)Pick files, images, videos, and directories with full native support for iOS and Android including HEIC conversion Opens the plugin repository until a dedicated docs page is available.
[File Sharer ](https://github.com/Cap-go/capacitor-file-sharer/)Share and save files from base64 data or local paths across Android, iOS, and Web Opens the plugin repository until a dedicated docs page is available.
[Firebase Analytics ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/analytics)Capacitor plugin for Firebase Analytics Opens the plugin repository until a dedicated docs page is available.
[Firebase App ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/app)Capacitor plugin for Firebase App Opens the plugin repository until a dedicated docs page is available.
[Firebase App Check ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/app-check)Capacitor plugin for Firebase App Check Opens the plugin repository until a dedicated docs page is available.
[Firebase Authentication ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/authentication)Capacitor plugin for Firebase Authentication Opens the plugin repository until a dedicated docs page is available.
[Firebase Crashlytics ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/crashlytics)Capacitor plugin for Firebase Crashlytics Opens the plugin repository until a dedicated docs page is available.
[Firebase Firestore ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/firestore)Capacitor plugin for Firebase Cloud Firestore Opens the plugin repository until a dedicated docs page is available.
[Firebase Functions ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/functions)Capacitor plugin for Firebase Cloud Functions Opens the plugin repository until a dedicated docs page is available.
[Firebase Messaging ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/messaging)Capacitor plugin for Firebase Cloud Messaging (FCM) Opens the plugin repository until a dedicated docs page is available.
[Firebase Performance ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/performance)Capacitor plugin for Firebase Performance Monitoring Opens the plugin repository until a dedicated docs page is available.
[Firebase Remote Config ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/remote-config)Capacitor plugin for Firebase Remote Config Opens the plugin repository until a dedicated docs page is available.
[Firebase Storage ](https://github.com/Cap-go/capacitor-firebase/tree/main/packages/storage)Capacitor plugin for Firebase Cloud Storage Opens the plugin repository until a dedicated docs page is available.
[Flash ](https://github.com/Cap-go/capacitor-flash/)Control device flashlight and torch with simple on/off toggle functionality Opens the plugin repository until a dedicated docs page is available.
[GTM ](https://github.com/Cap-go/capacitor-gtm/)Google Tag Manager integration for analytics and tracking Opens the plugin repository until a dedicated docs page is available.
[Health ](https://github.com/Cap-go/capacitor-health/)Access health and fitness data from native health platforms Opens the plugin repository until a dedicated docs page is available.
[iBeacon ](https://github.com/Cap-go/capacitor-ibeacon/)iBeacon plugin for Capacitor - proximity detection and beacon region monitoring Opens the plugin repository until a dedicated docs page is available.
[In App Browser ](https://github.com/Cap-go/capacitor-inappbrowser/)Open web pages in a customizable in-app browser without leaving your application Opens the plugin repository until a dedicated docs page is available.
[In App Review ](https://github.com/Cap-go/capacitor-in-app-review/)Prompt users to submit app store ratings and reviews without leaving your app using native iOS and Android APIs Opens the plugin repository until a dedicated docs page is available.
[Incoming Call Kit ](https://github.com/Cap-go/capacitor-incoming-call-kit/)Present native incoming-call UI with iOS CallKit and Android full-screen notifications Opens the plugin repository until a dedicated docs page is available.
[Indicator ](https://github.com/Cap-go/capacitor-home-indicator/)Hide or show iOS home indicator for fullscreen and immersive app experiences Opens the plugin repository until a dedicated docs page is available.
[Install Referrer ](https://github.com/Cap-go/capacitor-install-referrer/)Read Google Play install referrer data and Apple AdServices attribution from Capacitor Opens the plugin repository until a dedicated docs page is available.
[Intent Launcher ](https://github.com/Cap-go/capacitor-intent-launcher/)Launch Android intents, open system settings, and interact with other apps using the Intent system Opens the plugin repository until a dedicated docs page is available.
[Intercom ](https://github.com/Cap-go/capacitor-intercom/)Integrate Intercom live chat, help center, and support workflows in your Capacitor app Opens the plugin repository until a dedicated docs page is available.
[Intune ](https://github.com/Cap-go/capacitor-intune/)Microsoft Intune MAM, app protection policy, app config, and MSAL authentication for Capacitor Opens the plugin repository until a dedicated docs page is available.
[Is Root ](https://github.com/Cap-go/capacitor-is-root/)Detect rooted Android or jailbroken iOS devices to enhance app security Opens the plugin repository until a dedicated docs page is available.
[IVS Player ](https://github.com/Cap-go/capacitor-ivs-player/)Stream ultra-low latency live video using Amazon Interactive Video Service (IVS) Opens the plugin repository until a dedicated docs page is available.
[JW Player ](https://github.com/Cap-go/capacitor-jw-player/)Embed JW Player for professional video streaming with ads and analytics support Opens the plugin repository until a dedicated docs page is available.
[Keep Awake ](https://github.com/Cap-go/capacitor-keep-awake/)Prevent device screen from dimming or sleeping for video players, navigation, and presentations Opens the plugin repository until a dedicated docs page is available.
[Launch Navigator ](https://github.com/Cap-go/capacitor-launch-navigator/)Open navigation apps like Google Maps or Apple Maps with directions to destinations Opens the plugin repository until a dedicated docs page is available.
[Light Sensor ](https://github.com/Cap-go/capacitor-light-sensor/)Access the ambient light sensor to measure illuminance levels in lux with real-time updates Opens the plugin repository until a dedicated docs page is available.
[Live Activities ](https://github.com/Cap-go/capacitor-live-activities/)Manage iOS Live Activities and Dynamic Island layouts from Capacitor with JSON-driven templates Opens the plugin repository until a dedicated docs page is available.
[Live Reload ](https://github.com/Cap-go/capacitor-live-reload/)Connect to your dev server for instant hot reloading during development Opens the plugin repository until a dedicated docs page is available.
[LLM ](https://github.com/Cap-go/capacitor-llm/)Run Large Language Models locally on-device with Apple Intelligence and MLX support Opens the plugin repository until a dedicated docs page is available.
[Media Session ](https://github.com/Cap-go/capacitor-media-session/)Control media playback from lock screen and notification center Opens the plugin repository until a dedicated docs page is available.
[MQTT ](https://github.com/Cap-go/capacitor-mqtt/)MQTT support for real-time messaging across iOS, Android, and Web. Opens the plugin repository until a dedicated docs page is available.
[Mute ](https://github.com/Cap-go/capacitor-mute/)Detect device mute switch state for iOS devices to handle audio playback appropriately Opens the plugin repository until a dedicated docs page is available.
[Mux Player ](https://github.com/Cap-go/capacitor-mux-player/)Stream adaptive bitrate video with Mux player for optimized playback quality Opens the plugin repository until a dedicated docs page is available.
[Native Audio ](https://github.com/Cap-go/capacitor-native-audio/)Play short audio files with low latency using native audio engine for games and apps Opens the plugin repository until a dedicated docs page is available.
[Native Biometric ](https://github.com/Cap-go/capacitor-native-biometric/)Secure authentication using Face ID, Touch ID, and Android biometric APIs Opens the plugin repository until a dedicated docs page is available.
[Native Geocoder ](https://github.com/Cap-go/capacitor-nativegeocoder/)Convert addresses to coordinates and coordinates to addresses using native geocoding Opens the plugin repository until a dedicated docs page is available.
[Native Market ](https://github.com/Cap-go/capacitor-native-market/)Deep link users directly to your app page on Google Play Store or Apple App Store Opens the plugin repository until a dedicated docs page is available.
[Native Navigation ](https://github.com/Cap-go/capacitor-native-navigation/)Render native navbars, tabbars, and transition shells over a full-screen Capacitor WebView Opens the plugin repository until a dedicated docs page is available.
[Native Purchases ](https://github.com/Cap-go/capacitor-native-purchases/)Implement native in-app purchases and subscriptions for iOS and Android with simple API Opens the plugin repository until a dedicated docs page is available.
[Navigation Bar ](https://github.com/Cap-go/capacitor-navigation-bar/)Customize Android navigation bar color and visibility for immersive UI experiences Opens the plugin repository until a dedicated docs page is available.
[NFC ](https://github.com/Cap-go/capacitor-nfc/)Native NFC tag discovery, reading and writing for Capacitor apps on iOS and Android Opens the plugin repository until a dedicated docs page is available.
[Passkey ](https://github.com/Cap-go/capacitor-passkey/)Keep browser-style WebAuthn code in Capacitor while native passkey calls and host patching are handled for you Opens the plugin repository until a dedicated docs page is available.
[Pay ](https://github.com/Cap-go/capacitor-pay/)Accept payments with Apple Pay and Google Pay for seamless checkout experience Opens the plugin repository until a dedicated docs page is available.
[PDF Generator ](https://github.com/Cap-go/capacitor-pdf-generator/)Create PDF documents from HTML templates for invoices, reports, and receipts Opens the plugin repository until a dedicated docs page is available.
[Pedometer ](https://github.com/Cap-go/capacitor-pedometer/)Track steps, distance, pace, cadence, and floors with device pedometer sensors Opens the plugin repository until a dedicated docs page is available.
[Persistent Account ](https://github.com/Cap-go/capacitor-persistent-account/)Preserve user authentication and account data across app reinstalls and updates Opens the plugin repository until a dedicated docs page is available.
[Persona ](https://github.com/Cap-go/capacitor-persona/)Launch Persona identity verification inquiries with native iOS and Android SDKs Opens the plugin repository until a dedicated docs page is available.
[Photo Library ](https://github.com/Cap-go/capacitor-photo-library/)Browse, save, and manage photos and videos in device photo library with permissions Opens the plugin repository until a dedicated docs page is available.
[Printer ](https://github.com/Cap-go/capacitor-printer/)Capacitor plugin for printing documents, HTML, PDFs, images and web views Opens the plugin repository until a dedicated docs page is available.
[Privacy Screen ](https://github.com/Cap-go/capacitor-privacy-screen/)Protect app content in Android screenshots and obscure the iOS app switcher snapshot Opens the plugin repository until a dedicated docs page is available.
[Proximity ](https://github.com/Cap-go/capacitor-proximity/)Enable native proximity monitoring so your app can react when the device is near a face, hand, or surface Opens the plugin repository until a dedicated docs page is available.
[Purchases ](https://github.com/RevenueCat/purchases-capacitor/)Implement in-app subscriptions and purchases with RevenueCat SDK for cross-platform monetization Opens the plugin repository until a dedicated docs page is available.
[RealtimeKit ](https://github.com/Cap-go/capacitor-realtimekit/)Cloudflare Calls integration with built-in UI for video meetings and real-time communication Opens the plugin repository until a dedicated docs page is available.
[Ricoh360 Camera ](https://github.com/Cap-go/capacitor-ricoh360-camera-plugin/)Control Ricoh Theta 360-degree cameras for immersive panoramic photography Opens the plugin repository until a dedicated docs page is available.
[RudderStack ](https://github.com/Cap-go/capacitor-rudderstack/)RudderStack analytics, identity resolution, screen tracking, and delivery controls for Capacitor Opens the plugin repository until a dedicated docs page is available.
[Screen Orientation ](https://github.com/Cap-go/capacitor-screen-orientation/)Screen orientation plugin with support for bypassing orientation lock Opens the plugin repository until a dedicated docs page is available.
[Screen Recorder ](https://github.com/Cap-go/capacitor-screen-recorder/)Capture screen recordings with audio for tutorials, demos, and bug reports Opens the plugin repository until a dedicated docs page is available.
[Shake ](https://github.com/Cap-go/capacitor-shake/)Detect shake gestures on device for triggering actions like undo or feedback Opens the plugin repository until a dedicated docs page is available.
[Share Target ](https://github.com/Cap-go/capacitor-share-target/)Receive shared content from other apps - text, images, and files Opens the plugin repository until a dedicated docs page is available.
[SIM ](https://github.com/Cap-go/capacitor-sim/)Retrieve SIM card information including carrier name, country code, and phone number Opens the plugin repository until a dedicated docs page is available.
[Social Login ](https://github.com/Cap-go/capacitor-social-login/)Authenticate users with Google, Facebook, and Apple Sign-In for easy social login Opens the plugin repository until a dedicated docs page is available.
[Speech Recognition ](https://github.com/Cap-go/capacitor-speech-recognition/)Natural, low-latency speech recognition with streaming partial results and cross-platform parity Opens the plugin repository until a dedicated docs page is available.
[Speech Synthesis ](https://github.com/Cap-go/capacitor-speech-synthesis/)Synthesize speech from text with full control over language, voice, pitch, rate, and volume. Opens the plugin repository until a dedicated docs page is available.
[SSL Pinning ](https://github.com/Cap-go/capacitor-ssl-pinning/)Pin HTTPS connections to bundled certificates for CapacitorHttp on iOS and Android Opens the plugin repository until a dedicated docs page is available.
[Streamcall ](https://github.com/Cap-go/capacitor-streamcall/)Integrate video calling and live streaming with Stream SDK for real-time communication Opens the plugin repository until a dedicated docs page is available.
[Text Interaction ](https://github.com/Cap-go/capacitor-textinteraction/)Enable advanced text selection, copy-paste, and interaction features in web views Opens the plugin repository until a dedicated docs page is available.
[Twilio Video ](https://github.com/Cap-go/capacitor-twilio-video/)Join Twilio Video rooms from Capacitor with native audio, camera, and room lifecycle events Opens the plugin repository until a dedicated docs page is available.
[Twilio Voice ](https://github.com/Cap-go/capacitor-twilio-voice/)Make and receive VoIP calls with Twilio Voice for in-app calling functionality Opens the plugin repository until a dedicated docs page is available.
[Updater ](https://github.com/Cap-go/capacitor-updater/)Deploy live updates instantly to your users without app store review delays Opens the plugin repository until a dedicated docs page is available.
[Uploader ](https://github.com/Cap-go/capacitor-uploader/)Upload large files reliably in background with progress tracking and retry support Opens the plugin repository until a dedicated docs page is available.
[Usage Stats Manager ](https://github.com/Cap-go/capacitor-android-usagestatsmanager/)Access Android usage statistics to track app usage time and screen time analytics Opens the plugin repository until a dedicated docs page is available.
[Video Player ](https://github.com/Cap-go/capacitor-video-player/)Native video playback with subtitles, fullscreen, and comprehensive controls Opens the plugin repository until a dedicated docs page is available.
[Video Thumbnails ](https://github.com/Cap-go/capacitor-video-thumbnails/)Generate thumbnail images from local and remote video files at specific timestamps Opens the plugin repository until a dedicated docs page is available.
[Volume Buttons ](https://github.com/Cap-go/capacitor-volume-buttons/)Capture hardware volume button presses for custom app controls and shortcuts Opens the plugin repository until a dedicated docs page is available.
[Watch ](https://github.com/Cap-go/capacitor-watch/)Apple Watch communication with bidirectional messaging between iPhone and watchOS apps Opens the plugin repository until a dedicated docs page is available.
[WebView Crash ](https://github.com/Cap-go/capacitor-webview-crash/)Detect recovered WebView crashes and tell the next JavaScript runtime what happened Opens the plugin repository until a dedicated docs page is available.
[WebView Guardian ](https://github.com/Cap-go/capacitor-webview-guardian/)Detect when the WebView was killed in the background and relaunch it on foreground Opens the plugin repository until a dedicated docs page is available.
[WebView Version Checker ](https://github.com/Cap-go/capacitor-webview-version-checker/)Capacitor plugin for checking Android WebView version freshness and guiding users to native update flows Opens the plugin repository until a dedicated docs page is available.
[WeChat ](https://github.com/Cap-go/capacitor-wechat/)WeChat SDK for Capacitor - enables authentication, sharing, payments, and mini-programs Opens the plugin repository until a dedicated docs page is available.
[Widget Kit ](https://github.com/Cap-go/capacitor-widget-kit/)Build WidgetKit and Live Activity surfaces from Capacitor with SVG frames, timers, action hotspots, or full-native widget state sync Opens the plugin repository until a dedicated docs page is available.
[WiFi ](https://github.com/Cap-go/capacitor-wifi/)Manage WiFi connectivity for your Capacitor app Opens the plugin repository until a dedicated docs page is available.
[YouTube Player ](https://github.com/Cap-go/capacitor-youtube-player/)Embed YouTube videos with full player API control and event handling Opens the plugin repository until a dedicated docs page is available.
[Zebra DataWedge ](https://github.com/Cap-go/capacitor-zebra-datawedge/)Manage Zebra DataWedge profiles, notifications, queries, and scan triggers on Zebra Android devices Opens the plugin repository until a dedicated docs page is available.
[Zip ](https://github.com/Cap-go/capacitor-zip/)A free Capacitor plugin for zipping and unzipping files on iOS, Android, and Web. Opens the plugin repository until a dedicated docs page is available.
# @capgo/capacitor-accelerometer
> Capacitor plugin contract for working with the device accelerometer.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin contract for working with the device accelerometer.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getMeasurement` - Get the most recent accelerometer sample that was recorded by the native layer.
* `isAvailable` - Check if the current device includes an accelerometer sensor.
* `startMeasurementUpdates` - Begin streaming accelerometer updates to the JavaScript layer.
* `stopMeasurementUpdates` - Stop streaming accelerometer updates started via .
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------- | ------------------------------------------------------------------------------- |
| `getMeasurement` | Get the most recent accelerometer sample that was recorded by the native layer. |
| `isAvailable` | Check if the current device includes an accelerometer sensor. |
| `startMeasurementUpdates` | Begin streaming accelerometer updates to the JavaScript layer. |
| `stopMeasurementUpdates` | Stop streaming accelerometer updates started via . |
| `checkPermissions` | Return the current permission state for accessing motion data. |
| `requestPermissions` | Request permission to access motion data if supported by the platform. |
| `addListener` | Listen for measurement updates. |
| `removeAllListeners` | Remove all listeners that have been registered on the plugin. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-accelerometer](https://github.com/Cap-go/capacitor-accelerometer/).
# Getting Started
> Install @capgo/capacitor-accelerometer and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-accelerometer
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getMeasurement`
[Section titled âgetMeasurementâ](#getmeasurement)
Get the most recent accelerometer sample that was recorded by the native layer.
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.getMeasurement();
```
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if the current device includes an accelerometer sensor.
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.isAvailable();
```
### `startMeasurementUpdates`
[Section titled âstartMeasurementUpdatesâ](#startmeasurementupdates)
Begin streaming accelerometer updates to the JavaScript layer.
Call with the `measurement` event to receive the updates.
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.startMeasurementUpdates();
```
### `stopMeasurementUpdates`
[Section titled âstopMeasurementUpdatesâ](#stopmeasurementupdates)
Stop streaming accelerometer updates started via .
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.stopMeasurementUpdates();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Return the current permission state for accessing motion data.
On platforms without explicit permissions this resolves to `granted`.
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission to access motion data if supported by the platform.
```typescript
import { CapacitorAccelerometer } from '@capgo/capacitor-accelerometer';
await CapacitorAccelerometer.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetMeasurementResult`
[Section titled âGetMeasurementResultâ](#getmeasurementresult)
Alias for the most recent measurement.
```typescript
export type GetMeasurementResult = Measurement;
```
### `IsAvailableResult`
[Section titled âIsAvailableResultâ](#isavailableresult)
Result returned by .
```typescript
export interface IsAvailableResult {
/**
* Whether an accelerometer sensor is available on the device.
*
* @since 1.0.0
*/
isAvailable: boolean;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission information returned by and .
```typescript
export interface PermissionStatus {
/**
* The permission state for accessing motion data on the current platform.
*
* @since 1.0.0
*/
accelerometer: AccelerometerPermissionState;
}
```
### `MeasurementEvent`
[Section titled âMeasurementEventâ](#measurementevent)
Event payload emitted when is active.
```typescript
export type MeasurementEvent = Measurement;
```
### `Measurement`
[Section titled âMeasurementâ](#measurement)
The x, y and z axis acceleration values reported by the device motion sensors.
```typescript
export interface Measurement {
/**
* The acceleration on the x-axis in G's.
*
* @since 1.0.0
*/
x: number;
/**
* The acceleration on the y-axis in G's.
*
* @since 1.0.0
*/
y: number;
/**
* The acceleration on the z-axis in G's.
*
* @since 1.0.0
*/
z: number;
}
```
### `AccelerometerPermissionState`
[Section titled âAccelerometerPermissionStateâ](#accelerometerpermissionstate)
Permission state union including `limited` for platforms that can throttle motion access.
```typescript
export type AccelerometerPermissionState = PermissionState | 'limited';
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Platform permission states supported by Capacitor.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-admob
> AdMob Plus Plugin interface for displaying Google AdMob ads in Capacitor apps.
## Overview
[Section titled âOverviewâ](#overview)
AdMob Plus Plugin interface for displaying Google AdMob ads in Capacitor apps.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `start` - Initialize and start the AdMob SDK.
* `configure` - Configure AdMob settings.
* `configRequest` - Configure ad request settings.
* `adCreate` - Create a new ad instance.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------ | --------------------------------------------------------- |
| `start` | Initialize and start the AdMob SDK. |
| `configure` | Configure AdMob settings. |
| `configRequest` | Configure ad request settings. |
| `adCreate` | Create a new ad instance. |
| `adIsLoaded` | Check if an ad is loaded and ready to be shown. |
| `adLoad` | Load an ad. |
| `adShow` | Show a loaded ad. |
| `adHide` | Hide a currently displayed ad. |
| `trackingAuthorizationStatus` | Get the current tracking authorization status (iOS only). |
| `requestTrackingAuthorization` | Request tracking authorization from the user (iOS only). |
| `addListener` | Add a listener for ad events. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-admob](https://github.com/Cap-go/capacitor-admob/).
# Getting Started
> Install @capgo/capacitor-admob and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-admob
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AdMob } from '@capgo/capacitor-admob';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `start`
[Section titled âstartâ](#start)
Initialize and start the AdMob SDK.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.start();
```
### `configure`
[Section titled âconfigureâ](#configure)
Configure AdMob settings.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.configure({
appMuted: false,
appVolume: 0.5
});
```
### `configRequest`
[Section titled âconfigRequestâ](#configrequest)
Configure ad request settings.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.configRequest({
maxAdContentRating: MaxAdContentRating.PG,
tagForChildDirectedTreatment: true,
testDeviceIds: ['test-device-id']
});
```
### `adCreate`
[Section titled âadCreateâ](#adcreate)
Create a new ad instance.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.adCreate({
adUnitId: 'ca-app-pub-3940256099942544/1033173712'
});
```
### `adIsLoaded`
[Section titled âadIsLoadedâ](#adisloaded)
Check if an ad is loaded and ready to be shown.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
const isLoaded = await AdMob.adIsLoaded({ id: 1 });
if (isLoaded) {
await AdMob.adShow({ id: 1 });
}
```
### `adLoad`
[Section titled âadLoadâ](#adload)
Load an ad.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.adLoad({ id: 1 });
```
### `adShow`
[Section titled âadShowâ](#adshow)
Show a loaded ad.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.adShow({ id: 1 });
```
### `adHide`
[Section titled âadHideâ](#adhide)
Hide a currently displayed ad.
```typescript
import { AdMob } from '@capgo/capacitor-admob';
await AdMob.adHide({ id: 1 });
```
### `trackingAuthorizationStatus`
[Section titled âtrackingAuthorizationStatusâ](#trackingauthorizationstatus)
Get the current tracking authorization status (iOS only).
```typescript
import { AdMob } from '@capgo/capacitor-admob';
const { status } = await AdMob.trackingAuthorizationStatus();
if (status === TrackingAuthorizationStatus.notDetermined) {
await AdMob.requestTrackingAuthorization();
}
```
### `requestTrackingAuthorization`
[Section titled ârequestTrackingAuthorizationâ](#requesttrackingauthorization)
Request tracking authorization from the user (iOS only).
```typescript
import { AdMob } from '@capgo/capacitor-admob';
const { status } = await AdMob.requestTrackingAuthorization();
console.log('User tracking status:', status);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AdMobConfig`
[Section titled âAdMobConfigâ](#admobconfig)
Configuration options for AdMob.
```typescript
export type AdMobConfig = {
/** Whether the app should be muted */
appMuted?: boolean;
/** The app volume (0.0 to 1.0) */
appVolume?: number;
};
```
### `RequestConfig`
[Section titled âRequestConfigâ](#requestconfig)
Configuration for ad requests.
```typescript
export type RequestConfig = {
/** Maximum ad content rating */
maxAdContentRating?: MaxAdContentRating;
/** Whether to use the same app key */
sameAppKey?: boolean;
/** Tag for child-directed treatment (true, false, or null for unspecified) */
tagForChildDirectedTreatment?: boolean | null;
/** Tag for under age of consent (true, false, or null for unspecified) */
tagForUnderAgeOfConsent?: boolean | null;
/** Array of test device IDs */
testDeviceIds?: string[];
};
```
### `MobileAdOptions`
[Section titled âMobileAdOptionsâ](#mobileadoptions)
Base options for mobile ads.
```typescript
export type MobileAdOptions = {
/** The ad unit ID from AdMob */
adUnitId: string;
};
```
### `TrackingAuthorizationStatus`
[Section titled âTrackingAuthorizationStatusâ](#trackingauthorizationstatus-1)
Tracking authorization status for iOS App Tracking Transparency.
```typescript
export enum TrackingAuthorizationStatus {
/** User has not yet received an authorization request */
notDetermined = 0,
/** User restricted, device is unable to provide authorization */
restricted = 1,
/** User denied authorization */
denied = 2,
/** User authorized access */
authorized = 3,
}
```
### `MaxAdContentRating`
[Section titled âMaxAdContentRatingâ](#maxadcontentrating)
Maximum ad content rating enum used to restrict ads based on content rating.
```typescript
export enum MaxAdContentRating {
/** General Audiences */
G = 'G',
/** Mature Audiences */
MA = 'MA',
/** Parental Guidance */
PG = 'PG',
/** Teen */
T = 'T',
/** Unspecified rating */
UNSPECIFIED = '',
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-age-range
> Cross-platform age range detection plugin.
## Overview
[Section titled âOverviewâ](#overview)
Cross-platform age range detection plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `requestAgeRange` - Request the userâs age range.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ---------------------------------------- |
| `requestAgeRange` | Request the userâs age range. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-age-range](https://github.com/Cap-go/capacitor-age-range/).
# Getting Started
> Install @capgo/capacitor-age-range and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-age-range
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AgeRange } from '@capgo/capacitor-age-range';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `requestAgeRange`
[Section titled ârequestAgeRangeâ](#requestagerange)
Request the userâs age range.
On Android: queries Google Play Age Signals API (no user prompt). On iOS: presents the system DeclaredAgeRange dialog (requires iOS 26.2+).
```typescript
import { AgeRange } from '@capgo/capacitor-age-range';
const result = await AgeRange.requestAgeRange({ ageGates: [13, 16, 18] });
if (result.status === 'SHARING') {
console.log('Age range:', result.ageLower, '-', result.ageUpper);
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `RequestAgeRangeOptions`
[Section titled âRequestAgeRangeOptionsâ](#requestagerangeoptions)
Options for the age range request.
```typescript
export interface RequestAgeRangeOptions {
/**
* Age thresholds for the request.
*
* On iOS: these are passed to `requestAgeRange(ageGates:)` as the
* age boundaries presented in the system dialog. Common values: [13, 16, 18].
*
* On Android: this parameter is ignored (Play Age Signals returns
* predefined ranges: 0-12, 13-15, 16-17, 18+).
*
* @default [13, 16, 18]
* @since 8.0.0
*/
ageGates?: number[];
}
```
### `AgeRangeResult`
[Section titled âAgeRangeResultâ](#agerangeresult)
Result of the age range request.
```typescript
export interface AgeRangeResult {
/**
* The outcome status of the age range request.
*
* @since 8.0.0
*/
status: AgeRangeStatus;
/**
* Inclusive lower bound of the user's age range.
*
* Present when age data is available.
*
* @since 8.0.0
*/
ageLower?: number;
/**
* Inclusive upper bound of the user's age range.
*
* May be absent if the user is in the highest age bracket (e.g. 18+).
*
* @since 8.0.0
*/
ageUpper?: number;
/**
* How the age was declared/determined.
*
* On iOS: 'SELF_DECLARED' or 'GUARDIAN_DECLARED'.
* On Android: 'SUPERVISED' (guardian-managed) or 'VERIFIED' (Google-verified 18+).
*
* @since 8.0.0
*/
declarationSource?: DeclarationSource;
/**
* Android-only. The user's Google Play verification status.
*
* @since 8.0.0
*/
androidUserStatus?: AndroidUserStatus;
/**
* Android-only. Effective date for the most recent guardian-approved change.
*
* @since 8.0.0
*/
mostRecentApprovalDate?: string;
/**
* Android-only. Install identifier for supervised installs in Google Play.
*
* @since 8.0.0
*/
installId?: string;
}
```
### `AgeRangeStatus`
[Section titled âAgeRangeStatusâ](#agerangestatus)
Top-level status of the age range request.
```typescript
export type AgeRangeStatus =
/**
* The user shared their age range (iOS) or age signals are available (Android).
*/
| 'SHARING'
/**
* The user declined to share their age range.
*/
| 'DECLINED_SHARING'
/**
* The age range API is not available on this device/OS version.
*/
| 'NOT_AVAILABLE'
/**
* An error occurred while requesting the age range.
*/
| 'ERROR';
```
### `DeclarationSource`
[Section titled âDeclarationSourceâ](#declarationsource)
How the age range was declared or determined.
```typescript
export type DeclarationSource =
/** The user self-declared their age (iOS). */
| 'SELF_DECLARED'
/** A guardian declared the user's age (iOS Family Sharing or Android supervised). */
| 'GUARDIAN_DECLARED'
/** Google has verified the user is 18+ (Android only). */
| 'VERIFIED'
/** Source is unknown or not provided by the platform. */
| 'UNKNOWN';
```
### `AndroidUserStatus`
[Section titled âAndroidUserStatusâ](#androiduserstatus)
Android-specific Google Play user status values.
```typescript
export type AndroidUserStatus =
| 'VERIFIED'
| 'SUPERVISED'
| 'SUPERVISED_APPROVAL_PENDING'
| 'SUPERVISED_APPROVAL_DENIED'
| 'UNKNOWN'
| 'EMPTY';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-android-age-signals
> Capacitor interface for retrieving Play Age Signals.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor interface for retrieving Play Age Signals.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `checkAgeSignals` - Request the current Play Age Signals for the active user.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------- |
| `checkAgeSignals` | Request the current Play Age Signals for the active user. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-android-age-signals](https://github.com/Cap-go/capacitor-android-age-signals/).
# Getting Started
> Install @capgo/capacitor-android-age-signals and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-android-age-signals
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AgeSignals } from '@capgo/capacitor-android-age-signals';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `checkAgeSignals`
[Section titled âcheckAgeSignalsâ](#checkagesignals)
Request the current Play Age Signals for the active user.
Only available on Android devices with Google Play installed.
```typescript
import { AgeSignals } from '@capgo/capacitor-android-age-signals';
await AgeSignals.checkAgeSignals();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CheckAgeSignalsResult`
[Section titled âCheckAgeSignalsResultâ](#checkagesignalsresult)
Structured result returned by .
```typescript
export interface CheckAgeSignalsResult {
/**
* The user's verification status as reported by Google Play.
*
* @since 0.0.1
*/
userStatus: UserStatus;
/**
* Inclusive lower bound of the supervised user's age range.
*
* Present only when `userStatus` is `SUPERVISED`, `SUPERVISED_APPROVAL_PENDING`, or `SUPERVISED_APPROVAL_DENIED`.
*
* @since 0.0.1
* @example 13
*/
ageLower?: number;
/**
* Inclusive upper bound of the supervised user's age range.
*
* Present only when `userStatus` is `SUPERVISED`, `SUPERVISED_APPROVAL_PENDING`, or `SUPERVISED_APPROVAL_DENIED`
* and the user's age is reported as less than 18.
*
* @since 0.0.1
* @example 15
*/
ageUpper?: number;
/**
* Effective date for the most recent significant change that received guardian approval.
*
* Present only when `userStatus` is `SUPERVISED_APPROVAL_PENDING` or `SUPERVISED_APPROVAL_DENIED`.
*
* @since 0.0.1
* @example "2024-01-15"
*/
mostRecentApprovalDate?: string;
/**
* Identifier assigned to supervised installs in Google Play for revocation notifications.
*
* Present only when `userStatus` is `SUPERVISED`, `SUPERVISED_APPROVAL_PENDING`, or `SUPERVISED_APPROVAL_DENIED`.
*
* @since 0.0.1
* @example "abc123xyz"
*/
installId?: string;
}
```
### `UserStatus`
[Section titled âUserStatusâ](#userstatus)
Status values reported by Google Play Age Signals.
```typescript
export enum UserStatus {
/**
* The user is over 18 and their age has been verified by Google.
*
* @since 0.0.1
*/
Verified = 'VERIFIED',
/**
* The user has a supervised Google Account managed by a guardian.
*
* Use `ageLower` and `ageUpper` to determine the user's age range.
*
* @since 0.0.1
*/
Supervised = 'SUPERVISED',
/**
* The supervised user has pending significant changes awaiting guardian approval.
*
* Use `ageLower` and `ageUpper` to determine the user's age range and `mostRecentApprovalDate`
* to identify the most recent approved change.
*
* @since 0.0.1
*/
SupervisedApprovalPending = 'SUPERVISED_APPROVAL_PENDING',
/**
* The supervised user's guardian denied one or more significant changes.
*
* Use `ageLower` and `ageUpper` to determine the user's age range and `mostRecentApprovalDate`
* to identify the last approved change.
*
* @since 0.0.1
*/
SupervisedApprovalDenied = 'SUPERVISED_APPROVAL_DENIED',
/**
* The user is not verified or supervised in supported regions.
*
* You should prompt the user to resolve their status in the Play Store.
*
* @since 0.0.1
*/
Unknown = 'UNKNOWN',
/**
* All other users return this value.
*
* @since 0.0.1
*/
Empty = 'EMPTY',
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-alarm
> Capacitor Alarm Plugin interface for managing native OS alarms.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Alarm Plugin interface for managing native OS alarms.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `createAlarm` - Create a native OS alarm using the platform clock app. On Android this uses the Alarm Clock intent; on iOS this uses AlarmKit if available (iOS 16+).
* `openAlarms` - Open the platformâs native alarm list UI, if available.
* `getOSInfo` - Get information about the OS and capabilities.
* `requestPermissions` - Request relevant permissions for alarm usage on the platform. On Android, may route to settings for exact alarms.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `createAlarm` | Create a native OS alarm using the platform clock app. On Android this uses the Alarm Clock intent; on iOS this uses AlarmKit if available (iOS 16+). |
| `openAlarms` | Open the platformâs native alarm list UI, if available. |
| `getOSInfo` | Get information about the OS and capabilities. |
| `requestPermissions` | Request relevant permissions for alarm usage on the platform. On Android, may route to settings for exact alarms. |
| `checkPermissions` | Check the current permission state for native alarm access without triggering UI. On iOS this reports AlarmKit readiness; on Android it reports capability details. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `getAlarms` | Get a list of alarms scheduled by this app. On iOS 26+, returns alarms from AlarmKit. On Android, this is not supported as the system does not provide an API to query alarms. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-alarm](https://github.com/Cap-go/capacitor-alarm/).
# Getting Started
> Install @capgo/capacitor-alarm and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-alarm
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `createAlarm`
[Section titled âcreateAlarmâ](#createalarm)
Create a native OS alarm using the platform clock app. On Android this uses the Alarm Clock intent; on iOS this uses AlarmKit if available (iOS 16+).
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const result = await CapgoAlarm.createAlarm({
hour: 7,
minute: 30,
label: 'Wake up',
skipUi: false,
vibrate: true
});
console.log('Alarm created:', result.success);
```
### `openAlarms`
[Section titled âopenAlarmsâ](#openalarms)
Open the platformâs native alarm list UI, if available.
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const result = await CapgoAlarm.openAlarms();
if (result.success) {
console.log('Alarms UI opened');
}
```
### `getOSInfo`
[Section titled âgetOSInfoâ](#getosinfo)
Get information about the OS and capabilities.
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const info = await CapgoAlarm.getOSInfo();
console.log('Platform:', info.platform);
console.log('Supports native alarms:', info.supportsNativeAlarms);
if (info.platform === 'android') {
console.log('Can schedule exact alarms:', info.canScheduleExactAlarms);
}
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request relevant permissions for alarm usage on the platform. On Android, may route to settings for exact alarms.
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const result = await CapgoAlarm.requestPermissions({ exactAlarm: true });
if (result.granted) {
console.log('Permissions granted');
} else {
console.log('Permissions denied');
}
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission state for native alarm access without triggering UI. On iOS this reports AlarmKit readiness; on Android it reports capability details.
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const status = await CapgoAlarm.checkPermissions();
console.log('AlarmKit allowed?', status.details?.alarmKit);
```
### `getAlarms`
[Section titled âgetAlarmsâ](#getalarms)
Get a list of alarms scheduled by this app. On iOS 26+, returns alarms from AlarmKit. On Android, this is not supported as the system does not provide an API to query alarms.
```typescript
import { CapgoAlarm } from '@capgo/capacitor-alarm';
const { alarms } = await CapgoAlarm.getAlarms();
console.log('Scheduled alarms:', alarms);
alarms.forEach(alarm => {
console.log(`Alarm ${alarm.id}: ${alarm.hour}:${alarm.minute} - ${alarm.label}`);
});
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `NativeAlarmCreateOptions`
[Section titled âNativeAlarmCreateOptionsâ](#nativealarmcreateoptions)
Options for creating a native OS alarm via the platform clock app.
```typescript
export interface NativeAlarmCreateOptions {
/** Hour of day in 24h format (0-23) */
hour: number;
/** Minute of hour (0-59) */
minute: number;
/** Optional label for the alarm */
label?: string;
/** Android only: attempt to skip UI if possible */
skipUi?: boolean;
/** Android only: set alarm to vibrate */
vibrate?: boolean;
}
```
### `NativeActionResult`
[Section titled âNativeActionResultâ](#nativeactionresult)
Result of a native action.
```typescript
export interface NativeActionResult {
/** Whether the action was successful */
success: boolean;
/** Optional message with additional information */
message?: string;
}
```
### `OSInfo`
[Section titled âOSInfoâ](#osinfo)
Returned info about current OS and capabilities.
```typescript
export interface OSInfo {
/** Platform identifier: 'ios' | 'android' | 'web' */
platform: string;
/** OS version string */
version: string;
/** Whether the platform exposes a native alarm app integration */
supportsNativeAlarms: boolean;
/** Whether scheduling local notifications is supported */
supportsScheduledNotifications: boolean;
/** Android only: whether exact alarms are allowed */
canScheduleExactAlarms?: boolean;
}
```
### `PermissionResult`
[Section titled âPermissionResultâ](#permissionresult)
Result of a permissions request.
```typescript
export interface PermissionResult {
/** Overall grant for requested scope */
granted: boolean;
/** Optional details by permission key */
details?: Record;
/** Optional human readable diagnostic */
message?: string;
}
```
### `AlarmInfo`
[Section titled âAlarmInfoâ](#alarminfo)
Information about a scheduled alarm.
```typescript
export interface AlarmInfo {
/** Unique identifier for the alarm */
id: string;
/** Hour of day in 24h format (0-23) */
hour: number;
/** Minute of hour (0-59) */
minute: number;
/** Optional label for the alarm */
label?: string;
/** Whether the alarm is enabled */
enabled?: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-android-inline-install
> Android Inline Install Plugin for triggering Google Play in-app install flows.
## Overview
[Section titled âOverviewâ](#overview)
Android Inline Install Plugin for triggering Google Play in-app install flows.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startInlineInstall` - Start an inline install flow using the Google Play overlay.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ----------------------------------------------------------- |
| `startInlineInstall` | Start an inline install flow using the Google Play overlay. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-android-inline-install](https://github.com/Cap-go/capacitor-android-inline-install/).
# Getting Started
> Install @capgo/capacitor-android-inline-install and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-android-inline-install
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AndroidInlineInstall } from '@capgo/capacitor-android-inline-install';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `startInlineInstall`
[Section titled âstartInlineInstallâ](#startinlineinstall)
Start an inline install flow using the Google Play overlay.
Note: Only eligible apps can use Inline Install. See:
```typescript
import { AndroidInlineInstall } from '@capgo/capacitor-android-inline-install';
const result = await AndroidInlineInstall.startInlineInstall({
id: 'com.example.app',
referrer: 'my-referrer',
overlay: true,
fallback: true
});
if (result.started) {
console.log('Install flow started');
if (result.fallbackUsed) {
console.log('Using fallback Play Store link');
}
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `StartInlineInstallOptions`
[Section titled âStartInlineInstallOptionsâ](#startinlineinstalloptions)
Options for starting an inline install flow.
```typescript
export interface StartInlineInstallOptions {
/** Package name of the app to be installed (target app). */
id: string;
/** Referrer string to pass to Play. Optional but recommended. */
referrer?: string;
/**
* Package name of your app (caller). Defaults to the current app package
* if omitted.
*/
callerId?: string;
/** Optional Custom Store Listing ID. */
csl_id?: string;
/** Whether to request the Play overlay. Defaults to true. */
overlay?: boolean;
/** If true, falls back to full Play Store deep link when overlay unavailable. Defaults to true. */
fallback?: boolean;
}
```
### `StartInlineInstallResult`
[Section titled âStartInlineInstallResultâ](#startinlineinstallresult)
Result of starting an inline install flow.
```typescript
export interface StartInlineInstallResult {
/** True when the inline install intent has been started. */
started: boolean;
/** True if a fallback deep link was used instead of inline overlay. */
fallbackUsed?: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-android-kiosk
> Capacitor Android Kiosk Plugin for controlling kiosk mode and launcher functionality. This plugin is Android-only. For iOS kiosk mode, use the device's Guided Access feature.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Android Kiosk Plugin for controlling kiosk mode and launcher functionality. This plugin is Android-only. For iOS kiosk mode, use the deviceâs Guided Access feature.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isInKioskMode` - Checks if the app is currently running in kiosk mode.
* `isSetAsLauncher` - Checks if the app is set as the device launcher (home app).
* `enterKioskMode` - Enters kiosk mode, hiding system UI and blocking hardware buttons. Also starts a foreground keep-alive service so the app is less likely to be killed by the system. The app must be set as the device launcher for this to work effectively.
* `exitKioskMode` - Exits kiosk mode, restoring normal system UI and hardware button functionality. Also stops the foreground keep-alive service started in enterKioskMode().
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isInKioskMode` | Checks if the app is currently running in kiosk mode. |
| `isSetAsLauncher` | Checks if the app is set as the device launcher (home app). |
| `enterKioskMode` | Enters kiosk mode, hiding system UI and blocking hardware buttons. Also starts a foreground keep-alive service so the app is less likely to be killed by the system. The app must be set as the device launcher for this to work effectively. |
| `exitKioskMode` | Exits kiosk mode, restoring normal system UI and hardware button functionality. Also stops the foreground keep-alive service started in enterKioskMode(). |
| `setAsLauncher` | Opens the deviceâs home screen settings to allow user to set this app as the launcher. This is required for full kiosk mode functionality. |
| `setAllowedKeys` | Sets which hardware keys are allowed to function in kiosk mode. By default, all hardware keys are blocked in kiosk mode. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-android-kiosk](https://github.com/Cap-go/capacitor-android-kiosk/).
# Getting Started
> Install @capgo/capacitor-android-kiosk and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-android-kiosk
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isInKioskMode`
[Section titled âisInKioskModeâ](#isinkioskmode)
Checks if the app is currently running in kiosk mode.
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
const { isInKioskMode } = await CapacitorAndroidKiosk.isInKioskMode();
console.log('Kiosk mode active:', isInKioskMode);
```
### `isSetAsLauncher`
[Section titled âisSetAsLauncherâ](#issetaslauncher)
Checks if the app is set as the device launcher (home app).
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
const { isLauncher } = await CapacitorAndroidKiosk.isSetAsLauncher();
console.log('Is launcher:', isLauncher);
```
### `enterKioskMode`
[Section titled âenterKioskModeâ](#enterkioskmode)
Enters kiosk mode, hiding system UI and blocking hardware buttons. Also starts a foreground keep-alive service so the app is less likely to be killed by the system. The app must be set as the device launcher for this to work effectively.
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
await CapacitorAndroidKiosk.enterKioskMode();
```
### `exitKioskMode`
[Section titled âexitKioskModeâ](#exitkioskmode)
Exits kiosk mode, restoring normal system UI and hardware button functionality. Also stops the foreground keep-alive service started in enterKioskMode().
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
await CapacitorAndroidKiosk.exitKioskMode();
console.log('Exited kiosk mode');
```
### `setAsLauncher`
[Section titled âsetAsLauncherâ](#setaslauncher)
Opens the deviceâs home screen settings to allow user to set this app as the launcher. This is required for full kiosk mode functionality.
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
await CapacitorAndroidKiosk.setAsLauncher();
// User will be prompted to select this app as the home app
```
### `setAllowedKeys`
[Section titled âsetAllowedKeysâ](#setallowedkeys)
Sets which hardware keys are allowed to function in kiosk mode. By default, all hardware keys are blocked in kiosk mode.
```typescript
import { CapacitorAndroidKiosk } from '@capgo/capacitor-android-kiosk';
// Allow volume keys only
await CapacitorAndroidKiosk.setAllowedKeys({
volumeUp: true,
volumeDown: true,
back: false,
home: false,
recent: false
});
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `EnterKioskModeOptions`
[Section titled âEnterKioskModeOptionsâ](#enterkioskmodeoptions)
Optional flags for `enterKioskMode`.
```typescript
export interface EnterKioskModeOptions {
/**
* After reboot, start the app so you can call `enterKioskMode()` again. Best-effort only (OEM
* behavior, force-stop). Omit to keep the saved value. Cleared when you call `exitKioskMode()`.
*/
restoreAfterReboot?: boolean;
/**
* Periodically tries to bring the app to the foreground. Skipped while the screen is off. Often
* blocked from the background on some devicesâbeing the default launcher, relaxing battery limits,
* and allowing exact alarms (where required) improve odds. Omit to keep the saved value.
*/
relaunch?: boolean;
/** Minutes between relaunch attempts when `relaunch` is on. Range 5â60; default 15. */
relaunchIntervalMinutes?: number;
}
```
### `AllowedKeysOptions`
[Section titled âAllowedKeysOptionsâ](#allowedkeysoptions)
Configuration options for allowed hardware keys in kiosk mode.
```typescript
export interface AllowedKeysOptions {
/**
* Allow volume up button
* @default false
*/
volumeUp?: boolean;
/**
* Allow volume down button
* @default false
*/
volumeDown?: boolean;
/**
* Allow back button
* @default false
*/
back?: boolean;
/**
* Allow home button
* @default false
*/
home?: boolean;
/**
* Allow recent apps button
* @default false
*/
recent?: boolean;
/**
* Allow power button
* @default false
*/
power?: boolean;
/**
* Allow camera button (if present)
* @default false
*/
camera?: boolean;
/**
* Allow menu button (if present)
* @default false
*/
menu?: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-android-sms-retriever
> Read one app-targeted verification SMS without SMS permissions and request SIM phone number hints on Android.
## Overview
[Section titled âOverviewâ](#overview)
`@capgo/capacitor-android-sms-retriever` wraps Google Play services SMS Retriever and Phone Number Hint APIs for Android-only Capacitor verification flows.
The plugin lets your app listen for a single verification SMS addressed to your app without requesting SMS permissions. It can also show Androidâs native Phone Number Hint UI so users can choose a SIM-based phone number without typing it manually.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startWatch` - Start a five-minute SMS Retriever watch for one verification SMS.
* `stopWatch` - Stop the active SMS Retriever watch.
* `getHashString` - Read the 11-character app hash used in verification SMS messages.
* `getPhoneNumber` - Open Android Phone Number Hint and return the selected phone number.
* `smsReceived` - Listen for the retrieved verification SMS.
* `smsRetrieverTimeout` - Listen for the five-minute timeout.
* `smsRetrieverError` - Listen for runtime errors from Android or Google Play services.
## Platform Support
[Section titled âPlatform Supportâ](#platform-support)
| Platform | Support |
| -------- | ---------------- |
| Android | Supported |
| iOS | Unsupported stub |
| Web | Unsupported stub |
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------------------------- | ------------------------------------------------------ |
| `startWatch` | Start listening for one verification SMS. |
| `stopWatch` | Stop the active watch. |
| `getHashString` | Return the 11-character app hash. |
| `getPhoneNumber` | Show Phone Number Hint and return the selected number. |
| `addListener('smsReceived', ...)` | Receive the retrieved SMS payload. |
| `addListener('smsRetrieverTimeout', ...)` | Handle timeout events. |
| `addListener('smsRetrieverError', ...)` | Handle retriever errors. |
| `getPluginVersion` | Return the native plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-android-sms-retriever](https://github.com/Cap-go/capacitor-android-sms-retriever/).
# Getting Started
> Install @capgo/capacitor-android-sms-retriever and use Android SMS Retriever in a Capacitor app.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-android-sms-retriever
bunx cap sync android
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AndroidSmsRetriever } from '@capgo/capacitor-android-sms-retriever';
```
## Android Requirements
[Section titled âAndroid Requirementsâ](#android-requirements)
SMS Retriever requires Google Play services on the Android device. The plugin does not request `READ_SMS` or `RECEIVE_SMS` permissions.
Your verification SMS must include the app hash returned by `getHashString()`. Generate the hash for the signing key used to distribute the app. Debug, release, and Play App Signing builds can have different hashes.
## Listen For A Verification SMS
[Section titled âListen For A Verification SMSâ](#listen-for-a-verification-sms)
```typescript
import { AndroidSmsRetriever } from '@capgo/capacitor-android-sms-retriever';
const received = await AndroidSmsRetriever.addListener('smsReceived', ({ message }) => {
const code = message.match(/\b\d{6}\b/)?.[0];
console.log('Verification code:', code);
});
const timeout = await AndroidSmsRetriever.addListener('smsRetrieverTimeout', () => {
console.log('SMS Retriever timed out');
});
const errors = await AndroidSmsRetriever.addListener('smsRetrieverError', ({ message }) => {
console.error('SMS Retriever error:', message);
});
await AndroidSmsRetriever.startWatch();
// Remove listeners when the verification flow is done.
await received.remove();
await timeout.remove();
await errors.remove();
```
## Stop Watching
[Section titled âStop Watchingâ](#stop-watching)
```typescript
await AndroidSmsRetriever.stopWatch();
```
## Get The App Hash
[Section titled âGet The App Hashâ](#get-the-app-hash)
```typescript
const { hash } = await AndroidSmsRetriever.getHashString();
console.log(hash);
```
Use this hash at the end of the verification SMS sent by your backend.
## Request A Phone Number Hint
[Section titled âRequest A Phone Number Hintâ](#request-a-phone-number-hint)
```typescript
const { phoneNumber } = await AndroidSmsRetriever.getPhoneNumber();
console.log(phoneNumber);
```
Android shows the native Phone Number Hint UI and returns the phone number selected by the user.
## Example SMS
[Section titled âExample SMSâ](#example-sms)
```text
<#> 123456 is your verification code.
FA+9qCX9VSu
```
Replace the final line with the hash for your app signing key.
# @capgo/capacitor-android-usagestatsmanager
> Capacitor plugin for accessing Android UsageStatsManager API.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for accessing Android UsageStatsManager API.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `queryAndAggregateUsageStats` - Queries and aggregates usage stats for the given time range.
* `isUsageStatsPermissionGranted` - Checks if the usage stats permission is granted.
* `openUsageStatsSettings` - Open the usage stats settings screen. This will open the usage stats settings screen, which allows the user to grant the usage stats permission. This will always open the settings screen, even if the permission is already granted.
* `queryAllPackages` - Queries all installed packages on the device. Requires the QUERY\_ALL\_PACKAGES permission.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `queryAndAggregateUsageStats` | Queries and aggregates usage stats for the given time range. |
| `isUsageStatsPermissionGranted` | Checks if the usage stats permission is granted. |
| `openUsageStatsSettings` | Open the usage stats settings screen. This will open the usage stats settings screen, which allows the user to grant the usage stats permission. This will always open the settings screen, even if the permission is already granted. |
| `queryAllPackages` | Queries all installed packages on the device. Requires the QUERY\_ALL\_PACKAGES permission. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-android-usagestatsmanager](https://github.com/Cap-go/capacitor-android-usagestatsmanager/).
# Getting Started
> Install @capgo/capacitor-android-usagestatsmanager and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-android-usagestatsmanager
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorUsageStatsManager } from '@capgo/capacitor-android-usagestatsmanager';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `queryAndAggregateUsageStats`
[Section titled âqueryAndAggregateUsageStatsâ](#queryandaggregateusagestats)
Queries and aggregates usage stats for the given time range.
```typescript
import { CapacitorUsageStatsManager } from '@capgo/capacitor-android-usagestatsmanager';
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
const now = Date.now();
const stats = await UsageStatsManager.queryAndAggregateUsageStats({
beginTime: oneDayAgo,
endTime: now
});
for (const [packageName, usageData] of Object.entries(stats)) {
console.log(`${packageName}: ${usageData.totalTimeInForeground}ms`);
}
```
### `isUsageStatsPermissionGranted`
[Section titled âisUsageStatsPermissionGrantedâ](#isusagestatspermissiongranted)
Checks if the usage stats permission is granted.
```typescript
import { CapacitorUsageStatsManager } from '@capgo/capacitor-android-usagestatsmanager';
const { granted } = await UsageStatsManager.isUsageStatsPermissionGranted();
if (!granted) {
await UsageStatsManager.openUsageStatsSettings();
}
```
### `openUsageStatsSettings`
[Section titled âopenUsageStatsSettingsâ](#openusagestatssettings)
Open the usage stats settings screen. This will open the usage stats settings screen, which allows the user to grant the usage stats permission. This will always open the settings screen, even if the permission is already granted.
```typescript
import { CapacitorUsageStatsManager } from '@capgo/capacitor-android-usagestatsmanager';
await UsageStatsManager.openUsageStatsSettings();
```
### `queryAllPackages`
[Section titled âqueryAllPackagesâ](#queryallpackages)
Queries all installed packages on the device. Requires the QUERY\_ALL\_PACKAGES permission.
```typescript
import { CapacitorUsageStatsManager } from '@capgo/capacitor-android-usagestatsmanager';
const { packages } = await UsageStatsManager.queryAllPackages();
packages.forEach(pkg => {
console.log(`${pkg.appName} (${pkg.packageName}): v${pkg.versionName}`);
});
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `UsageStatsOptions`
[Section titled âUsageStatsOptionsâ](#usagestatsoptions)
Options for querying usage statistics.
```typescript
export interface UsageStatsOptions {
/**
* The inclusive beginning of the range of stats to include in the results.
* Defined in terms of "Unix time"
*/
beginTime: number;
/**
* The exclusive end of the range of stats to include in the results.
* Defined in terms of "Unix time"
*/
endTime: number;
}
```
### `UsageStats`
[Section titled âUsageStatsâ](#usagestats)
Usage statistics for an Android app.
```typescript
export interface UsageStats {
/**
* The first timestamp of the usage stats.
*/
firstTimeStamp: number;
/**
* The last timestamp of the usage stats.
*/
lastTimeStamp: number;
/**
* Only available on Android Q (API level 29) and above.
* Will be undefined on lower Android versions.
*/
lastTimeForegroundServiceUsed?: number;
/**
* The last time the app was used.
*/
lastTimeUsed: number;
/**
* Only available on Android Q (API level 29) and above.
* Will be undefined on lower Android versions.
*/
lastTimeVisible?: number;
/**
* The name of the package.
*/
packageName: string;
/**
* Only available on Android Q (API level 29) and above.
* Will be undefined on lower Android versions.
*/
totalForegroundServiceUsed?: number;
/**
* The total time the app was in the foreground.
*/
totalTimeInForeground: number;
/**
* Only available on Android Q (API level 29) and above.
* Will be undefined on lower Android versions.
*/
totalTimeVisible?: number;
}
```
### `UsageStatsPermissionResult`
[Section titled âUsageStatsPermissionResultâ](#usagestatspermissionresult)
Result of a usage stats permission check.
```typescript
export interface UsageStatsPermissionResult {
/**
* Whether the usage stats permission is granted.
*/
granted: boolean;
}
```
### `PackageInfo`
[Section titled âPackageInfoâ](#packageinfo)
Represents basic information about an installed package.
```typescript
export interface PackageInfo {
/** Package name */
packageName: string;
/** App display name */
appName: string;
/** Version name string */
versionName: string;
/** Version code number */
versionCode: number;
/** First install time in milliseconds since epoch */
firstInstallTime: number;
/** Last update time in milliseconds since epoch */
lastUpdateTime: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-app-attest
> Unified cross-platform attestation plugin for Capacitor.
## Overview
[Section titled âOverviewâ](#overview)
Unified cross-platform attestation plugin for Capacitor.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isSupported` - Checks whether native attestation is available on this device.
* `prepare` - Prepares attestation state and returns the key handle used for later calls.
* `createAttestation` - Creates a registration attestation token bound to a backend-issued challenge.
* `createAssertion` - Creates a request assertion token bound to a request payload.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------- | ----------------------------------------------------------------------------- |
| `isSupported` | Checks whether native attestation is available on this device. |
| `prepare` | Prepares attestation state and returns the key handle used for later calls. |
| `createAttestation` | Creates a registration attestation token bound to a backend-issued challenge. |
| `createAssertion` | Creates a request assertion token bound to a request payload. |
| `storeKeyId` | Stores/prepares a key identifier for reuse. |
| `getStoredKeyId` | Returns the currently stored/prepared key identifier. |
| `clearStoredKeyId` | Clears stored/prepared key identifiers. |
| `generateKey` | Legacy alias for `prepare()`. |
| `attestKey` | Legacy alias for `createAttestation()`. |
| `generateAssertion` | Legacy alias for `createAssertion()`. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-app-attest](https://github.com/Cap-go/capacitor-app-attest/).
# Android Setup & Backend Verification
> Configure Google Play Integrity Standard API on Android and verify integrity tokens on your backend.
## Android native system used
[Section titled âAndroid native system usedâ](#android-native-system-used)
On Android, this plugin uses **Google Play Integrity Standard API**:
* `prepareIntegrityToken` during `prepare()`
* `requestStandardIntegrityToken` for `createAttestation()` and `createAssertion()`
## Requirements
[Section titled âRequirementsâ](#requirements)
* Android app distributed through Google Play ecosystem
* Google Play services available on device
* Play Integrity API enabled for your app
* Google Cloud project number configured
## Google setup
[Section titled âGoogle setupâ](#google-setup)
1. Enable **Play Integrity API** in your Google Cloud project.
2. Open Play Console and configure Play Integrity access for your app.
3. Provide `cloudProjectNumber` to the plugin.
## Capacitor config
[Section titled âCapacitor configâ](#capacitor-config)
capacitor.config.ts
```ts
plugins: {
AppAttest: {
cloudProjectNumber: '123456789012',
},
}
```
You can also pass `cloudProjectNumber` per call in method options.
## Client flow
[Section titled âClient flowâ](#client-flow)
```typescript
import { AppAttest } from '@capgo/capacitor-app-attest';
const { keyId } = await AppAttest.prepare({
cloudProjectNumber: '123456789012',
});
const attestation = await AppAttest.createAttestation({
keyId,
challenge: 'backend-registration-challenge',
});
const assertion = await AppAttest.createAssertion({
keyId,
payload: 'backend-request-payload',
});
```
`token` is a Play Integrity token and must be decoded server-side.
## Backend workflow (Android)
[Section titled âBackend workflow (Android)â](#backend-workflow-android)
### Registration (`createAttestation`)
[Section titled âRegistration (createAttestation)â](#registration-createattestation)
1. Backend creates one-time `challenge`.
2. App calls `createAttestation({ keyId, challenge })`.
3. Backend calls Google `decodeIntegrityToken` API.
4. Backend verifies at minimum:
* `requestDetails.requestHash === base64url(SHA256(challenge))`
* `appIntegrity.packageName` equals your Android application id
* `appIntegrity.certificateSha256Digest` contains your release signing cert digest
* integrity verdicts match your security policy
### Request protection (`createAssertion`)
[Section titled âRequest protection (createAssertion)â](#request-protection-createassertion)
1. Backend creates one-time `payload`.
2. App calls `createAssertion({ keyId, payload })`.
3. Backend decodes token and checks `requestHash === base64url(SHA256(payload))`.
4. Enforce replay prevention (single-use + TTL) and integrity verdict policy.
## Android schema
[Section titled âAndroid schemaâ](#android-schema)
```mermaid
sequenceDiagram
participant App as Android App
participant Plugin as AppAttest plugin
participant PlaySDK as Play Integrity SDK
participant BE as Backend
participant Google as decodeIntegrityToken API
App->>Plugin: prepare(cloudProjectNumber)
Plugin->>PlaySDK: prepareIntegrityToken()
PlaySDK-->>Plugin: provider handle (keyId)
BE->>App: one-time challenge
App->>Plugin: createAttestation(keyId, challenge)
Plugin->>PlaySDK: requestStandardIntegrityToken(requestHash)
PlaySDK-->>Plugin: integrity token
Plugin-->>App: token + platform + format + keyId
App->>BE: token + challenge + keyId
BE->>Google: decodeIntegrityToken(token)
Google-->>BE: decoded payload
BE->>BE: verify requestHash + app identity + verdicts
BE->>App: one-time payload
App->>Plugin: createAssertion(keyId, payload)
Plugin->>PlaySDK: requestStandardIntegrityToken(requestHash)
PlaySDK-->>Plugin: integrity token
App->>BE: token + payload + keyId
BE->>Google: decodeIntegrityToken(token)
Google-->>BE: decoded payload
BE->>BE: verify requestHash + replay policy
```
## Minimal backend payload contract
[Section titled âMinimal backend payload contractâ](#minimal-backend-payload-contract)
Registration:
```json
{
"platform": "android",
"format": "google-play-integrity-standard",
"keyId": "string",
"challenge": "string",
"token": "string"
}
```
Assertion:
```json
{
"platform": "android",
"format": "google-play-integrity-standard",
"keyId": "string",
"payload": "string",
"token": "string"
}
```
# Getting Started
> Learn how to install and use App Attest with a unified API for iOS and Android attestation.
1. **Install the package**
```sh
bun add @capgo/capacitor-app-attest
```
2. **Sync native projects**
```sh
bunx cap sync
```
3. **Configure platform requirements**
* Complete [iOS setup](/docs/plugins/app-attest/ios/) for App Attest capability and backend verification flow.
* Complete [Android setup](/docs/plugins/app-attest/android/) for Play Integrity Standard and backend verification flow.
## Why use this plugin
[Section titled âWhy use this pluginâ](#why-use-this-plugin)
This plugin provides one cross-platform API while keeping native platform security:
* iOS: Apple App Attest (`DeviceCheck`)
* Android: Google Play Integrity Standard API
* No custom client-side crypto scheme
* Normalized outputs for backend checks
## Usage
[Section titled âUsageâ](#usage)
```typescript
import { AppAttest } from '@capgo/capacitor-app-attest';
const support = await AppAttest.isSupported();
if (!support.isSupported) {
throw new Error(`Attestation not supported on ${support.platform}`);
}
const prepared = await AppAttest.prepare();
const registration = await AppAttest.createAttestation({
keyId: prepared.keyId,
challenge: 'backend-one-time-registration-challenge',
});
const assertion = await AppAttest.createAssertion({
keyId: prepared.keyId,
payload: 'backend-one-time-request-payload',
});
console.log(registration.platform, registration.format, registration.token);
console.log(assertion.platform, assertion.format, assertion.token);
```
## Unified response shape
[Section titled âUnified response shapeâ](#unified-response-shape)
`createAttestation()` and `createAssertion()` return the same key fields on iOS and Android:
| Field | Type | Description |
| ---------- | ----------------------------- | ------------------------------------------------------ |
| `platform` | `'ios' \| 'android' \| 'web'` | Native platform that produced the token |
| `format` | `AttestationFormat` | `apple-app-attest` or `google-play-integrity-standard` |
| `keyId` | `string` | Key/provider handle used for attestation |
| `token` | `string` | Token to verify on your backend |
## Backend requirement
[Section titled âBackend requirementâ](#backend-requirement)
Attestation is only useful when verified server-side.
* Never trust client-only success.
* Require one-time challenge/payload values from your backend.
* Verify `token`, app identity, and replay protections in backend logic.
Use the platform-specific backend guides:
* [iOS setup and backend verification](/docs/plugins/app-attest/ios/)
* [Android setup and backend verification](/docs/plugins/app-attest/android/)
# iOS Setup & Backend Verification
> Configure Apple App Attest on iOS and verify attestation/assertion payloads on your backend.
## iOS native system used
[Section titled âiOS native system usedâ](#ios-native-system-used)
On iOS, this plugin uses **Apple App Attest** from the `DeviceCheck` framework.
## Requirements
[Section titled âRequirementsâ](#requirements)
* iOS 14+
* Physical device recommended for real validation flows
* Xcode target with App Attest capability enabled
## Xcode setup
[Section titled âXcode setupâ](#xcode-setup)
1. Open your iOS app target in Xcode.
2. Go to **Signing & Capabilities**.
3. Click **+ Capability** and add **App Attest**.
No custom iOS permissions are required in `Info.plist` for App Attest itself.
## Client flow
[Section titled âClient flowâ](#client-flow)
```typescript
import { AppAttest } from '@capgo/capacitor-app-attest';
const { keyId } = await AppAttest.prepare();
const attestation = await AppAttest.createAttestation({
keyId,
challenge: 'backend-registration-challenge',
});
const assertion = await AppAttest.createAssertion({
keyId,
payload: 'backend-request-payload',
});
```
Send `attestation.token` and `assertion.token` to your backend. Do not validate them in the app.
## Backend workflow (iOS)
[Section titled âBackend workflow (iOS)â](#backend-workflow-ios)
### Registration (`createAttestation`)
[Section titled âRegistration (createAttestation)â](#registration-createattestation)
1. Backend creates one-time `challenge`.
2. App calls `createAttestation({ keyId, challenge })`.
3. Backend verifies App Attest attestation:
* certificate chain is valid and anchored to Apple App Attest
* app identity matches your app (`bundleId`, team)
* `clientDataHash` matches `SHA256(challenge)`
4. Store device key state (`keyId`, public key, and verifier metadata).
### Request protection (`createAssertion`)
[Section titled âRequest protection (createAssertion)â](#request-protection-createassertion)
1. Backend creates one-time `payload` (or canonical request hash input).
2. App calls `createAssertion({ keyId, payload })`.
3. Backend verifies assertion signature with previously stored key material.
4. Enforce replay protection and nonce TTL checks.
## iOS schema
[Section titled âiOS schemaâ](#ios-schema)
```mermaid
sequenceDiagram
participant App as iOS App
participant Plugin as AppAttest plugin
participant Apple as Apple App Attest
participant BE as Backend
BE->>App: one-time challenge
App->>Plugin: prepare()
Plugin->>Apple: generateKey()
Apple-->>Plugin: keyId
App->>Plugin: createAttestation(keyId, challenge)
Plugin->>Apple: attestKey(keyId, SHA256(challenge))
Apple-->>Plugin: attestation token
Plugin-->>App: token + platform + format + keyId
App->>BE: token + challenge + keyId
BE->>BE: verify Apple attestation rules
BE->>App: one-time payload
App->>Plugin: createAssertion(keyId, payload)
Plugin->>Apple: generateAssertion(keyId, SHA256(payload))
Apple-->>Plugin: assertion token
Plugin-->>App: token + platform + format + keyId
App->>BE: token + payload + keyId
BE->>BE: verify signature + replay policy
```
## Minimal backend payload contract
[Section titled âMinimal backend payload contractâ](#minimal-backend-payload-contract)
Registration:
```json
{
"platform": "ios",
"format": "apple-app-attest",
"keyId": "string",
"challenge": "string",
"token": "string"
}
```
Assertion:
```json
{
"platform": "ios",
"format": "apple-app-attest",
"keyId": "string",
"payload": "string",
"token": "string"
}
```
# @capgo/capacitor-app-tracking-transparency
> Capacitor App Tracking Transparency Plugin.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor App Tracking Transparency Plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getStatus` - Gets the current tracking authorization status without prompting the user.
* `requestPermission` - Requests user authorization to access app-related data for tracking. Displays the native iOS tracking permission dialog.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `getStatus` | Gets the current tracking authorization status without prompting the user. |
| `requestPermission` | Requests user authorization to access app-related data for tracking. Displays the native iOS tracking permission dialog. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-app-tracking-transparency](https://github.com/Cap-go/capacitor-app-tracking-transparency/).
# Getting Started
> Install @capgo/capacitor-app-tracking-transparency and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-app-tracking-transparency
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AppTrackingTransparency } from '@capgo/capacitor-app-tracking-transparency';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getStatus`
[Section titled âgetStatusâ](#getstatus)
Gets the current tracking authorization status without prompting the user.
```typescript
import { AppTrackingTransparency } from '@capgo/capacitor-app-tracking-transparency';
const { status } = await AppTrackingTransparency.getStatus();
if (status === 'authorized') {
console.log('Tracking is authorized');
}
```
### `requestPermission`
[Section titled ârequestPermissionâ](#requestpermission)
Requests user authorization to access app-related data for tracking. Displays the native iOS tracking permission dialog.
Note: This method will only show the dialog once. Subsequent calls will return the stored authorization status without showing the dialog.
```typescript
import { AppTrackingTransparency } from '@capgo/capacitor-app-tracking-transparency';
const { status } = await AppTrackingTransparency.requestPermission();
switch (status) {
case 'authorized':
console.log('User authorized tracking');
break;
case 'denied':
console.log('User denied tracking');
break;
case 'restricted':
console.log('Tracking is restricted');
break;
case 'notDetermined':
console.log('Status not determined');
break;
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AppTrackingStatusResponse`
[Section titled âAppTrackingStatusResponseâ](#apptrackingstatusresponse)
Response object containing the tracking authorization status.
```typescript
export interface AppTrackingStatusResponse {
/**
* The current tracking authorization status.
*
* @since 1.0.0
*/
status: AppTrackingStatus;
}
```
### `AppTrackingStatus`
[Section titled âAppTrackingStatusâ](#apptrackingstatus)
Possible values for the tracking authorization status.
```typescript
export type AppTrackingStatus = 'authorized' | 'denied' | 'notDetermined' | 'restricted';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-appinsights
> A wrapper around the https://github.com/apptopia/appinsights SDK.
## Overview
[Section titled âOverviewâ](#overview)
A wrapper around the SDK.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `init` - Initialize the AppInsights SDK.
* `setUserId` - Set or update the user ID after initialization.
* `getState` - Get the current state of the SDK.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ----------------------------------------------- |
| `init` | Initialize the AppInsights SDK. |
| `setUserId` | Set or update the user ID after initialization. |
| `getState` | Get the current state of the SDK. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-appinsights](https://github.com/Cap-go/capacitor-appinsights/).
# Getting Started
> Install @capgo/capacitor-appinsights and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-appinsights
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorAppInsights } from '@capgo/capacitor-appinsights';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `init`
[Section titled âinitâ](#init)
Initialize the AppInsights SDK
```typescript
import { CapacitorAppInsights } from '@capgo/capacitor-appinsights';
await CapacitorAppInsights.init({} as {
partnerId: string; // Provided by our business unit
partnerKey: string; // Provided by our business unit
});
```
### `setUserId`
[Section titled âsetUserIdâ](#setuserid)
Set or update the user ID after initialization
```typescript
import { CapacitorAppInsights } from '@capgo/capacitor-appinsights';
await CapacitorAppInsights.setUserId({} as { userId: string });
```
### `getState`
[Section titled âgetStateâ](#getstate)
Get the current state of the SDK
```typescript
import { CapacitorAppInsights } from '@capgo/capacitor-appinsights';
await CapacitorAppInsights.getState();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `PanelSDKState`
[Section titled âPanelSDKStateâ](#panelsdkstate)
```typescript
export interface PanelSDKState {
initCompleted: boolean; // SDK initialization status
jobScheduled: boolean; // Background job scheduling status
permissionAcquired: boolean; // Required permissions status
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-appsflyer
> Capacitor plugin for AppsFlyer attribution, analytics, and deep links.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for AppsFlyer attribution, analytics, and deep links.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `initSDK` - Use this method to initialize and start AppsFlyer SDK. This API should be called as soon as the app launched.
* `startSDK` - Use this method to start AppsFlyer SDK, only on manual start mode.
* `logEvent` - Log an in-app event.
* `setCustomerUserId` - Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyerâs unique ID and other devicesâ IDs. This ID is available in raw-data reports and in the Postback APIs for cross-referencing with your internal IDs.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `addListener('conversion_callback', listener)` | Listen for conversion callbacks, including `onConversionDataSuccess` and `onConversionDataFail`, with `OnConversionDataResult` payloads. |
| `addListener('oaoa_callback', listener)` | Listen for app-open attribution callbacks, including `onAppOpenAttribution` and `onAttributionFailure`, with `OnAppOpenAttribution` payloads. |
| `addListener('udl_callback', listener)` | Listen for unified deep link callbacks with `OnDeepLink` payloads. |
| `initSDK` | Use this method to initialize and start AppsFlyer SDK. This API should be called as soon as the app launched. |
| `startSDK` | Use this method to start AppsFlyer SDK, only on manual start mode. |
| `logEvent` | Log an in-app event. |
| `setCustomerUserId` | Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyerâs unique ID and other devicesâ IDs. This ID is available in raw-data reports and in the Postback APIs for cross-referencing with your internal IDs. |
| `setCurrencyCode` | Sets the currency used for in-app purchases. Provide a three-character ISO 4217 code. |
| `updateServerUninstallToken` | Pass GCM/FCM tokens on Android or APNs tokens on iOS when another plugin collected them. Use this to forward uninstall measurement tokens to AppsFlyer. |
| `setAppInviteOneLink` | Sets the OneLink ID used as the base link for invite attribution. |
| `setOneLinkCustomDomain` | Registers branded OneLink domains so AppsFlyer can resolve attribution parameters hidden in short links. |
| `appendParametersToDeepLinkingURL` | Enables attribution for App Links deep links without OneLink. Call this method before `startSDK()`. Include at least `pid` and `is_retargeting=true` in the parameters map. |
| `setResolveDeepLinkURLs` | Use this when an AppsFlyer OneLink is wrapped inside another Universal Link. It lets the SDK resolve the wrapped URL so deep linking still works correctly. |
| `addPushNotificationDeepLinkPath` | Configures how the SDK extracts deep link values from push notification payloads. |
| `setSharingFilter` | Stops events from propagating to the specified AppsFlyer partners. |
| `setSharingFilterForAllPartners` | Stops events from propagating to all AppsFlyer partners. Overwrites setSharingFilter. |
| `setSharingFilterForPartners` | Stops events from propagating to the specified AppsFlyer partners. |
| `setAdditionalData` | Sets additional key-value data to send to AppsFlyer. |
| `getAppsFlyerUID` | Get AppsFlyerâs unique device ID (created for every new install of an app). |
| `anonymizeUser` | End User Opt-Out from AppsFlyer analytics (Anonymize user data). |
| `stop` | Once this API is invoked, our SDK no longer communicates with our servers and stops functioning. Useful when implementing user opt-in/opt-out. |
| `disableSKAdNetwork` | Opt-out of SKAdNetwork. |
| `disableAdvertisingIdentifier` | Disables collection of various Advertising IDs by the SDK. This includes Apple Identity for Advertisers (IDFA), Google Advertising ID (GAID), OAID and Amazon Advertising ID (AAID). |
| `disableCollectASA` | Opt-out of Apple Search Ads attributions. |
| `setHost` | Set a custom host. |
| `generateInviteLink` | Allowing your existing users to invite their friends and contacts as new users to your app. |
| `validateAndLogInAppPurchaseAndroid` | API for server verification of in-app purchases. An af\_purchase event with the relevant values will be automatically logged if the validation is successful. |
| `validateAndLogInAppPurchaseIos` | See the source definitions for current behavior. |
| `getSdkVersion` | Get the AppsFlyer SDK version used in app. |
| `enableFacebookDeferredApplinks` | Enable the collection of Facebook Deferred AppLinks. Requires Facebook SDK and Facebook app on target/client device. This API must be invoked before initializing the AppsFlyer SDK in order to function properly. |
| `sendPushNotificationData` | Measure and get data from push-notification campaigns. |
| `setCurrentDeviceLanguage` | Set the language of the device. The data will be displayed in Raw Data Reports. |
| `logCrossPromoteImpression` | Logs an impression as part of a cross-promotion campaign. Make sure to use the promoted app ID as it appears in the AppsFlyer dashboard. |
| `setUserEmails` | Set the user emails and encrypt them. |
| `logLocation` | Manually log the location of the user. |
| `setPhoneNumber` | Will be sent as an SHA-256 encrypted string. |
| `setPartnerData` | Allows sending custom data for partner integration purposes. |
| `logInvite` | Use to log a user-invite in-app event (af\_invite). |
| `setDisableNetworkData` | Use to opt-out of collecting the network operator name (carrier) and sim operator name from the device. |
| `enableTCFDataCollection` | Use to opt-in/out the automatic collection of consent data, for users who use a CMP. Flag value will be persisted between app sessions. |
| `setConsentData` | Use this to set user consent data manually. If your app doesnât use a CMP compatible with TCF v2.2, use the following method to manually provide the consent data directly to the SDK. |
| `logAdRevenue` | By attributing ad revenue, app owners gain the complete view of user LTV and campaign ROI. Ad revenue is generated by displaying ads on rewarded videos, offer walls, interstitials, and banners in an app. You can use this method to log your ad revenue. |
| `setConsentDataV2` | Use this to set user consent data manually. If your app doesnât use a CMP compatible with TCF v2.2, use the following method to manually provide the consent data directly to the SDK. |
| `isSDKStarted` | Use this method to check whether the AppsFlyer SDK has already been started in the current session. |
| `isSDKStopped` | Use this method to check whether the AppsFlyer SDK is currently stopped. |
| `disableAppSetId` | Disables AppSet ID collection. If called before SDK init, App Set ID will not be collected. If called after init, App Set ID will be collected but not sent in request payloads. Android only. |
| `validateAndLogInAppPurchaseV2` | API for server verification of in-app purchases V2. An af\_purchase event with the relevant values will be automatically logged if the validation is successful. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-appsflyer](https://github.com/Cap-go/capacitor-appsflyer/).
# Getting Started
> Install @capgo/capacitor-appsflyer and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-appsflyer
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
import type {
AFAdRevenueData,
AFAndroidInAppPurchase,
AFAnonymizeUser,
AFAppendToDeepLink,
AFConsentData,
AFConsentOptions,
AFCuid,
AFCurrency,
AFData,
AFDisable,
AFEmails,
AFEnableTCFDataCollection,
AFEvent,
AFFbDAL,
AFFilters,
AFHost,
AFInit,
AFIosInAppPurchase,
AFLanguage,
AFLatLng,
AFLinkGenerator,
AFLogInvite,
AFOnelinkDomain,
AFOnelinkID,
AFPartnerData,
AFPath,
AFPhone,
AFPromotion,
AFPurchaseDetailsV2,
AFPushPayload,
AFUninstall,
AFUrls,
} from '@capgo/capacitor-appsflyer';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `initSDK`
[Section titled âinitSDKâ](#initsdk)
Use this method to initialize and start AppsFlyer SDK. This API should be called as soon as the app launches.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.initSDK({} as AFInit);
```
### `startSDK`
[Section titled âstartSDKâ](#startsdk)
Use this method to start AppsFlyer SDK, only on manual start mode.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.startSDK();
```
### `logEvent`
[Section titled âlogEventâ](#logevent)
Log an in-app event.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.logEvent({} as AFEvent);
```
### `setCustomerUserId`
[Section titled âsetCustomerUserIdâ](#setcustomeruserid)
Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyerâs unique ID and other devicesâ IDs. This ID is available in raw-data reports and in the Postback APIs for cross-referencing with your internal IDs.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setCustomerUserId({} as AFCuid);
```
### `setCurrencyCode`
[Section titled âsetCurrencyCodeâ](#setcurrencycode)
Sets the currency used for in-app purchases. Provide a three-character ISO 4217 code.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setCurrencyCode({} as AFCurrency);
```
### `updateServerUninstallToken`
[Section titled âupdateServerUninstallTokenâ](#updateserveruninstalltoken)
Pass GCM/FCM tokens on Android or APNs tokens on iOS when another plugin collected them. Use this to forward uninstall measurement tokens to AppsFlyer.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.updateServerUninstallToken({} as AFUninstall);
```
### `setAppInviteOneLink`
[Section titled âsetAppInviteOneLinkâ](#setappinviteonelink)
Sets the OneLink ID used as the base link for invite attribution.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setAppInviteOneLink({} as AFOnelinkID);
```
### `setOneLinkCustomDomain`
[Section titled âsetOneLinkCustomDomainâ](#setonelinkcustomdomain)
Registers branded OneLink domains so AppsFlyer can resolve attribution parameters hidden in short links.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setOneLinkCustomDomain({} as AFOnelinkDomain);
```
### `appendParametersToDeepLinkingURL`
[Section titled âappendParametersToDeepLinkingURLâ](#appendparameterstodeeplinkingurl)
Enables attribution for App Links deep links without OneLink. Call this method before `startSDK()`. Include at least `pid` and `is_retargeting=true` in the parameters map.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.appendParametersToDeepLinkingURL({} as AFAppendToDeepLink);
```
### `setResolveDeepLinkURLs`
[Section titled âsetResolveDeepLinkURLsâ](#setresolvedeeplinkurls)
Use this when an AppsFlyer OneLink is wrapped inside another Universal Link. It lets the SDK resolve the wrapped URL so deep linking still works correctly.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setResolveDeepLinkURLs({} as AFUrls);
```
### `addPushNotificationDeepLinkPath`
[Section titled âaddPushNotificationDeepLinkPathâ](#addpushnotificationdeeplinkpath)
Configures how the SDK extracts deep link values from push notification payloads.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.addPushNotificationDeepLinkPath({} as AFPath);
```
### `setSharingFilter`
[Section titled âsetSharingFilterâ](#setsharingfilter)
Stops events from propagating to the specified AppsFlyer partners.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setSharingFilter({} as AFFilters);
```
### `setSharingFilterForAllPartners`
[Section titled âsetSharingFilterForAllPartnersâ](#setsharingfilterforallpartners)
Stops events from propagating to all AppsFlyer partners. Overwrites setSharingFilter.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setSharingFilterForAllPartners();
```
### `setSharingFilterForPartners`
[Section titled âsetSharingFilterForPartnersâ](#setsharingfilterforpartners)
Stops events from propagating to the specified AppsFlyer partners.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setSharingFilterForPartners({} as AFFilters);
```
### `setAdditionalData`
[Section titled âsetAdditionalDataâ](#setadditionaldata)
Sets additional key-value data to send to AppsFlyer.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setAdditionalData({} as AFData);
```
### `getAppsFlyerUID`
[Section titled âgetAppsFlyerUIDâ](#getappsflyeruid)
Get AppsFlyerâs unique device ID (created for every new install of an app).
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.getAppsFlyerUID();
```
### `anonymizeUser`
[Section titled âanonymizeUserâ](#anonymizeuser)
End User Opt-Out from AppsFlyer analytics (Anonymize user data).
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.anonymizeUser({} as AFAnonymizeUser);
```
### `stop`
[Section titled âstopâ](#stop)
Once this API is invoked, our SDK no longer communicates with our servers and stops functioning. Useful when implementing user opt-in/opt-out.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.stop();
```
### `disableSKAdNetwork`
[Section titled âdisableSKAdNetworkâ](#disableskadnetwork)
Opt-out of SKAdNetwork
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.disableSKAdNetwork({} as AFDisable);
```
### `disableAdvertisingIdentifier`
[Section titled âdisableAdvertisingIdentifierâ](#disableadvertisingidentifier)
Disables collection of various Advertising IDs by the SDK. This includes Apple Identity for Advertisers (IDFA), Google Advertising ID (GAID), OAID and Amazon Advertising ID (AAID).
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.disableAdvertisingIdentifier({} as AFDisable);
```
### `disableCollectASA`
[Section titled âdisableCollectASAâ](#disablecollectasa)
Opt-out of Apple Search Ads attributions.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.disableCollectASA({} as AFDisable);
```
### `setHost`
[Section titled âsetHostâ](#sethost)
Set a custom host.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setHost({} as AFHost);
```
### `generateInviteLink`
[Section titled âgenerateInviteLinkâ](#generateinvitelink)
Allowing your existing users to invite their friends and contacts as new users to your app
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.generateInviteLink({} as AFLinkGenerator);
```
### `validateAndLogInAppPurchaseAndroid`
[Section titled âvalidateAndLogInAppPurchaseAndroidâ](#validateandloginapppurchaseandroid)
API for server verification of in-app purchases. An af\_purchase event with the relevant values will be automatically logged if the validation is successful.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.validateAndLogInAppPurchaseAndroid({} as AFAndroidInAppPurchase);
```
### `validateAndLogInAppPurchaseIos`
[Section titled âvalidateAndLogInAppPurchaseIosâ](#validateandloginapppurchaseios)
See the source definitions for the current contract.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.validateAndLogInAppPurchaseIos({} as AFIosInAppPurchase);
```
### `getSdkVersion`
[Section titled âgetSdkVersionâ](#getsdkversion)
Get the AppsFlyer SDK version used in app.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.getSdkVersion();
```
### `enableFacebookDeferredApplinks`
[Section titled âenableFacebookDeferredApplinksâ](#enablefacebookdeferredapplinks)
Enable the collection of Facebook Deferred AppLinks. Requires Facebook SDK and Facebook app on target/client device. This API must be invoked before initializing the AppsFlyer SDK in order to function properly.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.enableFacebookDeferredApplinks({} as AFFbDAL);
```
### `sendPushNotificationData`
[Section titled âsendPushNotificationDataâ](#sendpushnotificationdata)
Measure and get data from push-notification campaigns.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.sendPushNotificationData({} as AFPushPayload);
```
### `setCurrentDeviceLanguage`
[Section titled âsetCurrentDeviceLanguageâ](#setcurrentdevicelanguage)
Set the language of the device. The data will be displayed in Raw Data Reports
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setCurrentDeviceLanguage({} as AFLanguage);
```
### `logCrossPromoteImpression`
[Section titled âlogCrossPromoteImpressionâ](#logcrosspromoteimpression)
Logs an impression as part of a cross-promotion campaign. Make sure to use the promoted app ID as it appears in the AppsFlyer dashboard.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.logCrossPromoteImpression({} as AFPromotion);
```
### `setUserEmails`
[Section titled âsetUserEmailsâ](#setuseremails)
Set the user emails and encrypt them.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setUserEmails({} as AFEmails);
```
### `logLocation`
[Section titled âlogLocationâ](#loglocation)
Manually log the location of the user
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.logLocation({} as AFLatLng);
```
### `setPhoneNumber`
[Section titled âsetPhoneNumberâ](#setphonenumber)
Will be sent as an SHA-256 encrypted string.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setPhoneNumber({} as AFPhone);
```
### `setPartnerData`
[Section titled âsetPartnerDataâ](#setpartnerdata)
Allows sending custom data for partner integration purposes.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setPartnerData({} as AFPartnerData);
```
### `logInvite`
[Section titled âlogInviteâ](#loginvite)
Use to log a user-invite in-app event (af\_invite).
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.logInvite({} as AFLogInvite);
```
### `setDisableNetworkData`
[Section titled âsetDisableNetworkDataâ](#setdisablenetworkdata)
Use to opt-out of collecting the network operator name (carrier) and sim operator name from the device.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setDisableNetworkData({} as AFDisable);
```
### `enableTCFDataCollection`
[Section titled âenableTCFDataCollectionâ](#enabletcfdatacollection)
Use to opt-in/out the automatic collection of consent data, for users who use a CMP. Flag value will be persisted between app sessions.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.enableTCFDataCollection({} as AFEnableTCFDataCollection);
```
### `setConsentData`
[Section titled âsetConsentDataâ](#setconsentdata)
Use this to set user consent data manually. If your app doesnât use a CMP compatible with TCF v2.2, use the following method to manually provide the consent data directly to the SDK.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setConsentData({} as AFConsentData);
```
### `logAdRevenue`
[Section titled âlogAdRevenueâ](#logadrevenue)
By attributing ad revenue, app owners gain the complete view of user LTV and campaign ROI. Ad revenue is generated by displaying ads on rewarded videos, offer walls, interstitials, and banners in an app. You can use this method to log your ad revenue.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.logAdRevenue({} as AFAdRevenueData);
```
### `setConsentDataV2`
[Section titled âsetConsentDataV2â](#setconsentdatav2)
Use this to set user consent data manually. If your app doesnât use a CMP compatible with TCF v2.2, use the following method to manually provide the consent data directly to the SDK.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.setConsentDataV2({} as AFConsentOptions);
```
### `isSDKStarted`
[Section titled âisSDKStartedâ](#issdkstarted)
Use this method to check whether the AppsFlyer SDK has already been started in the current session.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.isSDKStarted();
```
### `isSDKStopped`
[Section titled âisSDKStoppedâ](#issdkstopped)
Use this method to check whether the AppsFlyer SDK is currently stopped.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.isSDKStopped();
```
### `disableAppSetId`
[Section titled âdisableAppSetIdâ](#disableappsetid)
Disables AppSet ID collection. If called before SDK init, App Set ID will not be collected. If called after init, App Set ID will be collected but not sent in request payloads. Android only.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.disableAppSetId();
```
### `validateAndLogInAppPurchaseV2`
[Section titled âvalidateAndLogInAppPurchaseV2â](#validateandloginapppurchasev2)
API for server verification of in-app purchases V2. An af\_purchase event with the relevant values will be automatically logged if the validation is successful.
```typescript
import { AppsFlyer } from '@capgo/capacitor-appsflyer';
await AppsFlyer.validateAndLogInAppPurchaseV2({} as AFPurchaseDetailsV2);
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-audio-recorder
> Capacitor plugin contract for recording audio.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin contract for recording audio.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startRecording` - Start recording audio using the device microphone.
* `pauseRecording` - Pause the ongoing recording. Only available on Android (API 24+), iOS, and Web.
* `resumeRecording` - Resume a previously paused recording.
* `stopRecording` - Stop the current recording and persist the recorded audio.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------- | ----------------------------------------------------------------------------------------------------- |
| `startRecording` | Start recording audio using the device microphone. |
| `pauseRecording` | Pause the ongoing recording. Only available on Android (API 24+), iOS, and Web. |
| `resumeRecording` | Resume a previously paused recording. |
| `stopRecording` | Stop the current recording and persist the recorded audio. |
| `cancelRecording` | Cancel the current recording and discard any captured audio. |
| `getRecordingStatus` | Retrieve the current recording status. |
| `getCurrentAmplitude` | Retrieve the current input amplitude (microphone level) as a normalized number in the `[0, 1]` range. |
| `checkPermissions` | Return the current permission state for accessing the microphone. |
| `requestPermissions` | Request permission to access the microphone. |
| `addListener` | Listen for recording errors. |
| `addListener` | Listen for pause events emitted when a recording is paused. |
| `addListener` | Listen for recording completion events. |
| `removeAllListeners` | Remove all registered listeners. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-audio-recorder](https://github.com/Cap-go/capacitor-audio-recorder/).
# Getting Started
> Install @capgo/capacitor-audio-recorder and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-audio-recorder
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `startRecording`
[Section titled âstartRecordingâ](#startrecording)
Start recording audio using the device microphone.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.startRecording();
```
### `pauseRecording`
[Section titled âpauseRecordingâ](#pauserecording)
Pause the ongoing recording. Only available on Android (API 24+), iOS, and Web.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.pauseRecording();
```
### `resumeRecording`
[Section titled âresumeRecordingâ](#resumerecording)
Resume a previously paused recording.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.resumeRecording();
```
### `stopRecording`
[Section titled âstopRecordingâ](#stoprecording)
Stop the current recording and persist the recorded audio.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.stopRecording();
```
### `cancelRecording`
[Section titled âcancelRecordingâ](#cancelrecording)
Cancel the current recording and discard any captured audio.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.cancelRecording();
```
### `getRecordingStatus`
[Section titled âgetRecordingStatusâ](#getrecordingstatus)
Retrieve the current recording status.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.getRecordingStatus();
```
### `getCurrentAmplitude`
[Section titled âgetCurrentAmplitudeâ](#getcurrentamplitude)
Retrieve the current input amplitude (microphone level) as a normalized number in the `[0, 1]` range.
Intended for driving live visualizations such as VU meters or waveforms while recording. Returns `0` when no recording is active. Designed for UI-rate polling â a 60â100 ms interval is a good starting point for a waveform. Avoid calling it in a tight loop; each call crosses the JS/native bridge.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.getCurrentAmplitude();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Return the current permission state for accessing the microphone.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission to access the microphone.
```typescript
import { CapacitorAudioRecorder } from '@capgo/capacitor-audio-recorder';
await CapacitorAudioRecorder.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `StartRecordingOptions`
[Section titled âStartRecordingOptionsâ](#startrecordingoptions)
Options accepted by .
```typescript
export interface StartRecordingOptions {
/**
* The audio session category options for recording. Only available on iOS.
*
* @since 1.0.0
*/
audioSessionCategoryOptions?: AudioSessionCategoryOption[];
/**
* The audio session mode for recording. Only available on iOS.
*
* @since 1.0.0
*/
audioSessionMode?: AudioSessionMode;
/**
* The audio bit rate in bytes per second.
* Only available on Android and iOS.
*
* @since 1.0.0
*/
bitRate?: number;
/**
* The audio sample rate in Hz.
* Only available on Android and iOS.
*
* @since 1.0.0
*/
sampleRate?: number;
}
```
### `StopRecordingResult`
[Section titled âStopRecordingResultâ](#stoprecordingresult)
Result returned by .
```typescript
export interface StopRecordingResult {
/**
* The recorded audio as a Blob. Only available on Web.
*
* @since 1.0.0
*/
blob?: Blob;
/**
* The duration of the recording in milliseconds.
*
* @since 1.0.0
*/
duration?: number;
/**
* The URI pointing to the recorded file. Only available on Android and iOS.
*
* @since 1.0.0
*/
uri?: string;
}
```
### `GetRecordingStatusResult`
[Section titled âGetRecordingStatusResultâ](#getrecordingstatusresult)
Result returned by .
```typescript
export interface GetRecordingStatusResult {
/**
* The current recording status.
*
* @since 1.0.0
*/
status: RecordingStatus;
}
```
### `GetCurrentAmplitudeResult`
[Section titled âGetCurrentAmplitudeResultâ](#getcurrentamplituderesult)
Result returned by .
```typescript
export interface GetCurrentAmplitudeResult {
/**
* The current input amplitude normalized to the `[0, 1]` range, where `0`
* represents silence and `1` represents the maximum level the platform can
* report. The value is `0` when no recording is active.
*
* Note: the source signal differs between platforms â Android reports the
* peak sample amplitude since the last call, iOS reports the average power
* in dB converted to linear, and Web reports the RMS of the latest frame.
* Consumers that need cross-platform parity may want to apply a
* per-platform scaling curve.
*
* @since 8.1.0
*/
value: number;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission information returned by and .
```typescript
export interface PermissionStatus {
/**
* The permission state for audio recording.
*
* @since 1.0.0
*/
recordAudio: PermissionState;
}
```
### `RecordingErrorEvent`
[Section titled âRecordingErrorEventâ](#recordingerrorevent)
Event emitted when an error occurs during recording.
```typescript
export interface RecordingErrorEvent {
/**
* The error message.
*
* @since 1.0.0
*/
message: string;
}
```
### `RecordingStoppedEvent`
[Section titled âRecordingStoppedEventâ](#recordingstoppedevent)
Event emitted when a recording completes.
```typescript
export type RecordingStoppedEvent = StopRecordingResult;
```
### `AudioSessionCategoryOption`
[Section titled âAudioSessionCategoryOptionâ](#audiosessioncategoryoption)
Audio session category options available on iOS.
```typescript
export enum AudioSessionCategoryOption {
AllowAirPlay = 'ALLOW_AIR_PLAY',
AllowBluetooth = 'ALLOW_BLUETOOTH',
AllowBluetoothA2DP = 'ALLOW_BLUETOOTH_A2DP',
DefaultToSpeaker = 'DEFAULT_TO_SPEAKER',
DuckOthers = 'DUCK_OTHERS',
InterruptSpokenAudioAndMixWithOthers = 'INTERRUPT_SPOKEN_AUDIO_AND_MIX_WITH_OTHERS',
MixWithOthers = 'MIX_WITH_OTHERS',
OverrideMutedMicrophoneInterruption = 'OVERRIDE_MUTED_MICROPHONE_INTERRUPTION',
}
```
### `AudioSessionMode`
[Section titled âAudioSessionModeâ](#audiosessionmode)
Audio session modes available on iOS.
```typescript
export enum AudioSessionMode {
Default = 'DEFAULT',
GameChat = 'GAME_CHAT',
Measurement = 'MEASUREMENT',
SpokenAudio = 'SPOKEN_AUDIO',
VideoChat = 'VIDEO_CHAT',
VideoRecording = 'VIDEO_RECORDING',
VoiceChat = 'VOICE_CHAT',
}
```
### `RecordingStatus`
[Section titled âRecordingStatusâ](#recordingstatus)
The recording status.
```typescript
export enum RecordingStatus {
Inactive = 'INACTIVE',
Recording = 'RECORDING',
Paused = 'PAUSED',
}
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Platform permission states supported by Capacitor.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-audio-session
> iOS-only plugin to query and control the audio session output and listen to route changes and interruptions.
## Overview
[Section titled âOverviewâ](#overview)
iOS-only plugin to query and control the audio session output and listen to route changes and interruptions.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `currentOutputs` - Get the current active audio output routes.
* `overrideOutput` - Override the current audio output route.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | -------------------------------------------------------------------------- |
| `currentOutputs` | Get the current active audio output routes. |
| `overrideOutput` | Override the current audio output route. |
| `addListener` | Listen for audio route changes (e.g. headset connected/disconnected). |
| `addListener` | Listen for audio session interruptions (e.g. incoming call) and their end. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-audiosession](https://github.com/Cap-go/capacitor-audiosession/).
# Getting Started
> Install @capgo/capacitor-audio-session and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-audio-session
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { AudioSession } from '@capgo/capacitor-audio-session';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `currentOutputs`
[Section titled âcurrentOutputsâ](#currentoutputs)
Get the current active audio output routes.
On web and non-iOS platforms, this resolves to an empty array.
```typescript
import { AudioSession } from '@capgo/capacitor-audio-session';
await AudioSession.currentOutputs();
```
### `overrideOutput`
[Section titled âoverrideOutputâ](#overrideoutput)
Override the current audio output route.
Use `speaker` to force playback through the built-in speaker, or `default` to restore the system-selected route.
```typescript
import { AudioSession } from '@capgo/capacitor-audio-session';
await AudioSession.overrideOutput({} as OutputOverrideType);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AudioSessionPorts`
[Section titled âAudioSessionPortsâ](#audiosessionports)
Available audio output routes on iOS.
```typescript
export enum AudioSessionPorts {
AIR_PLAY = 'airplay',
BLUETOOTH_LE = 'bluetooth-le',
BLUETOOTH_HFP = 'bluetooth-hfp',
BLUETOOTH_A2DP = 'bluetooth-a2dp',
BUILT_IN_SPEAKER = 'builtin-speaker',
BUILT_IN_RECEIVER = 'builtin-receiver',
HDMI = 'hdmi',
HEADPHONES = 'headphones',
LINE_OUT = 'line-out',
}
```
### `OutputOverrideType`
[Section titled âOutputOverrideTypeâ](#outputoverridetype)
Output override type. - `default`: Use the system-selected route. - `speaker`: Force playback through the built-in speaker.
```typescript
export type OutputOverrideType = 'default' | 'speaker';
```
### `OverrideResult`
[Section titled âOverrideResultâ](#overrideresult)
Result of an output override request.
```typescript
export type OverrideResult = {
success: boolean;
message: string;
};
```
### `RouteChangeListener`
[Section titled âRouteChangeListenerâ](#routechangelistener)
Listener called when the audio route changes.
```typescript
export type RouteChangeListener = (reason: RouteChangeReasons) => void;
```
### `InterruptionListener`
[Section titled âInterruptionListenerâ](#interruptionlistener)
Listener called when the audio session is interrupted or ends.
```typescript
export type InterruptionListener = (type: InterruptionTypes) => void;
```
### `RouteChangeReasons`
[Section titled âRouteChangeReasonsâ](#routechangereasons)
```typescript
export enum RouteChangeReasons {
NEW_DEVICE_AVAILABLE = 'new-device-available',
OLD_DEVICE_UNAVAILABLE = 'old-device-unavailable',
CATEGORY_CHANGE = 'category-change',
OVERRIDE = 'override',
WAKE_FROM_SLEEP = 'wake-from-sleep',
NO_SUITABLE_ROUTE_FOR_CATEGORY = 'no-suitable-route-for-category',
ROUTE_CONFIGURATION_CHANGE = 'route-config-change',
UNKNOWN = 'unknown',
}
```
### `InterruptionTypes`
[Section titled âInterruptionTypesâ](#interruptiontypes)
```typescript
export enum InterruptionTypes {
BEGAN = 'began',
ENDED = 'ended',
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-autofill-save-password
> Prompt to display dialog for saving password to keychain from webview app.
## Overview
[Section titled âOverviewâ](#overview)
Prompt to display dialog for saving password to keychain from webview app.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `promptDialog` - Save a password to the keychain.
* `readPassword` - Read a password from the keychain. Requires the developer to setup associated domain for the app for iOS.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| `promptDialog` | Save a password to the keychain. |
| `readPassword` | Read a password from the keychain. Requires the developer to setup associated domain for the app for iOS. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-autofill-save-password](https://github.com/Cap-go/capacitor-autofill-save-password/).
# Getting Started
> Install @capgo/capacitor-autofill-save-password and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-autofill-save-password
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { SavePassword } from '@capgo/capacitor-autofill-save-password';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `promptDialog`
[Section titled âpromptDialogâ](#promptdialog)
Save a password to the keychain.
```typescript
import { SavePassword } from '@capgo/capacitor-autofill-save-password';
await SavePassword.promptDialog({
username: 'your-username',
password: 'your-password'
});
```
### `readPassword`
[Section titled âreadPasswordâ](#readpassword)
Read a password from the keychain. Requires the developer to setup associated domain for the app for iOS.
```typescript
import { SavePassword } from '@capgo/capacitor-autofill-save-password';
await SavePassword.readPassword();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `Options`
[Section titled âOptionsâ](#options)
```typescript
export interface Options {
/**
* The username to save.
*/
username: string;
/**
* The password to save.
*/
password: string;
/**
* The url to save the password for. (For example: "console.capgo.app")
* iOS only.
*/
url?: string;
}
```
### `ReadPasswordResult`
[Section titled âReadPasswordResultâ](#readpasswordresult)
```typescript
export interface ReadPasswordResult {
/**
* The username of the password.
*/
username: string;
/**
* The password of the password.
*/
password: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/background-geolocation
> Accurate background location tracking, native geofence enter/exit events, and transition webhooks for Capacitor apps.
## Overview
[Section titled âOverviewâ](#overview)
Use `@capgo/background-geolocation` when your Capacitor app needs precise location updates in the foreground or background, native circular geofences on iOS and Android, and backend delivery for geofence transitions when the WebView is suspended.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `start` - Stream accurate foreground or background location updates.
* `stop` - Stop active location tracking cleanly.
* `openSettings` - Send users to native location settings when permissions need attention.
* `setPlannedRoute` - Play a native sound when the user deviates from a planned route.
* `setupGeofencing` - Configure native geofence defaults and optional transition webhook delivery.
* `addGeofence` - Monitor a circular iOS or Android geofence region by identifier.
* `removeGeofence` / `removeAllGeofences` - Stop monitoring one or all registered geofences.
* `getMonitoredGeofences` - List region identifiers currently monitored by the native layer.
* `geofenceTransition` listener - Receive enter and exit events while the app is active.
* `geofenceError` listener - Handle native monitoring errors without changing the transition event shape.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `start` | Streams accurate foreground or background location updates. |
| `stop` | Stops location updates. |
| `openSettings` | Opens the deviceâs location settings page. Useful for directing users to enable location services or adjust permissions. |
| `setPlannedRoute` | Plays a native sound when the user deviates from a planned route. |
| `setupGeofencing` | Configures geofence defaults and optional native transition POST delivery. |
| `addGeofence` | Starts monitoring a circular geofence on iOS and Android. |
| `removeGeofence` | Stops monitoring one geofence by identifier. |
| `removeAllGeofences` | Stops monitoring all geofences registered by this plugin. |
| `getMonitoredGeofences` | Returns the identifiers currently monitored by the native layer. |
| `addListener('geofenceTransition', ...)` | Receives geofence enter and exit events while the app is alive. |
| `addListener('geofenceError', ...)` | Receives native geofence monitoring errors while the app is alive. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-background-geolocation](https://github.com/Cap-go/capacitor-background-geolocation/).
# Getting Started
> Install @capgo/background-geolocation for background location tracking and native geofencing.
`@capgo/background-geolocation` combines precise background location tracking with native geofencing for iOS and Android. Use it for delivery zones, stores, job sites, campuses, check-ins, route alerts, and any workflow that needs enter or exit events even when the WebView is not running.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/background-geolocation
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `start`
[Section titled âstartâ](#start)
To start listening for changes in the deviceâs location, call this method. A Promise is returned to indicate that it finished the call. The callback will be called every time a new location is available, or if there was an error when calling this method. Donât rely on promise rejection for this.
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.start(
{
backgroundMessage: "App is using your location in the background",
backgroundTitle: "Location Service",
requestPermissions: true,
stale: false,
distanceFilter: 10
},
(location, error) => {
if (error) {
console.error('Location error:', error);
return;
}
if (location) {
console.log('New location:', location.latitude, location.longitude);
}
}
);
```
### `stop`
[Section titled âstopâ](#stop)
Stops location updates.
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.stop();
```
### `openSettings`
[Section titled âopenSettingsâ](#opensettings)
Opens the deviceâs location settings page. Useful for directing users to enable location services or adjust permissions.
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
// Direct user to location settings
await BackgroundGeolocation.openSettings();
```
### `setPlannedRoute`
[Section titled âsetPlannedRouteâ](#setplannedroute)
Plays a sound file when the user deviates from the planned route. This should be used to play a sound (in the background too, only for native).
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.setPlannedRoute({
soundFile: "notification.mp3",
route: [[-74.0060, 40.7128], [-118.2437, 34.0522]]
});
```
### Native geofencing
[Section titled âNative geofencingâ](#native-geofencing)
Geofencing runs in the native layer, so iOS and Android can trigger enter and exit events without relying on the WebView to stay awake. Configure an HTTP or HTTPS webhook URL when your backend must receive transitions even while the app UI is suspended.
```typescript
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.setupGeofencing({
url: 'https://api.example.com/geofences',
notifyOnEntry: true,
notifyOnExit: true,
payload: { userId: '123' },
});
await BackgroundGeolocation.addGeofence({
identifier: 'store-42',
latitude: 37.33182,
longitude: -122.03118,
radius: 150,
payload: { storeId: '42' },
});
const handle = await BackgroundGeolocation.addListener(
'geofenceTransition',
(event) => {
console.log(event.identifier, event.transition);
},
);
const errorHandle = await BackgroundGeolocation.addListener(
'geofenceError',
(event) => {
console.error(event.identifier, event.message);
},
);
const { regions } = await BackgroundGeolocation.getMonitoredGeofences();
console.log(regions);
await BackgroundGeolocation.removeGeofence({ identifier: 'store-42' });
await handle.remove();
await errorHandle.remove();
```
On iOS, geofencing requires Always location authorization. On Android 10 and newer, add background location permission to your app manifest when you need background geofencing:
```xml
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `StartOptions`
[Section titled âStartOptionsâ](#startoptions)
The options for configuring for location updates.
```typescript
export interface StartOptions {
/**
* If the "backgroundMessage" option is defined, the plugin will
* provide location updates whether the app is in the background or the
* foreground. If it is not defined, location updates are only
* guaranteed in the foreground. This is true on both platforms.
*
* On Android, a notification must be shown to continue receiving
* location updates in the background. This option specifies the text of
* that notification.
*
* @since 7.0.9
* @example "Getting your location to provide better service"
*/
backgroundMessage?: string;
/**
* The title of the notification mentioned above.
*
* @since 7.0.9
* @default "Using your location"
* @example "Location Service"
*/
backgroundTitle?: string;
/**
* Whether permissions should be requested from the user automatically,
* if they are not already granted.
*
* @since 7.0.9
* @default true
* @example
* // Auto-request permissions
* requestPermissions: true
*
* // Don't auto-request, handle manually
* requestPermissions: false
*/
requestPermissions?: boolean;
/**
* If "true", stale locations may be delivered while the device
* obtains a GPS fix. You are responsible for checking the "time"
* property. If "false", locations are guaranteed to be up to date.
*
* @since 7.0.9
* @default false
* @example
* // Allow stale locations for faster initial response
* stale: true
*
* // Only fresh locations
* stale: false
*/
stale?: boolean;
/**
* The distance in meters that the device must move before a new location update is triggered.
* This is used to filter out small movements and reduce the number of updates.
*
* @since 7.0.9
* @default 0
* @example
* // Update every 10 meters
* distanceFilter: 10
*
* // Update on any movement
* distanceFilter: 0
*/
distanceFilter?: number;
}
```
### `Location`
[Section titled âLocationâ](#location)
Represents a geographical location with various attributes. Contains all the standard location properties returned by GPS/network providers.
```typescript
export interface Location {
/**
* Latitude in degrees.
* Range: -90.0 to +90.0
*
* @since 7.0.0
* @example 40.7128
*/
latitude: number;
/**
* Longitude in degrees.
* Range: -180.0 to +180.0
*
* @since 7.0.0
* @example -74.0060
*/
longitude: number;
/**
* Radius of horizontal uncertainty in metres, with 68% confidence.
* Lower values indicate more accurate location.
*
* @since 7.0.0
* @example 5.0
*/
accuracy: number;
/**
* Metres above sea level (or null if not available).
*
* @since 7.0.0
* @example 10.5
*/
altitude: number | null;
/**
* Vertical uncertainty in metres, with 68% confidence (or null if not available).
*
* @since 7.0.0
* @example 3.0
*/
altitudeAccuracy: number | null;
/**
* `true` if the location was simulated by software, rather than GPS.
* Useful for detecting mock locations in development or testing.
*
* @since 7.0.0
* @example false
*/
simulated: boolean;
/**
* Deviation from true north in degrees (or null if not available).
* Range: 0.0 to 360.0
*
* @since 7.0.0
* @example 45.5
*/
bearing: number | null;
/**
* Speed in metres per second (or null if not available).
*
* @since 7.0.0
* @example 2.5
*/
speed: number | null;
/**
* Time the location was produced, in milliseconds since the unix epoch.
* Use this to check if a location is stale when using stale: true.
*
* @since 7.0.0
* @example 1640995200000
*/
time: number | null;
}
```
### `CallbackError`
[Section titled âCallbackErrorâ](#callbackerror)
Error object that may be passed to the location start callback. Extends the standard Error with optional error codes.
```typescript
export interface CallbackError extends Error {
/**
* Optional error code for more specific error handling.
*
* @since 7.0.0
* @example "PERMISSION_DENIED"
*/
code?: string;
}
```
### `SetPlannedRouteOptions`
[Section titled âSetPlannedRouteOptionsâ](#setplannedrouteoptions)
```typescript
export interface SetPlannedRouteOptions {
/**
* The name of the sound file to play.
* Must be a valid sound relative path in the app's public folder to work for both web and native platforms.
* There's no need to include the public folder in the path.
* @since 7.0.10
* @example "notification.mp3"
* */
soundFile: string;
/**
* The planned route as an array of longitude and latitude pairs.
* Each pair represents a point on the route.
* This is used to define a route that the user can follow.
* The route is used to play a sound when the user deviates from it.
* @since 7.0.11
* @example [[-74.0060, 40.7128], [-118.2437, 34.0522]]
*/
route: [number, number][];
/**
* The distance in meters that the user must deviate from the planned route to trigger the sound.
* This is used to determine how far off the route the user can be before the sound is played.
* If not specified, a default value of 50 meters is used.
* @since 7.0.11
* @default 50
* @example 50
*/
distance: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-barometer
> Capacitor plugin contract for working with the device barometer sensor.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin contract for working with the device barometer sensor.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getMeasurement` - Get the most recent barometer reading captured by the native layer.
* `isAvailable` - Check if the current device includes a barometer sensor.
* `startMeasurementUpdates` - Begin streaming barometer updates to the JavaScript layer.
* `stopMeasurementUpdates` - Stop the continuous updates started via .
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------- | ------------------------------------------------------------------------ |
| `getMeasurement` | Get the most recent barometer reading captured by the native layer. |
| `isAvailable` | Check if the current device includes a barometer sensor. |
| `startMeasurementUpdates` | Begin streaming barometer updates to the JavaScript layer. |
| `stopMeasurementUpdates` | Stop the continuous updates started via . |
| `checkPermissions` | Return the current permission state for accessing barometer data. |
| `requestPermissions` | Request permission to access barometer data if required by the platform. |
| `addListener` | Listen for pressure updates. |
| `removeAllListeners` | Remove all registered listeners for this plugin. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-barometer](https://github.com/Cap-go/capacitor-barometer/).
# Getting Started
> Install @capgo/capacitor-barometer and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-barometer
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getMeasurement`
[Section titled âgetMeasurementâ](#getmeasurement)
Get the most recent barometer reading captured by the native layer.
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.getMeasurement();
```
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if the current device includes a barometer sensor.
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.isAvailable();
```
### `startMeasurementUpdates`
[Section titled âstartMeasurementUpdatesâ](#startmeasurementupdates)
Begin streaming barometer updates to the JavaScript layer.
Call with the `measurement` event to receive the updates.
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.startMeasurementUpdates();
```
### `stopMeasurementUpdates`
[Section titled âstopMeasurementUpdatesâ](#stopmeasurementupdates)
Stop the continuous updates started via .
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.stopMeasurementUpdates();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Return the current permission state for accessing barometer data.
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission to access barometer data if required by the platform.
```typescript
import { CapacitorBarometer } from '@capgo/capacitor-barometer';
await CapacitorBarometer.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetMeasurementResult`
[Section titled âGetMeasurementResultâ](#getmeasurementresult)
Alias for the most recent pressure sample.
```typescript
export type GetMeasurementResult = Measurement;
```
### `IsAvailableResult`
[Section titled âIsAvailableResultâ](#isavailableresult)
Result returned by .
```typescript
export interface IsAvailableResult {
/**
* Indicates whether the device exposes a barometer sensor.
*
* @since 1.0.0
*/
isAvailable: boolean;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission information returned by and .
```typescript
export interface PermissionStatus {
/**
* The permission state for accessing barometer measurements on the current platform.
*
* @since 1.0.0
*/
barometer: BarometerPermissionState;
}
```
### `MeasurementEvent`
[Section titled âMeasurementEventâ](#measurementevent)
Event payload emitted when is active.
```typescript
export type MeasurementEvent = Measurement;
```
### `Measurement`
[Section titled âMeasurementâ](#measurement)
Air pressure and relative altitude values sampled from the device barometer.
```typescript
export interface Measurement {
/**
* The static air pressure in hectopascals (hPa).
*
* @since 1.0.0
*/
pressure: number;
/**
* The change in altitude relative to the time updates started.
* Only available on iOS; Android will always return `0`.
*
* @since 1.0.0
*/
relativeAltitude: number;
/**
* The timestamp of the measurement in milliseconds since the Unix epoch.
*
* @since 1.0.0
*/
timestamp: number;
}
```
### `BarometerPermissionState`
[Section titled âBarometerPermissionStateâ](#barometerpermissionstate)
Permission state union including `limited` for platforms that can throttle sensor access.
```typescript
export type BarometerPermissionState = PermissionState | 'limited';
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Platform permission states supported by Capacitor.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-bluetooth-low-energy
> Capacitor Bluetooth Low Energy Plugin for BLE communication.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Bluetooth Low Energy Plugin for BLE communication.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `initialize` - Initialize the BLE plugin. Must be called before any other method.
* `shimWebBluetooth` - Install the Capacitor Web Bluetooth shim on `navigator.bluetooth`. Call this manually before using the Web Bluetooth API from a Capacitor native app.
* `isAvailable` - Check if Bluetooth is available on the device.
* `isEnabled` - Check if Bluetooth is enabled on the device.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initialize` | Initialize the BLE plugin. Must be called before any other method. |
| `shimWebBluetooth` | Install the Capacitor Web Bluetooth shim on `navigator.bluetooth`. Call this manually before using the Web Bluetooth API from a Capacitor native app. |
| `isAvailable` | Check if Bluetooth is available on the device. |
| `isEnabled` | Check if Bluetooth is enabled on the device. |
| `isLocationEnabled` | Check if location services are enabled (Android only). |
| `openAppSettings` | Open the app settings page. |
| `openBluetoothSettings` | Open the Bluetooth settings page (Android only). |
| `openLocationSettings` | Open the location settings page (Android only). |
| `checkPermissions` | Check the current permission status. |
| `requestPermissions` | Request Bluetooth permissions. |
| `startScan` | Start scanning for BLE devices. |
| `stopScan` | Stop scanning for BLE devices. |
| `connect` | Connect to a BLE device. |
| `disconnect` | Disconnect from a BLE device. |
| `createBond` | Create a bond with a BLE device (Android only). |
| `isBonded` | Check if a device is bonded (Android only). |
| `discoverServices` | Discover services on a connected device. |
| `getServices` | Get discovered services for a device. |
| `getConnectedDevices` | Get a list of connected devices. |
| `readCharacteristic` | Read a characteristic value. |
| `writeCharacteristic` | Write a value to a characteristic. |
| `startCharacteristicNotifications` | Start notifications for a characteristic. |
| `stopCharacteristicNotifications` | Stop notifications for a characteristic. |
| `readDescriptor` | Read a descriptor value. |
| `writeDescriptor` | Write a value to a descriptor. |
| `readRssi` | Read the RSSI (signal strength) of a connected device. |
| `requestMtu` | Request MTU size change (Android only). |
| `requestConnectionPriority` | Request connection priority (Android only). |
| `startAdvertising` | Start advertising as a peripheral (BLE server). |
| `stopAdvertising` | Stop advertising. |
| `startForegroundService` | Start a foreground service to maintain BLE connections in background (Android only). |
| `stopForegroundService` | Stop the foreground service (Android only). |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `addListener` | Add a listener for device scanned events. |
| `addListener` | Add a listener for device connected events. |
| `addListener` | Add a listener for device disconnected events. |
| `addListener` | Add a listener for characteristic changed events. |
| `removeAllListeners` | Remove all listeners for this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-bluetooth-low-energy](https://github.com/Cap-go/capacitor-bluetooth-low-energy/).
# Getting Started
> Install @capgo/capacitor-bluetooth-low-energy and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-bluetooth-low-energy
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `initialize`
[Section titled âinitializeâ](#initialize)
Initialize the BLE plugin. Must be called before any other method.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });
```
### `shimWebBluetooth`
[Section titled âshimWebBluetoothâ](#shimwebbluetooth)
Install the Capacitor Web Bluetooth shim on `navigator.bluetooth`. Call this manually before using the Web Bluetooth API from a Capacitor native app.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();
```
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if Bluetooth is available on the device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();
```
### `isEnabled`
[Section titled âisEnabledâ](#isenabled)
Check if Bluetooth is enabled on the device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isEnabled();
```
### `isLocationEnabled`
[Section titled âisLocationEnabledâ](#islocationenabled)
Check if location services are enabled (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isLocationEnabled();
```
### `openAppSettings`
[Section titled âopenAppSettingsâ](#openappsettings)
Open the app settings page.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openAppSettings();
```
### `openBluetoothSettings`
[Section titled âopenBluetoothSettingsâ](#openbluetoothsettings)
Open the Bluetooth settings page (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openBluetoothSettings();
```
### `openLocationSettings`
[Section titled âopenLocationSettingsâ](#openlocationsettings)
Open the location settings page (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openLocationSettings();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission status.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request Bluetooth permissions.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.requestPermissions();
```
### `startScan`
[Section titled âstartScanâ](#startscan)
Start scanning for BLE devices.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startScan({
services: ['180D'], // Heart Rate Service
timeout: 10000
});
```
### `stopScan`
[Section titled âstopScanâ](#stopscan)
Stop scanning for BLE devices.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopScan();
```
### `connect`
[Section titled âconnectâ](#connect)
Connect to a BLE device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `disconnect`
[Section titled âdisconnectâ](#disconnect)
Disconnect from a BLE device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.disconnect({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `createBond`
[Section titled âcreateBondâ](#createbond)
Create a bond with a BLE device (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.createBond({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `isBonded`
[Section titled âisBondedâ](#isbonded)
Check if a device is bonded (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bonded } = await BluetoothLowEnergy.isBonded({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `discoverServices`
[Section titled âdiscoverServicesâ](#discoverservices)
Discover services on a connected device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.discoverServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `getServices`
[Section titled âgetServicesâ](#getservices)
Get discovered services for a device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { services } = await BluetoothLowEnergy.getServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `getConnectedDevices`
[Section titled âgetConnectedDevicesâ](#getconnecteddevices)
Get a list of connected devices.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { devices } = await BluetoothLowEnergy.getConnectedDevices();
```
### `readCharacteristic`
[Section titled âreadCharacteristicâ](#readcharacteristic)
Read a characteristic value.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { value } = await BluetoothLowEnergy.readCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});
```
### `writeCharacteristic`
[Section titled âwriteCharacteristicâ](#writecharacteristic)
Write a value to a characteristic.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.writeCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A39',
value: [0x01]
});
```
### `startCharacteristicNotifications`
[Section titled âstartCharacteristicNotificationsâ](#startcharacteristicnotifications)
Start notifications for a characteristic.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startCharacteristicNotifications({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});
```
### `stopCharacteristicNotifications`
[Section titled âstopCharacteristicNotificationsâ](#stopcharacteristicnotifications)
Stop notifications for a characteristic.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopCharacteristicNotifications({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});
```
### `readDescriptor`
[Section titled âreadDescriptorâ](#readdescriptor)
Read a descriptor value.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { value } = await BluetoothLowEnergy.readDescriptor({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37',
descriptor: '2902'
});
```
### `writeDescriptor`
[Section titled âwriteDescriptorâ](#writedescriptor)
Write a value to a descriptor.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.writeDescriptor({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37',
descriptor: '2902',
value: [0x01, 0x00]
});
```
### `readRssi`
[Section titled âreadRssiâ](#readrssi)
Read the RSSI (signal strength) of a connected device.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { rssi } = await BluetoothLowEnergy.readRssi({ deviceId: 'AA:BB:CC:DD:EE:FF' });
```
### `requestMtu`
[Section titled ârequestMtuâ](#requestmtu)
Request MTU size change (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { mtu } = await BluetoothLowEnergy.requestMtu({
deviceId: 'AA:BB:CC:DD:EE:FF',
mtu: 512
});
```
### `requestConnectionPriority`
[Section titled ârequestConnectionPriorityâ](#requestconnectionpriority)
Request connection priority (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.requestConnectionPriority({
deviceId: 'AA:BB:CC:DD:EE:FF',
priority: 'high'
});
```
### `startAdvertising`
[Section titled âstartAdvertisingâ](#startadvertising)
Start advertising as a peripheral (BLE server).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startAdvertising({
name: 'MyDevice',
services: ['180D']
});
```
### `stopAdvertising`
[Section titled âstopAdvertisingâ](#stopadvertising)
Stop advertising.
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopAdvertising();
```
### `startForegroundService`
[Section titled âstartForegroundServiceâ](#startforegroundservice)
Start a foreground service to maintain BLE connections in background (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startForegroundService({
title: 'BLE Connection',
body: 'Maintaining connection...'
});
```
### `stopForegroundService`
[Section titled âstopForegroundServiceâ](#stopforegroundservice)
Stop the foreground service (Android only).
```typescript
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopForegroundService();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `InitializeOptions`
[Section titled âInitializeOptionsâ](#initializeoptions)
Initialization options for the plugin.
```typescript
export interface InitializeOptions {
/**
* The mode to initialize the plugin in.
* - 'central': Act as a BLE central (client)
* - 'peripheral': Act as a BLE peripheral (server)
*
* @default 'central'
* @since 1.0.0
*/
mode?: 'central' | 'peripheral';
}
```
### `IsAvailableResult`
[Section titled âIsAvailableResultâ](#isavailableresult)
Result of the isAvailable method.
```typescript
export interface IsAvailableResult {
/**
* Whether Bluetooth is available on the device.
*
* @since 1.0.0
*/
available: boolean;
}
```
### `IsEnabledResult`
[Section titled âIsEnabledResultâ](#isenabledresult)
Result of the isEnabled method.
```typescript
export interface IsEnabledResult {
/**
* Whether Bluetooth is enabled on the device.
*
* @since 1.0.0
*/
enabled: boolean;
}
```
### `IsLocationEnabledResult`
[Section titled âIsLocationEnabledResultâ](#islocationenabledresult)
Result of the isLocationEnabled method.
```typescript
export interface IsLocationEnabledResult {
/**
* Whether location services are enabled on the device.
*
* @since 1.0.0
*/
enabled: boolean;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission status for Bluetooth and location.
```typescript
export interface PermissionStatus {
/**
* Bluetooth permission status.
*
* @since 1.0.0
*/
bluetooth: PermissionState;
/**
* Location permission status (Android only).
*
* @since 1.0.0
*/
location: PermissionState;
}
```
### `StartScanOptions`
[Section titled âStartScanOptionsâ](#startscanoptions)
Options for starting a scan.
```typescript
export interface StartScanOptions {
/**
* List of service UUIDs to filter by.
* Only devices advertising these services will be returned.
*
* @since 1.0.0
*/
services?: string[];
/**
* Scan timeout in milliseconds.
* Set to 0 for no timeout.
*
* @default 0
* @since 1.0.0
*/
timeout?: number;
/**
* Whether to allow duplicate scan results.
*
* @default false
* @since 1.0.0
*/
allowDuplicates?: boolean;
}
```
### `ConnectOptions`
[Section titled âConnectOptionsâ](#connectoptions)
Options for connecting to a device.
```typescript
export interface ConnectOptions {
/**
* The device ID (MAC address on Android, UUID on iOS).
*
* @since 1.0.0
*/
deviceId: string;
/**
* Whether to automatically connect when the device becomes available.
*
* @default false
* @since 1.0.0
*/
autoConnect?: boolean;
}
```
### `DisconnectOptions`
[Section titled âDisconnectOptionsâ](#disconnectoptions)
Options for disconnecting from a device.
```typescript
export interface DisconnectOptions {
/**
* The device ID to disconnect from.
*
* @since 1.0.0
*/
deviceId: string;
}
```
### `CreateBondOptions`
[Section titled âCreateBondOptionsâ](#createbondoptions)
Options for creating a bond.
```typescript
export interface CreateBondOptions {
/**
* The device ID to bond with.
*
* @since 1.0.0
*/
deviceId: string;
}
```
### `IsBondedOptions`
[Section titled âIsBondedOptionsâ](#isbondedoptions)
Options for checking bond status.
```typescript
export interface IsBondedOptions {
/**
* The device ID to check.
*
* @since 1.0.0
*/
deviceId: string;
}
```
### `IsBondedResult`
[Section titled âIsBondedResultâ](#isbondedresult)
Result of the isBonded method.
```typescript
export interface IsBondedResult {
/**
* Whether the device is bonded.
*
* @since 1.0.0
*/
bonded: boolean;
}
```
### `DiscoverServicesOptions`
[Section titled âDiscoverServicesOptionsâ](#discoverservicesoptions)
Options for discovering services.
```typescript
export interface DiscoverServicesOptions {
/**
* The device ID to discover services on.
*
* @since 1.0.0
*/
deviceId: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-brightness
> Control screen brightness on iOS and Android.
## Overview
[Section titled âOverviewâ](#overview)
Control screen brightness on iOS and Android.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getBrightness` - Get the current brightness level of the deviceâs main screen.
* `setBrightness` - Set the brightness level of the deviceâs main screen.
* `getSystemBrightness` - Get the system-wide screen brightness.
* `setSystemBrightness` - Set the system-wide screen brightness. Requires WRITE\_SETTINGS permission on Android. This also changes the brightness mode to MANUAL.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `getBrightness` | Get the current brightness level of the deviceâs main screen. |
| `setBrightness` | Set the brightness level of the deviceâs main screen. |
| `getSystemBrightness` | Get the system-wide screen brightness. |
| `setSystemBrightness` | Set the system-wide screen brightness. Requires WRITE\_SETTINGS permission on Android. This also changes the brightness mode to MANUAL. |
| `getSystemBrightnessMode` | Get the current system brightness mode (automatic or manual). Requires WRITE\_SETTINGS permission on Android. |
| `setSystemBrightnessMode` | Set the system brightness mode (automatic or manual). Requires WRITE\_SETTINGS permission on Android. |
| `isUsingSystemBrightness` | Check if the current activity is using the system-wide brightness value. |
| `restoreSystemBrightness` | Reset the brightness setting of the current activity to use the system-wide value. |
| `isAvailable` | Check if the Brightness API is available on the current device. |
| `checkPermissions` | Check userâs permissions for accessing system brightness. |
| `requestPermissions` | Request permissions for accessing system brightness. On Android, this opens the system settings to grant WRITE\_SETTINGS permission. |
| `getPluginVersion` | Get the native plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-brightness](https://github.com/Cap-go/capacitor-brightness/).
# Getting Started
> Install @capgo/capacitor-brightness and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-brightness
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getBrightness`
[Section titled âgetBrightnessâ](#getbrightness)
Get the current brightness level of the deviceâs main screen.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.getBrightness();
```
### `setBrightness`
[Section titled âsetBrightnessâ](#setbrightness)
Set the brightness level of the deviceâs main screen.
On iOS, the brightness will persist until the device is locked. On Android, the brightness only applies to the current activity.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.setBrightness({} as SetBrightnessOptions);
```
### `getSystemBrightness`
[Section titled âgetSystemBrightnessâ](#getsystembrightness)
Get the system-wide screen brightness.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.getSystemBrightness();
```
### `setSystemBrightness`
[Section titled âsetSystemBrightnessâ](#setsystembrightness)
Set the system-wide screen brightness. Requires WRITE\_SETTINGS permission on Android. This also changes the brightness mode to MANUAL.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.setSystemBrightness({} as SetBrightnessOptions);
```
### `getSystemBrightnessMode`
[Section titled âgetSystemBrightnessModeâ](#getsystembrightnessmode)
Get the current system brightness mode (automatic or manual). Requires WRITE\_SETTINGS permission on Android.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.getSystemBrightnessMode();
```
### `setSystemBrightnessMode`
[Section titled âsetSystemBrightnessModeâ](#setsystembrightnessmode)
Set the system brightness mode (automatic or manual). Requires WRITE\_SETTINGS permission on Android.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.setSystemBrightnessMode({} as SetBrightnessModeOptions);
```
### `isUsingSystemBrightness`
[Section titled âisUsingSystemBrightnessâ](#isusingsystembrightness)
Check if the current activity is using the system-wide brightness value.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.isUsingSystemBrightness();
```
### `restoreSystemBrightness`
[Section titled ârestoreSystemBrightnessâ](#restoresystembrightness)
Reset the brightness setting of the current activity to use the system-wide value.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.restoreSystemBrightness();
```
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if the Brightness API is available on the current device.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.isAvailable();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check userâs permissions for accessing system brightness.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permissions for accessing system brightness. On Android, this opens the system settings to grant WRITE\_SETTINGS permission.
```typescript
import { CapgoBrightness } from '@capgo/capacitor-brightness';
await CapgoBrightness.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetBrightnessResult`
[Section titled âGetBrightnessResultâ](#getbrightnessresult)
Result of getBrightness or getSystemBrightness.
```typescript
export interface GetBrightnessResult {
/**
* The brightness value from 0 to 1.
* 0 is the minimum brightness, 1 is the maximum brightness.
*
* @since 8.0.0
*/
brightness: number;
}
```
### `SetBrightnessOptions`
[Section titled âSetBrightnessOptionsâ](#setbrightnessoptions)
Options for setBrightness or setSystemBrightness.
```typescript
export interface SetBrightnessOptions {
/**
* The brightness value from 0 to 1.
* 0 is the minimum brightness, 1 is the maximum brightness.
*
* @since 8.0.0
*/
brightness: number;
}
```
### `GetBrightnessModeResult`
[Section titled âGetBrightnessModeResultâ](#getbrightnessmoderesult)
Result of getSystemBrightnessMode.
```typescript
export interface GetBrightnessModeResult {
/**
* The current brightness mode.
*
* @since 8.0.0
*/
mode: BrightnessMode;
}
```
### `SetBrightnessModeOptions`
[Section titled âSetBrightnessModeOptionsâ](#setbrightnessmodeoptions)
Options for setSystemBrightnessMode.
```typescript
export interface SetBrightnessModeOptions {
/**
* The brightness mode to set.
* Cannot be set to UNKNOWN.
*
* @since 8.0.0
*/
mode: BrightnessMode;
}
```
### `IsUsingSystemBrightnessResult`
[Section titled âIsUsingSystemBrightnessResultâ](#isusingsystembrightnessresult)
Result of isUsingSystemBrightness.
```typescript
export interface IsUsingSystemBrightnessResult {
/**
* Whether the current activity is using the system-wide brightness value.
*
* @since 8.0.0
*/
isUsing: boolean;
}
```
### `IsAvailableResult`
[Section titled âIsAvailableResultâ](#isavailableresult)
Result of isAvailable.
```typescript
export interface IsAvailableResult {
/**
* Whether the Brightness API is available on the current device.
*
* @since 8.0.0
*/
available: boolean;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission status result.
```typescript
export interface PermissionStatus {
/**
* Whether the permission to modify system brightness is granted.
*
* @since 8.0.0
*/
brightness: PermissionState;
}
```
### `GetPluginVersionResult`
[Section titled âGetPluginVersionResultâ](#getpluginversionresult)
Result of getPluginVersion.
```typescript
export interface GetPluginVersionResult {
/**
* The native plugin version.
*
* @since 8.0.0
*/
version: string;
}
```
### `BrightnessMode`
[Section titled âBrightnessModeâ](#brightnessmode)
The brightness mode.
```typescript
export enum BrightnessMode {
/**
* The brightness mode is unknown.
*
* @since 8.0.0
*/
UNKNOWN = 0,
/**
* The brightness is automatically adjusted by the system.
*
* @since 8.0.0
*/
AUTOMATIC = 1,
/**
* The brightness is manually set by the user.
*
* @since 8.0.0
*/
MANUAL = 2,
}
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Permission state.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/camera-preview
> The main interface for the CameraPreview plugin.
## Overview
[Section titled âOverviewâ](#overview)
The main interface for the CameraPreview plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `start` - Starts the camera preview.
* `stop` - Stops the camera preview.
* `capture` - Captures a picture from the camera.
* `captureSample` - Captures a single frame from the camera preview stream.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start` | Starts the camera preview. |
| `stop` | Stops the camera preview. |
| `capture` | Captures a picture from the camera. |
| `captureSample` | Captures a single frame from the camera preview stream. |
| `getSupportedFlashModes` | Gets the flash modes supported by the active camera. |
| `setAspectRatio` | Set the aspect ratio of the camera preview. |
| `getAspectRatio` | Gets the current aspect ratio of the camera preview. |
| `setGridMode` | Sets the grid mode of the camera preview overlay. |
| `getGridMode` | Gets the current grid mode of the camera preview overlay. |
| `checkPermissions` | Checks the current camera (and optionally microphone) permission status without prompting the system dialog. |
| `requestPermissions` | Requests camera (and optional microphone) permissions. If permissions are already granted or denied, the current status is returned without prompting. When `showSettingsAlert` is true and permissions are denied, a platform-specific alert guiding the user to the app settings will be presented. |
| `getHorizontalFov` | Gets the horizontal field of view for the active camera. Note: This can be an estimate on some devices. |
| `getSupportedPictureSizes` | Gets the supported picture sizes for all cameras. |
| `setFlashMode` | Sets the flash mode for the active camera. |
| `flip` | Toggles between the front and rear cameras. |
| `setOpacity` | Sets the opacity of the camera preview. |
| `stopRecordVideo` | Stops an ongoing video recording. |
| `startRecordVideo` | Starts recording a video. |
| `isRunning` | Checks if the camera preview is currently running. |
| `getAvailableDevices` | Gets all available camera devices. |
| `getZoom` | Gets the current zoom state, including min/max and current lens info. |
| `getZoomButtonValues` | Returns zoom button values for quick switching. - iOS/Android: includes 0.5 if ultra-wide available; 1 and 2 if wide available; 3 if telephoto available - Web: unsupported. |
| `setZoom` | Sets the zoom level of the camera. |
| `getFlashMode` | Gets the current flash mode. |
| `removeAllListeners` | Removes all registered listeners. |
| `setDeviceId` | Switches the active camera to the one with the specified `deviceId`. |
| `getDeviceId` | Gets the ID of the camera device that is currently bound. On Android, if a physical-lens request falls back to a logical camera, this returns the bound logical camera ID. |
| `getPreviewSize` | Gets the current preview size and position. |
| `setPreviewSize` | Sets the preview size and position. |
| `setFocus` | Sets the camera focus to a specific point in the preview. |
| `addListener` | Adds a listener for screen resize events. |
| `addListener` | Adds a listener for orientation change events. |
| `deleteFile` | Deletes a file at the given absolute path on the device. Use this to quickly clean up temporary images created with `storeToFile`. On web, this is not supported and will throw. |
| `getSafeAreaInsets` | Gets the safe area insets for devices. Returns the orientation-aware notch/camera cutout inset and the current orientation. In portrait mode: returns top inset (notch at top). In landscape mode: returns left inset (notch moved to side). This specifically targets the cutout area (notch, punch hole, etc.) that all modern phones have. |
| `getOrientation` | Gets the current device orientation in a cross-platform format. |
| `getExposureModes` | Returns the exposure modes supported by the active camera. Modes can include: âlockedâ, âautoâ, âcontinuousâ, âcustomâ. |
| `getExposureMode` | Returns the current exposure mode. |
| `setExposureMode` | Sets the exposure mode. |
| `getExposureCompensationRange` | Returns the exposure compensation (EV bias) supported range. |
| `getExposureCompensation` | Returns the current exposure compensation (EV bias). |
| `setExposureCompensation` | Sets the exposure compensation (EV bias). Value will be clamped to range. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-camera-preview](https://github.com/Cap-go/capacitor-camera-preview/).
# Getting Started
> Install @capgo/camera-preview and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/camera-preview
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CameraPreview } from '@capgo/camera-preview';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `start`
[Section titled âstartâ](#start)
Starts the camera preview.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.start({} as CameraPreviewOptions);
```
### `stop`
[Section titled âstopâ](#stop)
Stops the camera preview.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.stop();
```
### `capture`
[Section titled âcaptureâ](#capture)
Captures a picture from the camera.
If `storeToFile` was set to `true` when starting the preview, the returned `value` will be an absolute file path on the device instead of a base64 string. Use getBase64FromFilePath to get the base64 string from the file path.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.capture({} as CameraPreviewPictureOptions);
```
### `captureSample`
[Section titled âcaptureSampleâ](#capturesample)
Captures a single frame from the camera preview stream.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.captureSample({} as CameraSampleOptions);
```
### `getSupportedFlashModes`
[Section titled âgetSupportedFlashModesâ](#getsupportedflashmodes)
Gets the flash modes supported by the active camera.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getSupportedFlashModes();
```
### `setAspectRatio`
[Section titled âsetAspectRatioâ](#setaspectratio)
Set the aspect ratio of the camera preview.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setAspectRatio({} as { aspectRatio: '4:3' | '16:9'; x?: number; y?: number });
```
### `getAspectRatio`
[Section titled âgetAspectRatioâ](#getaspectratio)
Gets the current aspect ratio of the camera preview.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getAspectRatio();
```
### `setGridMode`
[Section titled âsetGridModeâ](#setgridmode)
Sets the grid mode of the camera preview overlay.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setGridMode({} as { gridMode: GridMode });
```
### `getGridMode`
[Section titled âgetGridModeâ](#getgridmode)
Gets the current grid mode of the camera preview overlay.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getGridMode();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Checks the current camera (and optionally microphone) permission status without prompting the system dialog.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Requests camera (and optional microphone) permissions. If permissions are already granted or denied, the current status is returned without prompting. When `showSettingsAlert` is true and permissions are denied, a platform-specific alert guiding the user to the app settings will be presented.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.requestPermissions();
```
### `getHorizontalFov`
[Section titled âgetHorizontalFovâ](#gethorizontalfov)
Gets the horizontal field of view for the active camera. Note: This can be an estimate on some devices.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getHorizontalFov();
```
### `getSupportedPictureSizes`
[Section titled âgetSupportedPictureSizesâ](#getsupportedpicturesizes)
Gets the supported picture sizes for all cameras.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getSupportedPictureSizes();
```
### `setFlashMode`
[Section titled âsetFlashModeâ](#setflashmode)
Sets the flash mode for the active camera.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFlashMode({} as { flashMode: CameraPreviewFlashMode | string });
```
### `flip`
[Section titled âflipâ](#flip)
Toggles between the front and rear cameras.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.flip();
```
### `setOpacity`
[Section titled âsetOpacityâ](#setopacity)
Sets the opacity of the camera preview.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setOpacity({} as CameraOpacityOptions);
```
### `stopRecordVideo`
[Section titled âstopRecordVideoâ](#stoprecordvideo)
Stops an ongoing video recording.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.stopRecordVideo();
```
### `startRecordVideo`
[Section titled âstartRecordVideoâ](#startrecordvideo)
Starts recording a video.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.startRecordVideo({} as CameraPreviewOptions);
```
### `isRunning`
[Section titled âisRunningâ](#isrunning)
Checks if the camera preview is currently running.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.isRunning();
```
### `getAvailableDevices`
[Section titled âgetAvailableDevicesâ](#getavailabledevices)
Gets all available camera devices.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getAvailableDevices();
```
### `getZoom`
[Section titled âgetZoomâ](#getzoom)
Gets the current zoom state, including min/max and current lens info.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getZoom();
```
### `getZoomButtonValues`
[Section titled âgetZoomButtonValuesâ](#getzoombuttonvalues)
Returns zoom button values for quick switching.
* iOS/Android: includes 0.5 if ultra-wide available; 1 and 2 if wide available; 3 if telephoto available
* Web: unsupported
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getZoomButtonValues();
```
### `setZoom`
[Section titled âsetZoomâ](#setzoom)
Sets the zoom level of the camera.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setZoom({} as { level: number; ramp?: boolean; autoFocus?: boolean });
```
### `getFlashMode`
[Section titled âgetFlashModeâ](#getflashmode)
Gets the current flash mode.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getFlashMode();
```
### `setDeviceId`
[Section titled âsetDeviceIdâ](#setdeviceid)
Switches the active camera to the one with the specified `deviceId`.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setDeviceId({} as { deviceId: string });
```
### `getDeviceId`
[Section titled âgetDeviceIdâ](#getdeviceid)
Gets the ID of the camera device that is currently bound. On Android, if a physical-lens request falls back to a logical camera, this returns the bound logical camera ID.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getDeviceId();
```
### `getPreviewSize`
[Section titled âgetPreviewSizeâ](#getpreviewsize)
Gets the current preview size and position.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getPreviewSize();
```
### `setPreviewSize`
[Section titled âsetPreviewSizeâ](#setpreviewsize)
Sets the preview size and position.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setPreviewSize({} as { x?: number; y?: number; width: number; height: number });
```
### `setFocus`
[Section titled âsetFocusâ](#setfocus)
Sets the camera focus to a specific point in the preview.
Note: The plugin does not attach any native tap-to-focus gesture handlers. Handle taps in your HTML/JS (e.g., on the overlaying UI), then pass normalized coordinates here.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFocus({} as { x: number; y: number });
```
### `deleteFile`
[Section titled âdeleteFileâ](#deletefile)
Deletes a file at the given absolute path on the device. Use this to quickly clean up temporary images created with `storeToFile`. On web, this is not supported and will throw.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.deleteFile({} as { path: string });
```
### `getSafeAreaInsets`
[Section titled âgetSafeAreaInsetsâ](#getsafeareainsets)
Gets the safe area insets for devices. Returns the orientation-aware notch/camera cutout inset and the current orientation. In portrait mode: returns top inset (notch at top). In landscape mode: returns left inset (notch moved to side). This specifically targets the cutout area (notch, punch hole, etc.) that all modern phones have.
Android: Values returned in dp (logical pixels). iOS: Values returned in physical pixels, excluding status bar (only pure notch/cutout size).
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getSafeAreaInsets();
```
### `getOrientation`
[Section titled âgetOrientationâ](#getorientation)
Gets the current device orientation in a cross-platform format.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getOrientation();
```
### `getExposureModes`
[Section titled âgetExposureModesâ](#getexposuremodes)
Returns the exposure modes supported by the active camera. Modes can include: âlockedâ, âautoâ, âcontinuousâ, âcustomâ.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getExposureModes();
```
### `getExposureMode`
[Section titled âgetExposureModeâ](#getexposuremode)
Returns the current exposure mode.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getExposureMode();
```
### `setExposureMode`
[Section titled âsetExposureModeâ](#setexposuremode)
Sets the exposure mode.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureMode({} as { mode: ExposureMode });
```
### `getExposureCompensationRange`
[Section titled âgetExposureCompensationRangeâ](#getexposurecompensationrange)
Returns the exposure compensation (EV bias) supported range.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getExposureCompensationRange();
```
### `getExposureCompensation`
[Section titled âgetExposureCompensationâ](#getexposurecompensation)
Returns the current exposure compensation (EV bias).
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.getExposureCompensation();
```
### `setExposureCompensation`
[Section titled âsetExposureCompensationâ](#setexposurecompensation)
Sets the exposure compensation (EV bias). Value will be clamped to range.
```typescript
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureCompensation({} as { value: number });
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CameraPreviewOptions`
[Section titled âCameraPreviewOptionsâ](#camerapreviewoptions)
Defines the configuration options for starting the camera preview.
```typescript
export interface CameraPreviewOptions {
/**
* The parent element to attach the video preview to.
* @platform web
*/
parent?: string;
/**
* A CSS class name to add to the preview element.
* @platform web
*/
className?: string;
/**
* The width of the preview in pixels. Defaults to the screen width.
* @platform android, ios, web
*/
width?: number;
/**
* The height of the preview in pixels. Defaults to the screen height.
* @platform android, ios, web
*/
height?: number;
/**
* The horizontal origin of the preview, in pixels.
* @platform android, ios
*/
x?: number;
/**
* The vertical origin of the preview, in pixels.
* @platform android, ios
*/
y?: number;
/**
* The aspect ratio of the camera preview, '4:3' or '16:9' or 'fill'.
* Cannot be set if width or height is provided, otherwise the call will be rejected.
* Use setPreviewSize to adjust size after starting.
*
* @since 2.0.0
*/
aspectRatio?: '4:3' | '16:9';
/**
* Controls how the camera preview fills the available space.
* - 'contain': Fits the entire preview within the space, may show letterboxing (default).
* - 'cover': Fills the entire space, may crop edges of the preview.
* @default "contain"
* @platform android, ios, web
*/
aspectMode?: 'cover' | 'contain';
/**
* The grid overlay to display on the camera preview.
* @default "none"
* @since 2.1.0
*/
gridMode?: GridMode;
/**
* Adjusts the y-position to account for safe areas (e.g., notches).
* @platform ios
* @default false
*/
includeSafeAreaInsets?: boolean;
/**
* If true, places the preview behind the webview.
* @platform android
* @default true
*/
toBack?: boolean;
/**
* Bottom padding for the preview, in pixels.
* @platform android, ios
*/
paddingBottom?: number;
/**
* Whether to rotate the preview when the device orientation changes.
* @platform ios
* @default true
*/
rotateWhenOrientationChanged?: boolean;
/**
* The camera to use.
* @default "rear"
*/
position?: CameraPosition | string;
/**
* If true, saves the captured image to a file and returns the file path.
* If false, returns a base64 encoded string.
* @default false
*/
storeToFile?: boolean;
/**
* If true, prevents the plugin from rotating the image based on EXIF data.
* @platform android
* @default false
*/
disableExifHeaderStripping?: boolean;
/**
* If true, disables the audio stream, preventing audio permission requests.
* @default true
*/
disableAudio?: boolean;
/**
* If true, locks the device orientation while the camera is active.
* @platform android
* @default false
*/
lockAndroidOrientation?: boolean;
/**
* If true, allows the camera preview's opacity to be changed.
* @platform android, web
* @default false
*/
enableOpacity?: boolean;
/**
* If true, disables the visual focus indicator when tapping to focus.
* @platform android, ios
* @default false
*/
disableFocusIndicator?: boolean;
/**
* The `deviceId` of the camera to use. If provided, `position` is ignored.
* @platform ios
*/
deviceId?: string;
/**
* On Android, attempts to bind a physical camera directly when `deviceId` refers to a physical lens.
* Disabled by default because OEM support is inconsistent; when false, Android keeps the current logical-camera fallback behavior.
* @default false
* @platform android
*/
enablePhysicalDeviceSelection?: boolean;
/**
* The initial zoom level when starting the camera preview.
* If the requested zoom level is not available, the native plugin will reject.
* @default 1.0
* @platform android, ios
* @since 2.2.0
*/
initialZoomLevel?: number;
/**
* The vertical positioning of the camera preview.
* @default "center"
* @platform android, ios, web
* @since 2.3.0
*/
positioning?: CameraPositioning;
/**
* If true, enables video capture capabilities when the camera starts.
* @default false
* @platform android
* @since 7.11.0
*/
enableVideoMode?: boolean;
/**
* If true, forces the camera to start/restart even if it's already running or busy.
* This will kill the current camera session and start a new one, ignoring all state checks.
* @default false
* @platform android, ios, web
*/
force?: boolean;
/**
* Sets the quality of video for recording.
* Options: 'low', 'medium', 'high'
* @note On Android requires 'enableVideoMode' to be true
* @note Will affect the entire preview stream for iOS
* @platform ios, android
* @default "high"
*/
videoQuality?: 'low' | 'medium' | 'high';
}
```
### `CameraPreviewPictureOptions`
[Section titled âCameraPreviewPictureOptionsâ](#camerapreviewpictureoptions)
Defines the options for capturing a picture.
```typescript
export interface CameraPreviewPictureOptions {
/**
* The maximum height of the picture in pixels. The image will be resized to fit within this height while maintaining aspect ratio.
* If not specified the captured image will match the preview's visible area.
*/
height?: number;
/**
* The maximum width of the picture in pixels. The image will be resized to fit within this width while maintaining aspect ratio.
* If not specified the captured image will match the preview's visible area.
*/
width?: number;
/**
* The quality of the captured image, from 0 to 100.
* Does not apply to `.png` format.
* @default 85
*/
quality?: number;
/**
* The format of the captured image.
* @default "jpeg"
*/
format?: PictureFormat;
/**
* If true, the captured image will be saved to the user's gallery.
* @default false
* @since 7.5.0
*/
saveToGallery?: boolean;
/**
* If true, the plugin will attempt to add GPS location data to the image's EXIF metadata.
* This may prompt the user for location permissions.
* @default false
* @since 7.6.0
*/
withExifLocation?: boolean;
/**
* If true, the plugin will embed a timestamp in the top-right corner of the image.
* @default false
* @since 7.17.0
*/
embedTimestamp?: boolean;
/**
* If true, the plugin will embed the current location in the top-right corner of the image.
* Requires `withExifLocation` to be enabled.
* @default false
* @since 7.18.0
*/
embedLocation?: boolean;
/**
* Sets the priority for photo quality vs. capture speed.
* - "speed": Prioritizes faster capture times, may reduce image quality.
* - "balanced": Aims for a balance between quality and speed.
* - "quality": Prioritizes image quality, may reduce capture speed.
* See https://developer.apple.com/documentation/avfoundation/avcapturephotosettings/photoqualityprioritization for details.
*
* @since 7.21.0
* @platform ios
* @default "speed"
*/
photoQualityPrioritization?: 'speed' | 'balanced' | 'quality';
}
```
### `ExifData`
[Section titled âExifDataâ](#exifdata)
Represents EXIF data extracted from an image.
```typescript
export interface ExifData {
[key: string]: any;
}
```
### `CameraSampleOptions`
[Section titled âCameraSampleOptionsâ](#camerasampleoptions)
Defines the options for capturing a sample frame from the camera preview.
```typescript
export interface CameraSampleOptions {
/**
* The quality of the captured sample, from 0 to 100.
* @default 85
*/
quality?: number;
}
```
### `CameraPreviewFlashMode`
[Section titled âCameraPreviewFlashModeâ](#camerapreviewflashmode)
The available flash modes for the camera. âtorchâ is a continuous light mode.
```typescript
export type CameraPreviewFlashMode = 'off' | 'on' | 'auto' | 'torch';
```
### `GridMode`
[Section titled âGridModeâ](#gridmode)
```typescript
export type GridMode = 'none' | '3x3' | '4x4';
```
### `PermissionRequestOptions`
[Section titled âPermissionRequestOptionsâ](#permissionrequestoptions)
```typescript
export interface PermissionRequestOptions {
disableAudio?: boolean;
showSettingsAlert?: boolean;
title?: string;
message?: string;
openSettingsButtonTitle?: string;
cancelButtonTitle?: string;
}
```
### `CameraPermissionStatus`
[Section titled âCameraPermissionStatusâ](#camerapermissionstatus)
```typescript
export interface CameraPermissionStatus {
camera: PermissionState;
microphone?: PermissionState;
}
```
### `SupportedPictureSizes`
[Section titled âSupportedPictureSizesâ](#supportedpicturesizes)
Represents the supported picture sizes for a camera facing a certain direction.
```typescript
export interface SupportedPictureSizes {
/** The camera direction ("front" or "rear"). */
facing: string;
/** A list of supported picture sizes for this camera. */
supportedPictureSizes: PictureSize[];
}
```
### `CameraOpacityOptions`
[Section titled âCameraOpacityOptionsâ](#cameraopacityoptions)
Defines the options for setting the camera previewâs opacity.
```typescript
export interface CameraOpacityOptions {
/**
* The opacity percentage, from 0.0 (fully transparent) to 1.0 (fully opaque).
* @default 1.0
*/
opacity?: number;
}
```
### `CameraDevice`
[Section titled âCameraDeviceâ](#cameradevice)
Represents a physical camera on the device (e.g., the front-facing camera).
```typescript
export interface CameraDevice {
/** A unique identifier for the camera device. */
deviceId: string;
/** A human-readable name for the camera device. */
label: string;
/** The physical position of the camera on the device. */
position: CameraPosition;
/** A list of all available lenses for this camera device. */
lenses: CameraLens[];
/** The overall minimum zoom factor available across all lenses on this device. */
minZoom: number;
/** The overall maximum zoom factor available across all lenses on this device. */
maxZoom: number;
/** Identifies whether the device is a logical camera (composed of multiple physical lenses). */
isLogical: boolean;
}
```
### `LensInfo`
[Section titled âLensInfoâ](#lensinfo)
Represents the detailed information of the currently active lens.
```typescript
export interface LensInfo {
/** The focal length of the active lens in millimeters. */
focalLength: number;
/** The device type of the active lens. */
deviceType: DeviceType;
/** The base zoom ratio of the active lens (e.g., 0.5x, 1.0x). */
baseZoomRatio: number;
/** The current digital zoom factor applied on top of the base zoom. */
digitalZoom: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# Capacitor+
> Capacitor+ is an automated fork of Capacitor that merges community PRs faster, with security-reviewed releases.
Tip
**Why Capacitor+?** Great PRs sit unmerged in the official Capacitor repository for months. Capacitor+ actively merges these community contributions so you donât have to wait.
Community PRs Merged Faster
Bug fixes and features stuck in upstream? We merge them so you can benefit immediately.
Auto-Synced Daily
Every change from official Capacitor is automatically pulled, tested, and verified.
Security Reviewed
Every release is analyzed by AI for security vulnerabilities, breaking changes, and stability risks.
Drop-in Replacement
Same API as official Capacitor - just change the package scope and youâre done.
## Philosophy
[Section titled âPhilosophyâ](#philosophy)
The Ionic team maintains Capacitor with their own priorities and release schedule. Community contributions can wait months or even years to be merged. Capacitor+ takes a different approach:
1. **Merge PRs from Forks** - Valuable PRs stuck in the upstream queue are actively merged
2. **Continuous Sync** - Every upstream change is automatically pulled and tested
3. **Rapid Releases** - Changes are published to npm as soon as they pass CI
4. **Community-First** - Your contributions matter and get prioritized
5. **Transparency** - All automation is open source and visible
## Packages
[Section titled âPackagesâ](#packages)
| Package | npm |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `@capacitor-plus/core` | [](https://www.npmjs.com/package/@capacitor-plus/core) |
| `@capacitor-plus/cli` | [](https://www.npmjs.com/package/@capacitor-plus/cli) |
| `@capacitor-plus/android` | [](https://www.npmjs.com/package/@capacitor-plus/android) |
| `@capacitor-plus/ios` | [](https://www.npmjs.com/package/@capacitor-plus/ios) |
# Getting Started
> Learn how to install Capacitor+ as a drop-in replacement for official Capacitor packages.
## New Project Installation
[Section titled âNew Project Installationâ](#new-project-installation)
1. **Install core packages**
```bash
npm install @capacitor-plus/core @capacitor-plus/cli
```
2. **Add platform packages**
```bash
npm install @capacitor-plus/android # for Android
npm install @capacitor-plus/ios # for iOS
```
3. **Initialize Capacitor**
* npm
```sh
npx cap init
```
* pnpm
```sh
pnpm cap init
```
* yarn
```sh
yarn cap init
```
* bun
```sh
bunx cap init
```
4. **Add platforms**
* npm
```sh
npx cap add android
```
* pnpm
```sh
pnpm cap add android
```
* yarn
```sh
yarn cap add android
```
* bun
```sh
bunx cap add android
```
- npm
```sh
npx cap add ios
```
- pnpm
```sh
pnpm cap add ios
```
- yarn
```sh
yarn cap add ios
```
- bun
```sh
bunx cap add ios
```
## Migrating from Official Capacitor
[Section titled âMigrating from Official Capacitorâ](#migrating-from-official-capacitor)
If you have an existing Capacitor project, migrating to Capacitor+ is simple:
1. **Remove official packages**
```bash
npm uninstall @capacitor/core @capacitor/cli @capacitor/android @capacitor/ios
```
2. **Install Capacitor+ packages**
```bash
npm install @capacitor-plus/core @capacitor-plus/cli
npm install @capacitor-plus/android # if using Android
npm install @capacitor-plus/ios # if using iOS
```
3. **Sync your project**
* npm
```sh
npx cap sync
```
* pnpm
```sh
pnpm cap sync
```
* yarn
```sh
yarn cap sync
```
* bun
```sh
bunx cap sync
```
Note
No code changes required! Capacitor+ has the same API as official Capacitor. Your imports and code remain exactly the same.
## Usage
[Section titled âUsageâ](#usage)
Since Capacitor+ is API-compatible, your existing code works without changes:
```typescript
import { Capacitor } from '@capacitor/core';
import { registerPlugin } from '@capacitor/core';
// Check platform
const platform = Capacitor.getPlatform();
console.log('Running on:', platform);
// Check if native
if (Capacitor.isNativePlatform()) {
console.log('Running on native platform');
}
// Register a custom plugin
const MyPlugin = registerPlugin('MyPlugin');
```
### With Official Capacitor Plugins
[Section titled âWith Official Capacitor Pluginsâ](#with-official-capacitor-plugins)
All official Capacitor plugins work seamlessly:
```typescript
import { Camera, CameraResultType } from '@capacitor/camera';
import { Geolocation } from '@capacitor/geolocation';
import { Storage } from '@capacitor/preferences';
// Camera
const photo = await Camera.getPhoto({
quality: 90,
resultType: CameraResultType.Uri
});
// Geolocation
const position = await Geolocation.getCurrentPosition();
// Storage
await Storage.set({ key: 'name', value: 'John' });
```
### With Capgo Plugins
[Section titled âWith Capgo Pluginsâ](#with-capgo-plugins)
Capgo plugins work perfectly with Capacitor+:
```typescript
import { CapacitorUpdater } from '@capgo/capacitor-updater';
import { ScreenOrientation } from '@capgo/capacitor-screen-orientation';
import { CapacitorFlash } from '@capgo/capacitor-flash';
// Live updates
await CapacitorUpdater.notifyAppReady();
// Screen orientation
await ScreenOrientation.lock({ orientation: 'portrait' });
// Flashlight
await CapacitorFlash.toggle();
```
## How the Sync Works
[Section titled âHow the Sync Worksâ](#how-the-sync-works)
```plaintext
âââââââââââââââââââââââ ââââââââââââââââââââ ââââââââââââââââââââ âââââââââââââââââââ
â ionic-team/ â â CI/CD â â Claude Code â â npm publish â
â capacitor ââââââśâ Pipeline ââââââśâ Security Review ââââââśâ @capacitor-plusâ
â (upstream) â â (daily sync) â â (AI analysis) â â packages â
âââââââââââââââââââââââ ââââââââââââââââââââ ââââââââââââââââââââ âââââââââââââââââââ
```
1. **Daily Sync**: GitHub Actions fetch latest changes from `ionic-team/capacitor`
2. **PR Creation**: Changes are proposed as pull requests to the `plus` branch
3. **CI Validation**: Full test suite runs (lint, unit tests, iOS build, Android build)
4. **Security Review**: AI-powered analysis checks for vulnerabilities and breaking changes
5. **Auto-Merge**: Only if CI passes AND security review approves
6. **Auto-Publish**: New version published to npm under `@capacitor-plus/*`
## Security Review Details
[Section titled âSecurity Review Detailsâ](#security-review-details)
Every upstream sync is analyzed for:
| Check | What It Catches |
| -------------------- | ---------------------------------------------------------------------- |
| **Security** | Command injection, XSS, path traversal, hardcoded secrets |
| **Breaking Changes** | Removed/renamed APIs, changed signatures, config changes |
| **Stability** | Null dereferences, unhandled exceptions, race conditions, memory leaks |
| **Data Safety** | Data loss scenarios, privacy violations, insecure storage |
| **Code Integrity** | Obfuscated code, suspicious network calls, backdoors |
Caution
If any issues are detected, the PR is flagged for manual review and will NOT be auto-merged. This ensures you always get stable, secure releases.
## Submitting Your PR
[Section titled âSubmitting Your PRâ](#submitting-your-pr)
Have a PR stuck in the official Capacitor repo? Get it merged in Capacitor+:
1. **Open an issue** in the [Capacitor+ repo](https://github.com/Cap-go/capacitor-plus/issues) linking to your upstream PR
2. **Or submit directly** as a PR to the `plus` branch
3. The team will review, run CI, and merge if it passes
This way you and others can benefit from your work immediately without waiting for the upstream release cycle.
## FAQ
[Section titled âFAQâ](#faq)
### Is this production-ready?
[Section titled âIs this production-ready?â](#is-this-production-ready)
Yes. Capacitor+ is used in production apps. Every release passes the same test suite as official Capacitor, plus additional security analysis.
### Will my official plugins still work?
[Section titled âWill my official plugins still work?â](#will-my-official-plugins-still-work)
Yes. All `@capacitor/*` plugins work with Capacitor+ out of the box.
### What if upstream releases a breaking change?
[Section titled âWhat if upstream releases a breaking change?â](#what-if-upstream-releases-a-breaking-change)
The AI security review flags breaking changes for manual review. Youâll see the changes documented before theyâre merged.
### How do I report issues?
[Section titled âHow do I report issues?â](#how-do-i-report-issues)
File issues on the [Capacitor+ GitHub repo](https://github.com/Cap-go/capacitor-plus/issues). For issues that also affect official Capacitor, weâll help coordinate upstream.
### Can I contribute?
[Section titled âCan I contribute?â](#can-i-contribute)
Absolutely! PRs are welcome. You can submit fixes directly or request that specific upstream PRs be merged.
# @capgo/capacitor-compass
> Capacitor Compass Plugin interface for reading device compass heading.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Compass Plugin interface for reading device compass heading.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getCurrentHeading` - Get the current compass heading in degrees. On iOS, the heading is updated in the background, and the latest value is returned. On Android, the heading is calculated when the method is called using accelerometer and magnetometer sensors. Not implemented on Web.
* `startListening` - Start listening for compass heading changes via events. This starts the compass sensors and emits âheadingChangeâ events.
* `stopListening` - Stop listening for compass heading changes. This stops the compass sensors and stops emitting events.
* `checkPermissions` - Check the current permission status for accessing compass data. On iOS, this checks location permission status. On Android, this always returns âgrantedâ as no permissions are required.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getCurrentHeading` | Get the current compass heading in degrees. On iOS, the heading is updated in the background, and the latest value is returned. On Android, the heading is calculated when the method is called using accelerometer and magnetometer sensors. Not implemented on Web. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `startListening` | Start listening for compass heading changes via events. This starts the compass sensors and emits âheadingChangeâ events. |
| `stopListening` | Stop listening for compass heading changes. This stops the compass sensors and stops emitting events. |
| `addListener` | Add a listener for compass heading change events. |
| `addListener` | Add a listener for compass accuracy change events. Only supported on Android. On iOS and Web, this will never emit events. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `checkPermissions` | Check the current permission status for accessing compass data. On iOS, this checks location permission status. On Android, this always returns âgrantedâ as no permissions are required. |
| `requestPermissions` | Request permission to access compass data. On iOS, this requests location permission (required for heading data). On Android, this resolves immediately as no permissions are required. |
| `watchAccuracy` | Start monitoring compass accuracy. On Android, this monitors the magnetometer accuracy and emits accuracyChange events. Developers can listen to these events and implement their own UI for calibration prompts. On iOS and Web, this method does nothing as compass accuracy monitoring is not available. |
| `unwatchAccuracy` | Stop monitoring compass accuracy. This stops the accuracy monitoring. |
| `getAccuracy` | Get the current compass accuracy level. On Android, returns the current magnetometer sensor accuracy. On iOS and Web, always returns CompassAccuracy.UNKNOWN as accuracy monitoring is not available. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-compass](https://github.com/Cap-go/capacitor-compass/).
# Getting Started
> Install @capgo/capacitor-compass and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-compass
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getCurrentHeading`
[Section titled âgetCurrentHeadingâ](#getcurrentheading)
Get the current compass heading in degrees. On iOS, the heading is updated in the background, and the latest value is returned. On Android, the heading is calculated when the method is called using accelerometer and magnetometer sensors. Not implemented on Web.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
const { value } = await CapgoCompass.getCurrentHeading();
console.log('Compass heading:', value, 'degrees');
```
### `startListening`
[Section titled âstartListeningâ](#startlistening)
Start listening for compass heading changes via events. This starts the compass sensors and emits âheadingChangeâ events.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
// With default throttling (100ms interval, 2° minimum change)
await CapgoCompass.startListening();
// With custom throttling for high-frequency updates
await CapgoCompass.startListening({
minInterval: 50, // 50ms between events
minHeadingChange: 1.0 // 1° minimum change
});
CapgoCompass.addListener('headingChange', (event) => {
console.log('Heading:', event.value);
});
```
### `stopListening`
[Section titled âstopListeningâ](#stoplistening)
Stop listening for compass heading changes. This stops the compass sensors and stops emitting events.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
await CapgoCompass.stopListening();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission status for accessing compass data. On iOS, this checks location permission status. On Android, this always returns âgrantedâ as no permissions are required.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
const status = await CapgoCompass.checkPermissions();
console.log('Compass permission:', status.compass);
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission to access compass data. On iOS, this requests location permission (required for heading data). On Android, this resolves immediately as no permissions are required.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
const status = await CapgoCompass.requestPermissions();
if (status.compass === 'granted') {
// Can now use compass
}
```
### `watchAccuracy`
[Section titled âwatchAccuracyâ](#watchaccuracy)
Start monitoring compass accuracy. On Android, this monitors the magnetometer accuracy and emits accuracyChange events. Developers can listen to these events and implement their own UI for calibration prompts. On iOS and Web, this method does nothing as compass accuracy monitoring is not available.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
// Start monitoring accuracy
await CapgoCompass.watchAccuracy();
// Listen for accuracy changes and implement custom UI
CapgoCompass.addListener('accuracyChange', (event) => {
console.log('Accuracy changed to:', event.accuracy);
if (event.accuracy < CompassAccuracy.MEDIUM) {
// Show your custom calibration UI
}
});
```
### `unwatchAccuracy`
[Section titled âunwatchAccuracyâ](#unwatchaccuracy)
Stop monitoring compass accuracy. This stops the accuracy monitoring.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
await CapgoCompass.unwatchAccuracy();
```
### `getAccuracy`
[Section titled âgetAccuracyâ](#getaccuracy)
Get the current compass accuracy level. On Android, returns the current magnetometer sensor accuracy. On iOS and Web, always returns CompassAccuracy.UNKNOWN as accuracy monitoring is not available.
```typescript
import { CapgoCompass } from '@capgo/capacitor-compass';
const { accuracy } = await CapgoCompass.getAccuracy();
if (accuracy < CompassAccuracy.MEDIUM) {
console.log('Compass needs calibration');
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CompassHeading`
[Section titled âCompassHeadingâ](#compassheading)
Result containing the compass heading value.
```typescript
export interface CompassHeading {
/** Compass heading in degrees (0-360) */
value: number;
}
```
### `ListeningOptions`
[Section titled âListeningOptionsâ](#listeningoptions)
Options for configuring compass listening behavior.
```typescript
export interface ListeningOptions {
/**
* Minimum interval between heading change events in milliseconds.
* Lower values = more frequent updates but higher CPU/battery usage.
*
* @default 100
* @since 8.1.4
*/
minInterval?: number;
/**
* Minimum heading change in degrees required to trigger an event.
* Lower values = more sensitive but more events.
* Handles wraparound (e.g., 359° to 1° = 2° change).
*
* @default 2.0
* @since 8.1.4
*/
minHeadingChange?: number;
}
```
### `HeadingChangeEvent`
[Section titled âHeadingChangeEventâ](#headingchangeevent)
Event data for heading change events.
```typescript
export interface HeadingChangeEvent {
/** Compass heading in degrees (0-360) */
value: number;
}
```
### `AccuracyChangeEvent`
[Section titled âAccuracyChangeEventâ](#accuracychangeevent)
Event data for accuracy change events.
```typescript
export interface AccuracyChangeEvent {
/** Current accuracy level of the compass */
accuracy: CompassAccuracy;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission status for compass plugin.
```typescript
export interface PermissionStatus {
/**
* Permission state for accessing compass/location data.
* On iOS, this requires location permission to access heading.
* On Android, no special permissions are required for compass sensors.
*
* @since 7.0.0
*/
compass: PermissionState;
}
```
### `CompassAccuracy`
[Section titled âCompassAccuracyâ](#compassaccuracy)
Compass accuracy level constants.
```typescript
export enum CompassAccuracy {
/** High accuracy - approximates to less than 5 degrees of error */
HIGH = 3,
/** Medium accuracy - approximates to less than 10 degrees of error */
MEDIUM = 2,
/** Low accuracy - approximates to less than 15 degrees of error */
LOW = 1,
/** Unreliable accuracy - approximates to more than 15 degrees of error */
UNRELIABLE = 0,
/** Unknown accuracy value */
UNKNOWN = -1,
}
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Permission state for compass access.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-contacts
> Capacitor Contacts Plugin interface for managing device contacts.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Contacts Plugin interface for managing device contacts.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `countContacts` - Count the total number of contacts on the device.
* `createContact` - Create a new contact programmatically.
* `createGroup` - Create a new contact group.
* `deleteContactById` - Delete a contact by ID.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------------- | ------------------------------------------------------------ |
| `countContacts` | Count the total number of contacts on the device. |
| `createContact` | Create a new contact programmatically. |
| `createGroup` | Create a new contact group. |
| `deleteContactById` | Delete a contact by ID. |
| `deleteGroupById` | Delete a group by ID. |
| `displayContactById` | Display a contact using the native contact viewer. |
| `displayCreateContact` | Display the native create contact UI. |
| `displayUpdateContactById` | Display the native update contact UI for a specific contact. |
| `getAccounts` | Get all accounts available on the device. |
| `getContactById` | Get a specific contact by ID. |
| `getContacts` | Get all contacts from the device. |
| `getGroupById` | Get a specific group by ID. |
| `getGroups` | Get all contact groups. |
| `isAvailable` | Check if contacts are available on the device. |
| `isSupported` | Check if the plugin is supported on the current platform. |
| `openSettings` | Open the deviceâs contacts settings. |
| `pickContact` | Pick a single contact using the native contact picker. |
| `pickContacts` | Pick one or more contacts using the native contact picker. |
| `updateContactById` | Update an existing contact by ID. |
| `checkPermissions` | Check the current permission status for contacts. |
| `requestPermissions` | Request permissions to access contacts. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-contacts](https://github.com/Cap-go/capacitor-contacts/).
# Getting Started
> Install @capgo/capacitor-contacts and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-contacts
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `countContacts`
[Section titled âcountContactsâ](#countcontacts)
Count the total number of contacts on the device.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.countContacts();
```
### `createContact`
[Section titled âcreateContactâ](#createcontact)
Create a new contact programmatically.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.createContact({} as CreateContactOptions);
```
### `createGroup`
[Section titled âcreateGroupâ](#creategroup)
Create a new contact group.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.createGroup({} as CreateGroupOptions);
```
### `deleteContactById`
[Section titled âdeleteContactByIdâ](#deletecontactbyid)
Delete a contact by ID.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.deleteContactById({} as DeleteContactByIdOptions);
```
### `deleteGroupById`
[Section titled âdeleteGroupByIdâ](#deletegroupbyid)
Delete a group by ID.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.deleteGroupById({} as DeleteGroupByIdOptions);
```
### `displayContactById`
[Section titled âdisplayContactByIdâ](#displaycontactbyid)
Display a contact using the native contact viewer.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.displayContactById({} as DisplayContactByIdOptions);
```
### `displayCreateContact`
[Section titled âdisplayCreateContactâ](#displaycreatecontact)
Display the native create contact UI.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.displayCreateContact();
```
### `displayUpdateContactById`
[Section titled âdisplayUpdateContactByIdâ](#displayupdatecontactbyid)
Display the native update contact UI for a specific contact.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.displayUpdateContactById({} as DisplayUpdateContactByIdOptions);
```
### `getAccounts`
[Section titled âgetAccountsâ](#getaccounts)
Get all accounts available on the device.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.getAccounts();
```
### `getContactById`
[Section titled âgetContactByIdâ](#getcontactbyid)
Get a specific contact by ID.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.getContactById({} as GetContactByIdOptions);
```
### `getContacts`
[Section titled âgetContactsâ](#getcontacts)
Get all contacts from the device.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.getContacts();
```
### `getGroupById`
[Section titled âgetGroupByIdâ](#getgroupbyid)
Get a specific group by ID.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.getGroupById({} as GetGroupByIdOptions);
```
### `getGroups`
[Section titled âgetGroupsâ](#getgroups)
Get all contact groups.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.getGroups();
```
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if contacts are available on the device.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.isAvailable();
```
### `isSupported`
[Section titled âisSupportedâ](#issupported)
Check if the plugin is supported on the current platform.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.isSupported();
```
### `openSettings`
[Section titled âopenSettingsâ](#opensettings)
Open the deviceâs contacts settings.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.openSettings();
```
### `pickContact`
[Section titled âpickContactâ](#pickcontact)
Pick a single contact using the native contact picker.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.pickContact();
```
### `pickContacts`
[Section titled âpickContactsâ](#pickcontacts)
Pick one or more contacts using the native contact picker.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.pickContacts();
```
### `updateContactById`
[Section titled âupdateContactByIdâ](#updatecontactbyid)
Update an existing contact by ID.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.updateContactById({} as UpdateContactByIdOptions);
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission status for contacts.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permissions to access contacts.
```typescript
import { CapacitorContacts } from '@capgo/capacitor-contacts';
await CapacitorContacts.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CountContactsResult`
[Section titled âCountContactsResultâ](#countcontactsresult)
Result from counting contacts.
```typescript
export interface CountContactsResult {
/**
* Total number of contacts.
*
* @since 1.0.0
*/
count: number;
}
```
### `CreateContactOptions`
[Section titled âCreateContactOptionsâ](#createcontactoptions)
Options for creating a contact.
```typescript
export interface CreateContactOptions {
/**
* Contact information to create. The 'id' field will be generated automatically.
*
* @since 1.0.0
*/
contact: Omit;
}
```
### `CreateContactResult`
[Section titled âCreateContactResultâ](#createcontactresult)
Result from creating a contact.
```typescript
export interface CreateContactResult {
/**
* The ID of the newly created contact.
*
* @since 1.0.0
*/
id: string;
}
```
### `CreateGroupOptions`
[Section titled âCreateGroupOptionsâ](#creategroupoptions)
Options for creating a group.
```typescript
export interface CreateGroupOptions {
/**
* Group information to create. The 'id' field will be generated automatically.
*
* @since 1.0.0
*/
group: Omit;
}
```
### `CreateGroupResult`
[Section titled âCreateGroupResultâ](#creategroupresult)
Result from creating a group.
```typescript
export interface CreateGroupResult {
/**
* The ID of the newly created group.
*
* @since 1.0.0
*/
id: string;
}
```
### `DeleteContactByIdOptions`
[Section titled âDeleteContactByIdOptionsâ](#deletecontactbyidoptions)
Options for deleting a contact by ID.
```typescript
export interface DeleteContactByIdOptions {
/**
* The ID of the contact to delete.
*
* @since 1.0.0
*/
id: string;
}
```
### `DeleteGroupByIdOptions`
[Section titled âDeleteGroupByIdOptionsâ](#deletegroupbyidoptions)
Options for deleting a group by ID.
```typescript
export interface DeleteGroupByIdOptions {
/**
* The ID of the group to delete.
*
* @since 1.0.0
*/
id: string;
}
```
### `DisplayContactByIdOptions`
[Section titled âDisplayContactByIdOptionsâ](#displaycontactbyidoptions)
Options for displaying a contact by ID.
```typescript
export interface DisplayContactByIdOptions {
/**
* The ID of the contact to display.
*
* @since 1.0.0
*/
id: string;
}
```
### `DisplayCreateContactOptions`
[Section titled âDisplayCreateContactOptionsâ](#displaycreatecontactoptions)
Options for displaying the native create contact UI.
```typescript
export interface DisplayCreateContactOptions {
/**
* Optional pre-filled contact information for the create UI.
*
* @since 1.0.0
*/
contact?: Omit;
}
```
### `DisplayCreateContactResult`
[Section titled âDisplayCreateContactResultâ](#displaycreatecontactresult)
Result from displaying the native create contact UI.
```typescript
export interface DisplayCreateContactResult {
/**
* The ID of the created contact, if one was created. Undefined if the user cancelled.
*
* @since 1.0.0
*/
id?: string;
}
```
### `DisplayUpdateContactByIdOptions`
[Section titled âDisplayUpdateContactByIdOptionsâ](#displayupdatecontactbyidoptions)
Options for displaying the native update contact UI.
```typescript
export interface DisplayUpdateContactByIdOptions {
/**
* The ID of the contact to update.
*
* @since 1.0.0
*/
id: string;
}
```
### `GetAccountsResult`
[Section titled âGetAccountsResultâ](#getaccountsresult)
Result from getting accounts.
```typescript
export interface GetAccountsResult {
/**
* List of accounts available on the device.
*
* @since 1.0.0
*/
accounts: Account[];
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-contentsquare
> Internal native bridge contract implemented by Capacitor.
## Overview
[Section titled âOverviewâ](#overview)
Internal native bridge contract implemented by Capacitor.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `optIn`
* `optOut`
* `sendScreenName`
* `sendTransaction`
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------- | ------------------------------------------------ |
| `optIn` | See the source definitions for current behavior. |
| `optOut` | See the source definitions for current behavior. |
| `sendScreenName` | See the source definitions for current behavior. |
| `sendTransaction` | See the source definitions for current behavior. |
| `sendDynamicVarWithStringValue` | See the source definitions for current behavior. |
| `sendDynamicVarWithIntValue` | See the source definitions for current behavior. |
| `onReady` | See the source definitions for current behavior. |
| `excludeURLForReplay` | See the source definitions for current behavior. |
| `setPIISelectors` | See the source definitions for current behavior. |
| `setCapturedElementsSelector` | See the source definitions for current behavior. |
| `collect` | See the source definitions for current behavior. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-contentsquare](https://github.com/Cap-go/capacitor-contentsquare/).
# Android Notes
> Android-specific validation and behavior notes for the Contentsquare Capacitor 8 plugin.
Android does not require extra host-app setup for the plugin itself. Once installed and synced, the plugin registers the main Capacitor `WebView`, injects the Contentsquare event bridge, and exposes the documented JavaScript APIs.
## What the plugin does on Android
[Section titled âWhat the plugin does on Androidâ](#what-the-plugin-does-on-android)
* Registers the Capacitor `WebView` with the native Contentsquare SDK.
* Exposes `optIn`, `optOut`, `sendScreenName`, `sendTransaction`, and dynamic variable APIs.
* Injects replay-related commands such as URL exclusion, PII masking, and captured element selectors.
## Validation tips
[Section titled âValidation tipsâ](#validation-tips)
### Check native logs
[Section titled âCheck native logsâ](#check-native-logs)
Filter Android Studio `Logcat` with:
```text
CSLIB
```
You should see the native Contentsquare SDK startup message and the WebView bridge registration during app launch.
### Track a first session
[Section titled âTrack a first sessionâ](#track-a-first-session)
```typescript
import { ContentsquarePlugin } from '@capgo/capacitor-contentsquare';
await ContentsquarePlugin.optIn();
await ContentsquarePlugin.sendScreenName('Home');
```
Without at least one screenview, the session is not kept by Contentsquare.
## Dynamic variable constraints
[Section titled âDynamic variable constraintsâ](#dynamic-variable-constraints)
* Keys are limited by Contentsquare to 512 characters.
* Values must be either a string or a non-negative integer.
* If you want a value on every session, send it again when the app returns to foreground.
# Getting Started
> Install and configure the Contentsquare Capacitor plugin for analytics and session replay.
1. **Install the plugin**
* npm
```sh
npm i @capgo/capacitor-contentsquare
```
* pnpm
```sh
pnpm add @capgo/capacitor-contentsquare
```
* yarn
```sh
yarn add @capgo/capacitor-contentsquare
```
* bun
```sh
bun add @capgo/capacitor-contentsquare
```
2. **Sync native platforms**
* npm
```sh
npx cap sync
```
* pnpm
```sh
pnpm cap sync
```
* yarn
```sh
yarn cap sync
```
* bun
```sh
bunx cap sync
```
3. **Review the upstream product configuration**
* Follow the official [Contentsquare Capacitor guide](https://docs.contentsquare.com/en/capacitor/) for project keys, replay settings, and dashboard setup.
## Basic usage
[Section titled âBasic usageâ](#basic-usage)
```typescript
import { ContentsquarePlugin, CurrencyCode } from '@capgo/capacitor-contentsquare';
await ContentsquarePlugin.optIn();
await ContentsquarePlugin.sendScreenName('Home');
await ContentsquarePlugin.sendTransaction({
transactionValue: 29.99,
transactionCurrency: CurrencyCode.EUR,
transactionId: 'order-123',
});
await ContentsquarePlugin.sendDynamicVar({
dynVarKey: 'store',
dynVarValue: 'rome',
});
```
## Screen naming tips
[Section titled âScreen naming tipsâ](#screen-naming-tips)
* Use stable names instead of user-specific values.
* Keep the same naming conventions across iOS and Android navigation stacks.
* When the app returns to foreground, resend the screen name and any critical dynamic variables.
## Replay privacy controls
[Section titled âReplay privacy controlsâ](#replay-privacy-controls)
Use the built-in masking helpers to keep sensitive content out of Session Replay:
```typescript
await ContentsquarePlugin.excludeURLForReplay('/checkout/');
await ContentsquarePlugin.setCapturedElementsSelector('[data-cs-capture]');
await ContentsquarePlugin.setPIISelectors({
PIISelectors: ['input[type="email"]', '.credit-card'],
Attributes: [{ selector: 'input[name="email"]', attrName: 'value' }],
});
```
## Platform setup
[Section titled âPlatform setupâ](#platform-setup)
* For iOS in-app features, complete the extra deeplink wiring in the [iOS setup](/docs/plugins/contentsquare/ios/) page.
* Android does not need extra manifest wiring for the plugin itself; see [Android notes](/docs/plugins/contentsquare/android/) for logging and validation tips.
## Notes
[Section titled âNotesâ](#notes)
* This plugin is a Capacitor 8 community port of the official Contentsquare Capacitor package.
* The JavaScript API stays aligned with the current Contentsquare Capacitor docs, while the packaging and native build setup target Capacitor 8.
# iOS Setup
> Configure the required iOS deeplink hooks for Contentsquare in-app features in Capacitor apps.
Contentsquare tracking starts automatically once the plugin is installed, but iOS in-app features such as SDK logs, screenshot capture, and replay configuration still need the upstream URL handling setup.
## 1. Add the URL scheme
[Section titled â1. Add the URL schemeâ](#1-add-the-url-scheme)
Add `cs-$(PRODUCT_BUNDLE_IDENTIFIER)` to your app URL schemes in Xcode or your host appâs `Info.plist`.
```xml
CFBundleURLTypesCFBundleURLSchemescs-$(PRODUCT_BUNDLE_IDENTIFIER)
```
## 2. Forward Contentsquare deeplinks
[Section titled â2. Forward Contentsquare deeplinksâ](#2-forward-contentsquare-deeplinks)
Wherever your Capacitor host app handles incoming URLs, forward them to the native SDK:
### AppDelegate
[Section titled âAppDelegateâ](#appdelegate)
```swift
import ContentsquareModule
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
Contentsquare.handle(url: url)
return true
}
```
### SceneDelegate
[Section titled âSceneDelegateâ](#scenedelegate)
```swift
import ContentsquareModule
func scene(_ scene: UIScene, openURLContexts urlContexts: Set) {
if let url = urlContexts.first?.url {
Contentsquare.handle(url: url)
}
}
```
### SwiftUI
[Section titled âSwiftUIâ](#swiftui)
```swift
import ContentsquareModule
.onOpenURL { url in
Contentsquare.handle(url: url)
}
```
## 3. Validate the installation
[Section titled â3. Validate the installationâ](#3-validate-the-installation)
* Launch the app on a device or simulator.
* Filter Xcode or Console logs with `CSLIB`.
* Open the Contentsquare mobile tooling and trigger in-app features to confirm the deeplink is handled.
# @capgo/capacitor-crisp
> Crisp Chat SDK Plugin for Capacitor. Provides live chat and customer support functionality through Crisp.chat.
## Overview
[Section titled âOverviewâ](#overview)
Crisp Chat SDK Plugin for Capacitor. Provides live chat and customer support functionality through Crisp.chat.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `configure` - Configure the Crisp SDK with your website ID. Must be called before using any other methods.
* `openMessenger` - Open the Crisp messenger chat window. Shows the chat interface to the user.
* `setTokenID` - Set a unique token ID for the current user session. Used to identify and restore previous conversations.
* `setUser` - Set user information for the current session. Updates the user profile visible to support agents.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | -------------------------------------------------------------------------------------------------------- |
| `configure` | Configure the Crisp SDK with your website ID. Must be called before using any other methods. |
| `openMessenger` | Open the Crisp messenger chat window. Shows the chat interface to the user. |
| `setTokenID` | Set a unique token ID for the current user session. Used to identify and restore previous conversations. |
| `setUser` | Set user information for the current session. Updates the user profile visible to support agents. |
| `pushEvent` | Push a custom event to Crisp. Useful for tracking user actions and behavior. |
| `setCompany` | Set company information for the current session. Associates the user with a company in Crisp. |
| `setInt` | Set a custom integer data field. Stores numerical data associated with the user session. |
| `setString` | Set a custom string data field. Stores text data associated with the user session. |
| `sendMessage` | Send a message from the user to the chat. Programmatically send a message as if the user typed it. |
| `setSegment` | Set a user segment for targeting and organization. Used to categorize users in the Crisp dashboard. |
| `reset` | Reset the Crisp session. Clears all user data and starts a fresh session. Useful when user logs out. |
| `getPluginVersion` | Get the plugin version number. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-crisp](https://github.com/Cap-go/capacitor-crisp/).
# Getting Started
> Install @capgo/capacitor-crisp and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-crisp
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `configure`
[Section titled âconfigureâ](#configure)
Configure the Crisp SDK with your website ID. Must be called before using any other methods.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.configure({ websiteID: 'YOUR_WEBSITE_ID' });
```
### `openMessenger`
[Section titled âopenMessengerâ](#openmessenger)
Open the Crisp messenger chat window. Shows the chat interface to the user.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CapacitorCrisp.openMessenger();
```
### `setTokenID`
[Section titled âsetTokenIDâ](#settokenid)
Set a unique token ID for the current user session. Used to identify and restore previous conversations.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CapacitorCrisp.setTokenID({} as { tokenID: string });
```
### `setUser`
[Section titled âsetUserâ](#setuser)
Set user information for the current session. Updates the user profile visible to support agents.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.setUser({
nickname: 'John Doe',
email: 'john@example.com',
phone: '+1234567890'
});
```
### `pushEvent`
[Section titled âpushEventâ](#pushevent)
Push a custom event to Crisp. Useful for tracking user actions and behavior.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.pushEvent({
name: 'completed_purchase',
color: 'green'
});
```
### `setCompany`
[Section titled âsetCompanyâ](#setcompany)
Set company information for the current session. Associates the user with a company in Crisp.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.setCompany({
name: 'Acme Corp',
url: 'https://acme.com',
employment: ['CEO', 'Executive'],
geolocation: ['USA', 'San Francisco']
});
```
### `setInt`
[Section titled âsetIntâ](#setint)
Set a custom integer data field. Stores numerical data associated with the user session.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.setInt({ key: 'user_level', value: 42 });
```
### `setString`
[Section titled âsetStringâ](#setstring)
Set a custom string data field. Stores text data associated with the user session.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.setString({ key: 'subscription_tier', value: 'premium' });
```
### `sendMessage`
[Section titled âsendMessageâ](#sendmessage)
Send a message from the user to the chat. Programmatically send a message as if the user typed it.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.sendMessage({ value: 'Hello, I need help!' });
```
### `setSegment`
[Section titled âsetSegmentâ](#setsegment)
Set a user segment for targeting and organization. Used to categorize users in the Crisp dashboard.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CrispPlugin.setSegment({ segment: 'premium-users' });
```
### `reset`
[Section titled âresetâ](#reset)
Reset the Crisp session. Clears all user data and starts a fresh session. Useful when user logs out.
```typescript
import { CapacitorCrisp } from '@capgo/capacitor-crisp';
await CapacitorCrisp.reset();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ConfigureOptions`
[Section titled âConfigureOptionsâ](#configureoptions)
Configuration for initializing Crisp.
```typescript
export interface ConfigureOptions {
/**
* Your Crisp website ID from dashboard.
*/
websiteID: string;
/**
* Optional - Locale to force in the Crisp chat widget (ISO 639-1), eg. `en`, `fr`, `es`.
* Web + Android: overrides the runtime locale. iOS follows the device/app locale.
*/
locale?: string;
/**
* Optional - Unique token identifier for the user session continuity.
*/
tokenID?: string;
}
```
### `eventColor`
[Section titled âeventColorâ](#eventcolor)
Available colors for Crisp events. Used to visually categorize events in the Crisp dashboard.
```typescript
export type eventColor =
| 'red'
| 'orange'
| 'yellow'
| 'green'
| 'blue'
| 'purple'
| 'pink'
| 'brown'
| 'grey'
| 'black';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-data-storage-sqlite
> SQLite Storage of key/value strings pair.
## Overview
[Section titled âOverviewâ](#overview)
SQLite Storage of key/value strings pair.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `openStore` - Open a store.
* `closeStore` - Close the Store.
* `isStoreOpen` - Check if the Store is opened.
* `isStoreExists` - Check if the Store exists.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------- |
| `openStore` | Open a store. |
| `closeStore` | Close the Store. |
| `isStoreOpen` | Check if the Store is opened. |
| `isStoreExists` | Check if the Store exists. |
| `deleteStore` | Delete a store. |
| `setTable` | Set or Add a table to an existing store. |
| `set` | Store a data with given key and value. |
| `get` | Retrieve a data value for a given data key. |
| `remove` | Remove a data with given key. |
| `clear` | Clear the Data Store (delete all keys). |
| `iskey` | Check if a data key exists. |
| `keys` | Get the data key list. |
| `values` | Get the data value list. |
| `filtervalues` | Get the data value list for filter keys. |
| `keysvalues` | Get the data key/value pair list. |
| `isTable` | Check if a table exists. |
| `tables` | Get the table list for the current store. |
| `deleteTable` | Delete a table. |
| `importFromJson` | Import a database From a JSON. |
| `isJsonValid` | Check the validity of a JSON Object. |
| `exportToJson` | Export the given database to a JSON Object. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-data-storage-sqlite](https://github.com/Cap-go/capacitor-data-storage-sqlite/).
# Getting Started
> Install @capgo/capacitor-data-storage-sqlite and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-data-storage-sqlite
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `openStore`
[Section titled âopenStoreâ](#openstore)
Open a store
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.openStore({} as capOpenStorageOptions);
```
### `closeStore`
[Section titled âcloseStoreâ](#closestore)
Close the Store
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.closeStore({} as capStorageOptions);
```
### `isStoreOpen`
[Section titled âisStoreOpenâ](#isstoreopen)
Check if the Store is opened
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.isStoreOpen({} as capStorageOptions);
```
### `isStoreExists`
[Section titled âisStoreExistsâ](#isstoreexists)
Check if the Store exists
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.isStoreExists({} as capStorageOptions);
```
### `deleteStore`
[Section titled âdeleteStoreâ](#deletestore)
Delete a store
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.deleteStore({} as capOpenStorageOptions);
```
### `setTable`
[Section titled âsetTableâ](#settable)
Set or Add a table to an existing store
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.setTable({} as capTableStorageOptions);
```
### `set`
[Section titled âsetâ](#set)
Store a data with given key and value
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.set({} as capDataStorageOptions);
```
### `get`
[Section titled âgetâ](#get)
Retrieve a data value for a given data key
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.get({} as capDataStorageOptions);
```
### `remove`
[Section titled âremoveâ](#remove)
Remove a data with given key
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.remove({} as capDataStorageOptions);
```
### `clear`
[Section titled âclearâ](#clear)
Clear the Data Store (delete all keys)
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.clear();
```
### `iskey`
[Section titled âiskeyâ](#iskey)
Check if a data key exists
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.iskey({} as capDataStorageOptions);
```
### `keys`
[Section titled âkeysâ](#keys)
Get the data key list
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.keys();
```
### `values`
[Section titled âvaluesâ](#values)
Get the data value list
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.values();
```
### `filtervalues`
[Section titled âfiltervaluesâ](#filtervalues)
Get the data value list for filter keys
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.filtervalues({} as capFilterStorageOptions);
```
### `keysvalues`
[Section titled âkeysvaluesâ](#keysvalues)
Get the data key/value pair list
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.keysvalues();
```
### `isTable`
[Section titled âisTableâ](#istable)
Check if a table exists
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.isTable({} as capTableStorageOptions);
```
### `tables`
[Section titled âtablesâ](#tables)
Get the table list for the current store
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.tables();
```
### `deleteTable`
[Section titled âdeleteTableâ](#deletetable)
Delete a table
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.deleteTable({} as capTableStorageOptions);
```
### `importFromJson`
[Section titled âimportFromJsonâ](#importfromjson)
Import a database From a JSON
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.importFromJson({} as capStoreImportOptions);
```
### `isJsonValid`
[Section titled âisJsonValidâ](#isjsonvalid)
Check the validity of a JSON Object
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.isJsonValid({} as capStoreImportOptions);
```
### `exportToJson`
[Section titled âexportToJsonâ](#exporttojson)
Export the given database to a JSON Object
```typescript
import { CapgoCapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
await CapgoCapacitorDataStorageSqlite.exportToJson();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `capOpenStorageOptions`
[Section titled âcapOpenStorageOptionsâ](#capopenstorageoptions)
```typescript
export interface capOpenStorageOptions {
/**
* The storage database name
*/
database?: string; // default:
// ios, android: storageSQLite
// web : storageIDB
/**
* The storage table name
*/
table?: string; // default:
// ios, android: storage_table
// web: storage_store
/**
* Set to true for database encryption
*/
encrypted?: boolean; // only for ios and android
/***
* Set the mode for database encryption
* ["encryption", "secret","newsecret"]
*/
mode?: string; // only for ios and android
}
```
### `capStorageOptions`
[Section titled âcapStorageOptionsâ](#capstorageoptions)
```typescript
export interface capStorageOptions {
/**
* The storage name
*/
database: string;
}
```
### `capDataStorageResult`
[Section titled âcapDataStorageResultâ](#capdatastorageresult)
```typescript
export interface capDataStorageResult {
/**
* result set to true when successful else false
*/
result?: boolean;
/**
* a returned message
*/
message?: string;
}
```
### `capTableStorageOptions`
[Section titled âcapTableStorageOptionsâ](#captablestorageoptions)
```typescript
export interface capTableStorageOptions {
/**
* The storage table name
*/
table: string;
}
```
### `capDataStorageOptions`
[Section titled âcapDataStorageOptionsâ](#capdatastorageoptions)
```typescript
export interface capDataStorageOptions {
/**
* The data name
*/
key: string;
/**
* The data value when required
*/
value?: string;
}
```
### `capValueResult`
[Section titled âcapValueResultâ](#capvalueresult)
```typescript
export interface capValueResult {
/**
* the data value for a given data key
*/
value: string;
}
```
### `capKeysResult`
[Section titled âcapKeysResultâ](#capkeysresult)
```typescript
export interface capKeysResult {
/**
* the data key list as an Array
*/
keys: string[];
}
```
### `capValuesResult`
[Section titled âcapValuesResultâ](#capvaluesresult)
```typescript
export interface capValuesResult {
/**
* the data values list as an Array
*/
values: string[];
}
```
### `capFilterStorageOptions`
[Section titled âcapFilterStorageOptionsâ](#capfilterstorageoptions)
```typescript
export interface capFilterStorageOptions {
/**
* The filter data for filtering keys
*
* ['%filter', 'filter', 'filter%'] for
* [starts with filter, contains filter, ends with filter]
*/
filter: string;
}
```
### `capKeysValuesResult`
[Section titled âcapKeysValuesResultâ](#capkeysvaluesresult)
```typescript
export interface capKeysValuesResult {
/**
* the data keys/values list as an Array of {key:string,value:string}
*/
keysvalues: any[];
}
```
### `capTablesResult`
[Section titled âcapTablesResultâ](#captablesresult)
```typescript
export interface capTablesResult {
/**
* the tables list as an Array
*/
tables: string[];
}
```
### `capStoreImportOptions`
[Section titled âcapStoreImportOptionsâ](#capstoreimportoptions)
```typescript
export interface capStoreImportOptions {
/**
* Set the JSON object to import
*
*/
jsonstring?: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-document-scanner
> Capacitor plugin to scan document iOS and Android.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin to scan document iOS and Android.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `scanDocument` - Opens the device camera and starts the document scanning experience.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------- | -------------------------------------------------------------------- |
| `scanDocument` | Opens the device camera and starts the document scanning experience. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-document-scanner](https://github.com/Cap-go/capacitor-document-scanner/).
# Getting Started
> Install @capgo/capacitor-document-scanner and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-document-scanner
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { DocumentScanner } from '@capgo/capacitor-document-scanner';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `scanDocument`
[Section titled âscanDocumentâ](#scandocument)
Opens the device camera and starts the document scanning experience.
```typescript
import { DocumentScanner } from '@capgo/capacitor-document-scanner';
await DocumentScanner.scanDocument();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ScanDocumentOptions`
[Section titled âScanDocumentOptionsâ](#scandocumentoptions)
```typescript
export interface ScanDocumentOptions {
/**
* Android only: quality of the cropped image from 0 - 100 (100 is best).
* @default 100
*/
croppedImageQuality?: number;
/**
* Allow the user to adjust the detected crop before saving.
* On iOS this forces the native VisionKit preview/editor after each capture using
* the private VisionKit navigation hooks needed to keep the scanner flow alive.
* On Android this enables ML Kit's crop adjustment flow.
* @default true
*/
letUserAdjustCrop?: boolean;
/**
* When enabled, shows the current scanned page before continuing so the user can
* review it and explicitly continue or finish the flow.
* On iOS this forces the native VisionKit preview/editor between captures.
* On Android this switches to a one-page-at-a-time flow between ML Kit sessions.
* The review/editor screen is still shown automatically when the scan limit is reached.
* @default false
*/
reviewCapturedDocument?: boolean;
/**
* Maximum number of documents to scan.
* On iOS: VisionKit caps scans at 24 pages (system limit), and the hacked native flow
* can still stop earlier when you pass a smaller limit.
* On Android: customizable limit; defaults to 20 for performance (clamped 1-24).
* Set to 1 for single-scan mode where the scanner stops after one document.
* @default 20 on Android, 24 on iOS
*/
maxNumDocuments?: number;
/**
* Format to return scanned images in (file paths or base64 strings).
* @default ResponseType.ImageFilePath
*/
responseType?: ResponseType;
/**
* Brightness adjustment applied to scanned images.
* Range: -255 to 255 (0 = no change, positive = brighter, negative = darker)
* Useful for compensating low-light scans.
* @default 0
*/
brightness?: number;
/**
* Contrast adjustment applied to scanned images.
* Range: 0.0 to 10.0 (1.0 = no change, >1 = more contrast, <1 = less contrast)
* Helps improve text clarity in poorly lit scans.
* @default 1.0
*/
contrast?: number;
/**
* Android only: scanner mode that controls ML Kit features and filters.
* - 'base': Basic scan with crop/rotate, no filters or ML cleaning
* - 'base_with_filter': Adds grayscale and auto-enhancement filters
* - 'full': All features including ML-based image cleaning (erases stains, fingers, etc.)
* @default ScannerMode.Full
*/
scannerMode?: ScannerMode;
}
```
### `ScanDocumentResponse`
[Section titled âScanDocumentResponseâ](#scandocumentresponse)
```typescript
export interface ScanDocumentResponse {
/**
* Scanned images in the requested response format.
*/
scannedImages?: string[];
/**
* Indicates whether the scan completed or was cancelled.
*/
status?: ScanDocumentResponseStatus;
/**
* Get the native Capacitor plugin version
*
* @returns {Promise<{ id: string }>} an Promise with version for this device
* @throws An error if the something went wrong
*/
getPluginVersion(): Promise<{ version: string }>;
}
```
### `ResponseType`
[Section titled âResponseTypeâ](#responsetype)
```typescript
export enum ResponseType {
/**
* Return scanned images as base64-encoded strings.
*/
Base64 = 'base64',
/**
* Return scanned images as file paths on disk.
*/
ImageFilePath = 'imageFilePath',
}
```
### `ScannerMode`
[Section titled âScannerModeâ](#scannermode)
```typescript
export enum ScannerMode {
/**
* Basic document scanning with crop and rotate features only.
* No filters or ML-based enhancements.
*/
Base = 'base',
/**
* Basic features plus automatic filters (grayscale, auto-enhancement).
*/
BaseWithFilter = 'base_with_filter',
/**
* Full feature set including ML-based image cleaning.
* Automatically removes stains, fingers, and other artifacts.
*/
Full = 'full',
}
```
### `ScanDocumentResponseStatus`
[Section titled âScanDocumentResponseStatusâ](#scandocumentresponsestatus)
```typescript
export enum ScanDocumentResponseStatus {
/**
* The scan completed successfully.
*/
Success = 'success',
/**
* The user cancelled the scan flow.
*/
Cancel = 'cancel',
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-downloader
> Capacitor plugin for downloading files with background support. Provides resumable downloads with progress tracking.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for downloading files with background support. Provides resumable downloads with progress tracking.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `download` - Start a new download task.
* `pause` - Pause an active download. Download can be resumed later from the same position.
* `resume` - Resume a paused download. Continues from where it was paused.
* `stop` - Stop and cancel a download permanently. Downloaded data will be deleted.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | -------------------------------------------------------------------------------- |
| `download` | Start a new download task. |
| `pause` | Pause an active download. Download can be resumed later from the same position. |
| `resume` | Resume a paused download. Continues from where it was paused. |
| `stop` | Stop and cancel a download permanently. Downloaded data will be deleted. |
| `checkStatus` | Check the current status of a download. |
| `getFileInfo` | Get information about a downloaded file. |
| `addListener` | Listen for download progress updates. Fired periodically as download progresses. |
| `addListener` | Listen for download completion. Fired when a download finishes successfully. |
| `addListener` | Listen for download failures. Fired when a download encounters an error. |
| `removeAllListeners` | Remove all event listeners. Cleanup method to prevent memory leaks. |
| `getPluginVersion` | Get the plugin version number. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-downloader](https://github.com/Cap-go/capacitor-downloader/).
# Getting Started
> Install @capgo/capacitor-downloader and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-downloader
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `download`
[Section titled âdownloadâ](#download)
Start a new download task.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
const task = await Downloader.download({
id: 'my-download',
url: 'https://example.com/file.pdf',
destination: 'downloads/file.pdf'
});
```
### `pause`
[Section titled âpauseâ](#pause)
Pause an active download. Download can be resumed later from the same position.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.pause({} as { id: string });
```
### `resume`
[Section titled âresumeâ](#resume)
Resume a paused download. Continues from where it was paused.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.resume({} as { id: string });
```
### `stop`
[Section titled âstopâ](#stop)
Stop and cancel a download permanently. Downloaded data will be deleted.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.stop({} as { id: string });
```
### `checkStatus`
[Section titled âcheckStatusâ](#checkstatus)
Check the current status of a download.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.checkStatus({} as { id: string });
```
### `getFileInfo`
[Section titled âgetFileInfoâ](#getfileinfo)
Get information about a downloaded file.
```typescript
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.getFileInfo({} as { path: string });
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `DownloadOptions`
[Section titled âDownloadOptionsâ](#downloadoptions)
Configuration options for starting a download.
```typescript
export interface DownloadOptions {
/** Unique identifier for this download task */
id: string;
/** URL of the file to download */
url: string;
/** Local file path where the download will be saved */
destination: string;
/** Optional HTTP headers to include in the request */
headers?: { [key: string]: string };
/** Network type requirement for download */
network?: 'cellular' | 'wifi-only';
/** Download priority level */
priority?: 'high' | 'normal' | 'low';
}
```
### `DownloadTask`
[Section titled âDownloadTaskâ](#downloadtask)
Represents the current state and progress of a download task.
```typescript
export interface DownloadTask {
/** Unique identifier for the download task */
id: string;
/** Download progress from 0 to 100 */
progress: number;
/** Current state of the download */
state: 'PENDING' | 'RUNNING' | 'PAUSED' | 'DONE' | 'ERROR';
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/electron-updater
> Push instant updates to your Electron desktop apps without rebuilding binaries. Same reliable live update system now for desktop.
Tip
New to Capgo? The Electron Updater brings the same powerful live update capabilities from mobile to desktop. If youâre already using `@capgo/capacitor-updater`, youâll feel right at home.
## Why Electron Updater?
[Section titled âWhy Electron Updater?â](#why-electron-updater)
Electronâs built-in auto-updater requires shipping a full new binary for every update. This plugin solves that by enabling JavaScript/HTML/CSS updates without rebuilding.
Instant Updates
Push JavaScript, HTML, and CSS updates directly to users without rebuilding the entire app binary.
Delta Updates
Only download changed files, making updates ultra-fast and bandwidth-efficient.
Rollback Protection
Automatic rollback if an update fails, keeping your app stable for users.
End-to-End Encryption
Secure update delivery with RSA session keys and AES bundle encryption.
## Key Features
[Section titled âKey Featuresâ](#key-features)
* **Live Updates** - Push updates instantly without app store delays
* **Auto-Update** - Automatic update checking and installation
* **Rollback Protection** - Automatic rollback if `notifyAppReady()` isnât called
* **Bundle Management** - Full control over downloaded bundles
* **Channel System** - Deploy to different user groups (production, beta, staging)
* **Delay Conditions** - Control when updates are applied (background, kill, date, native version)
* **Debug Menu** - Built-in debug tools accessible via `Ctrl+Shift+D` / `Cmd+Shift+D`
* **Statistics Reporting** - Track update success rates and user versions
## Feature Parity with Capacitor Updater
[Section titled âFeature Parity with Capacitor Updaterâ](#feature-parity-with-capacitor-updater)
The Electron Updater maintains 100% API compatibility with `@capgo/capacitor-updater`. The same methods, events, and configuration options work across both platforms:
| Feature | Capacitor | Electron |
| --------------------- | ------------ | ----------------- |
| Live Updates | Yes | Yes |
| Channels | Yes | Yes |
| Rollback Protection | Yes | Yes |
| End-to-End Encryption | Yes | Yes |
| Statistics | Yes | Yes |
| Delay Conditions | Yes | Yes |
| Debug Menu | Shake device | Keyboard shortcut |
## Installation
[Section titled âInstallationâ](#installation)
```bash
npm install @capgo/electron-updater
```
## Quick Links
[Section titled âQuick Linksâ](#quick-links)
[Getting Started ](/docs/plugins/electron-updater/getting-started/)Complete setup guide for adding live updates to your Electron app.
[API Reference ](/docs/plugins/electron-updater/api/)All available methods, events, and configuration options.
[Capacitor Updater Docs ](/docs/plugins/updater/)The mobile counterpart - same API, same concepts, for Capacitor apps.
## Documentation
[Section titled âDocumentationâ](#documentation)
* **[Getting Started](/docs/plugins/electron-updater/getting-started/)** - Setup and configuration guide
* **[API Reference](/docs/plugins/electron-updater/api/)** - All methods, events, and options
* **[Getting Started (from Capacitor)](/docs/plugins/electron-updater/getting-started/)** - Moving from Capacitor to Electron
## Community
[Section titled âCommunityâ](#community)
Join the [Discord](https://discord.gg/VnYRvBfgA6) to get help and connect with other developers.
# Electron Updater API Reference
> Complete API reference for @capgo/electron-updater - all methods, events, and configuration options.
This page documents all available methods, events, and configuration options for the Electron Updater.
## Core Methods
[Section titled âCore Methodsâ](#core-methods)
### notifyAppReady()
[Section titled ânotifyAppReady()â](#notifyappready)
**Must be called on every app launch.** Confirms the bundle loaded successfully and prevents automatic rollback.
```typescript
await updater.notifyAppReady();
```
Caution
If not called within `appReadyTimeout` (default 10 seconds), the update is considered failed and the app rolls back to the previous version.
### download(options)
[Section titled âdownload(options)â](#downloadoptions)
Download a bundle from a URL.
```typescript
const bundle = await updater.download({
url: 'https://example.com/bundle.zip',
version: '1.0.1',
checksum: 'sha256-hash', // Optional but recommended
sessionKey: '...', // For encrypted bundles
});
```
**Parameters:**
| Option | Type | Required | Description |
| ------------ | ------ | -------- | --------------------------------- |
| `url` | string | Yes | URL to download the bundle from |
| `version` | string | Yes | Version identifier for the bundle |
| `checksum` | string | No | SHA256 checksum for verification |
| `sessionKey` | string | No | Session key for encrypted bundles |
**Returns:** `BundleInfo` object with `id`, `version`, `status`
### next(options)
[Section titled ânext(options)â](#nextoptions)
Queue a bundle to be loaded on next app restart.
```typescript
await updater.next({ id: 'bundle-id' });
```
**Parameters:**
| Option | Type | Required | Description |
| ------ | ------ | -------- | ------------------ |
| `id` | string | Yes | Bundle ID to queue |
### set(options)
[Section titled âset(options)â](#setoptions)
Immediately switch to a bundle and reload the app.
```typescript
await updater.set({ id: 'bundle-id' });
```
**Parameters:**
| Option | Type | Required | Description |
| ------ | ------ | -------- | --------------------- |
| `id` | string | Yes | Bundle ID to activate |
### reload()
[Section titled âreload()â](#reload)
Manually reload the app with the current bundle.
```typescript
await updater.reload();
```
### delete(options)
[Section titled âdelete(options)â](#deleteoptions)
Delete a bundle from storage.
```typescript
await updater.delete({ id: 'bundle-id' });
```
**Parameters:**
| Option | Type | Required | Description |
| ------ | ------ | -------- | ------------------- |
| `id` | string | Yes | Bundle ID to delete |
### reset(options)
[Section titled âreset(options)â](#resetoptions)
Reset to builtin version or last successful bundle.
```typescript
// Reset to builtin
await updater.reset({ toLastSuccessful: false });
// Reset to last successful bundle
await updater.reset({ toLastSuccessful: true });
```
**Parameters:**
| Option | Type | Required | Description |
| ------------------ | ------- | -------- | ----------------------------------------------------------- |
| `toLastSuccessful` | boolean | No | If true, reset to last successful bundle instead of builtin |
## Bundle Information
[Section titled âBundle Informationâ](#bundle-information)
### current()
[Section titled âcurrent()â](#current)
Get information about the current bundle and native version.
```typescript
const info = await updater.current();
// { bundle: { id, version, status }, native: '1.0.0' }
```
### list(options)
[Section titled âlist(options)â](#listoptions)
List all downloaded bundles.
```typescript
const bundles = await updater.list();
// [{ id, version, status, downloaded, checksum }, ...]
```
### getNextBundle()
[Section titled âgetNextBundle()â](#getnextbundle)
Get the bundle queued for next restart.
```typescript
const next = await updater.getNextBundle();
// { id, version, status } or null
```
### getFailedUpdate()
[Section titled âgetFailedUpdate()â](#getfailedupdate)
Get information about the last failed update (useful for debugging rollbacks).
```typescript
const failed = await updater.getFailedUpdate();
// { id, version, reason } or null
```
### getBuiltinVersion()
[Section titled âgetBuiltinVersion()â](#getbuiltinversion)
Get the version shipped with the app binary.
```typescript
const version = await updater.getBuiltinVersion();
// '1.0.0'
```
## Update Checking
[Section titled âUpdate Checkingâ](#update-checking)
### getLatest(options)
[Section titled âgetLatest(options)â](#getlatestoptions)
Check the server for the latest available version.
```typescript
const latest = await updater.getLatest();
if (latest.url && !latest.error) {
// Update available
console.log('New version:', latest.version);
console.log('Download URL:', latest.url);
} else if (latest.error) {
console.error('Error checking updates:', latest.error);
}
```
**Returns:**
| Property | Type | Description |
| ------------ | ------ | --------------------------------- |
| `url` | string | Download URL (empty if no update) |
| `version` | string | Available version |
| `checksum` | string | SHA256 checksum |
| `sessionKey` | string | Encryption session key |
| `error` | string | Error message if check failed |
| `message` | string | Server message |
## Channel Management
[Section titled âChannel Managementâ](#channel-management)
### setChannel(options)
[Section titled âsetChannel(options)â](#setchanneloptions)
Assign the device to a specific channel.
```typescript
await updater.setChannel({ channel: 'beta' });
```
### unsetChannel(options)
[Section titled âunsetChannel(options)â](#unsetchanneloptions)
Remove channel assignment and use default.
```typescript
await updater.unsetChannel();
```
### getChannel()
[Section titled âgetChannel()â](#getchannel)
Get the current channel assignment.
```typescript
const channel = await updater.getChannel();
// { channel: 'production', status: 'set' }
```
### listChannels()
[Section titled âlistChannels()â](#listchannels)
List all available channels for this app.
```typescript
const channels = await updater.listChannels();
// ['production', 'beta', 'staging']
```
## Delay Conditions
[Section titled âDelay Conditionsâ](#delay-conditions)
Control when downloaded updates are applied.
### setMultiDelay(options)
[Section titled âsetMultiDelay(options)â](#setmultidelayoptions)
Set conditions that must be met before an update is applied.
```typescript
// Wait for app to be backgrounded
await updater.setMultiDelay({
delayConditions: [{ kind: 'background' }]
});
// Wait until specific date
await updater.setMultiDelay({
delayConditions: [{ kind: 'date', value: '2024-12-25T00:00:00Z' }]
});
// Wait for app to be killed and restarted
await updater.setMultiDelay({
delayConditions: [{ kind: 'kill' }]
});
// Multiple conditions (all must be met)
await updater.setMultiDelay({
delayConditions: [
{ kind: 'background' },
{ kind: 'date', value: '2024-12-25T00:00:00Z' }
]
});
```
**Delay Condition Types:**
| Kind | Value | Description |
| --------------- | ---------------------- | --------------------------------------- |
| `background` | Optional duration (ms) | Wait for app to be backgrounded |
| `kill` | - | Wait for app to be killed and restarted |
| `date` | ISO date string | Wait until specific date/time |
| `nativeVersion` | Version string | Wait for native app update |
### cancelDelay()
[Section titled âcancelDelay()â](#canceldelay)
Clear all delay conditions and apply update immediately on next check.
```typescript
await updater.cancelDelay();
```
## Device Identification
[Section titled âDevice Identificationâ](#device-identification)
### getDeviceId()
[Section titled âgetDeviceId()â](#getdeviceid)
Get the unique device identifier.
```typescript
const deviceId = await updater.getDeviceId();
// 'uuid-xxxx-xxxx-xxxx'
```
### setCustomId(options)
[Section titled âsetCustomId(options)â](#setcustomidoptions)
Set a custom identifier for the device (useful for analytics).
```typescript
await updater.setCustomId({ customId: 'user-123' });
```
## Configuration
[Section titled âConfigurationâ](#configuration)
### setUpdateUrl(options)
[Section titled âsetUpdateUrl(options)â](#setupdateurloptions)
Change the update server URL at runtime.
```typescript
await updater.setUpdateUrl({ url: 'https://my-server.com/updates' });
```
Note
Requires `allowModifyUrl: true` in the constructor options.
### setStatsUrl(options)
[Section titled âsetStatsUrl(options)â](#setstatsurloptions)
Change the statistics reporting URL.
```typescript
await updater.setStatsUrl({ url: 'https://my-server.com/stats' });
```
### setChannelUrl(options)
[Section titled âsetChannelUrl(options)â](#setchannelurloptions)
Change the channel management URL.
```typescript
await updater.setChannelUrl({ url: 'https://my-server.com/channel' });
```
### setAppId(options)
[Section titled âsetAppId(options)â](#setappidoptions)
Change the App ID at runtime.
```typescript
await updater.setAppId({ appId: 'com.example.newapp' });
```
Note
Requires `allowModifyAppId: true` in the constructor options.
### getAppId()
[Section titled âgetAppId()â](#getappid)
Get the current App ID.
```typescript
const appId = await updater.getAppId();
```
## Debug
[Section titled âDebugâ](#debug)
### setDebugMenu(options)
[Section titled âsetDebugMenu(options)â](#setdebugmenuoptions)
Enable or disable the debug menu.
```typescript
await updater.setDebugMenu({ enabled: true });
```
### isDebugMenuEnabled()
[Section titled âisDebugMenuEnabled()â](#isdebugmenuenabled)
Check if the debug menu is enabled.
```typescript
const enabled = await updater.isDebugMenuEnabled();
```
## Events
[Section titled âEventsâ](#events)
Listen to update events using `addListener`:
```typescript
updater.addListener('eventName', (event) => {
// Handle event
});
```
### Available Events
[Section titled âAvailable Eventsâ](#available-events)
| Event | Payload | Description |
| ------------------- | --------------------- | ------------------------------------------------------ |
| `download` | `{ percent, status }` | Download progress updates |
| `updateAvailable` | `{ bundle }` | New update available |
| `noNeedUpdate` | `{ message }` | Already up-to-date |
| `downloadComplete` | `{ bundle }` | Download finished successfully |
| `downloadFailed` | `{ bundle, error }` | Download failed |
| `breakingAvailable` | `{ bundle }` | Incompatible update available (requires native update) |
| `updateFailed` | `{ bundle, reason }` | Update installation failed |
| `appReloaded` | `{}` | App was reloaded |
| `appReady` | `{}` | `notifyAppReady()` was called |
### Example: Full Event Handling
[Section titled âExample: Full Event Handlingâ](#example-full-event-handling)
```typescript
// Progress tracking
updater.addListener('download', (event) => {
updateProgressBar(event.percent);
});
// Update available notification
updater.addListener('updateAvailable', (event) => {
showNotification(`Update ${event.bundle.version} available!`);
});
// Handle completion
updater.addListener('downloadComplete', async (event) => {
// Queue for next restart
await updater.next({ id: event.bundle.id });
showNotification('Update will apply on next restart');
});
// Handle failures
updater.addListener('updateFailed', (event) => {
console.error('Update failed:', event.reason);
reportError(event);
});
```
## Constructor Options
[Section titled âConstructor Optionsâ](#constructor-options)
Full configuration options for `ElectronUpdater`:
```typescript
const updater = new ElectronUpdater({
// Required
appId: 'com.example.app',
// Version override
version: '1.0.0', // Override builtin version detection
// Server URLs
updateUrl: 'https://plugin.capgo.app/updates',
channelUrl: 'https://plugin.capgo.app/channel_self',
statsUrl: 'https://plugin.capgo.app/stats',
// Behavior
autoUpdate: true, // Enable automatic update checks
appReadyTimeout: 10000, // Milliseconds before rollback (default: 10000)
autoDeleteFailed: true, // Auto-delete failed bundles
autoDeletePrevious: true, // Auto-delete old bundles
resetWhenUpdate: true, // Reset to builtin on native update
// Channels
defaultChannel: 'production',
// Direct Update Mode
directUpdate: false, // 'atInstall' | 'onLaunch' | 'always' | false
// Security
publicKey: '...', // RSA public key for E2E encryption
// Dynamic Configuration
allowModifyUrl: false, // Allow runtime URL changes
allowModifyAppId: false, // Allow runtime App ID changes
persistCustomId: false, // Persist custom ID across updates
persistModifyUrl: false, // Persist URL changes
// Debug
debugMenu: false, // Enable debug menu (Ctrl+Shift+D)
disableJSLogging: false, // Disable console logs
// Periodic Updates
periodCheckDelay: 0, // Seconds between auto-checks (0 = disabled, min 600)
});
```
# Getting Started with Electron Updater
> Complete setup guide for adding Capgo live updates to your Electron application.
This guide walks you through setting up `@capgo/electron-updater` in your Electron application to enable live JavaScript/HTML/CSS updates.
Tip
Already using Capgo with Capacitor? The Electron Updater uses the same Capgo Cloud backend, so you can manage both mobile and desktop apps from the same dashboard.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
* Electron 20.0.0 or higher
* Node.js 18 or higher
* A Capgo account (sign up at [capgo.app](https://capgo.app))
## Installation
[Section titled âInstallationâ](#installation)
1. Install the package:
```bash
bun add @capgo/electron-updater
```
2. Get your App ID from the Capgo dashboard. If you havenât created an app yet, run:
```bash
npx @capgo/cli@latest init
```
## Setup
[Section titled âSetupâ](#setup)
The Electron Updater requires setup in three places: main process, preload script, and renderer process.
### Main Process
[Section titled âMain Processâ](#main-process)
main.ts
```typescript
import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import {
ElectronUpdater,
setupIPCHandlers,
setupEventForwarding,
} from '@capgo/electron-updater';
// Create updater instance with your Capgo App ID
const updater = new ElectronUpdater({
appId: 'YOUR_CAPGO_APP_ID', // e.g., 'com.example.myapp'
autoUpdate: true,
});
app.whenReady().then(async () => {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
},
});
// Initialize updater with window and builtin path
const builtinPath = path.join(__dirname, 'www/index.html');
await updater.initialize(mainWindow, builtinPath);
// Setup IPC communication between main and renderer
setupIPCHandlers(updater);
setupEventForwarding(updater, mainWindow);
// Load the current bundle (either builtin or downloaded update)
await mainWindow.loadFile(updater.getCurrentBundlePath());
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
```
### Preload Script
[Section titled âPreload Scriptâ](#preload-script)
preload.ts
```typescript
import { exposeUpdaterAPI } from '@capgo/electron-updater/preload';
// Expose the updater API to the renderer process
exposeUpdaterAPI();
```
### Renderer Process
[Section titled âRenderer Processâ](#renderer-process)
```typescript
// renderer.ts (or in your app's entry point)
import { requireUpdater } from '@capgo/electron-updater/renderer';
const updater = requireUpdater();
// CRITICAL: Call this on every app launch!
// This confirms the bundle loaded successfully and prevents rollback
await updater.notifyAppReady();
console.log('App ready, current bundle:', await updater.current());
```
Caution
You **must** call `notifyAppReady()` within 10 seconds of app launch (configurable via `appReadyTimeout`). If not called, the updater assumes the update failed and rolls back to the previous version.
## Checking for Updates
[Section titled âChecking for Updatesâ](#checking-for-updates)
With `autoUpdate: true`, the updater automatically checks for updates. You can also trigger manual checks:
```typescript
// Check for updates manually
const latest = await updater.getLatest();
if (latest.url && !latest.error) {
console.log('Update available:', latest.version);
// Download the update
const bundle = await updater.download({
url: latest.url,
version: latest.version,
checksum: latest.checksum,
});
console.log('Downloaded bundle:', bundle.id);
// Option 1: Queue for next restart
await updater.next({ id: bundle.id });
// Option 2: Apply immediately and reload
// await updater.set({ id: bundle.id });
}
```
## Listening to Events
[Section titled âListening to Eventsâ](#listening-to-events)
Track update progress and status with events:
```typescript
// Download progress
updater.addListener('download', (event) => {
console.log(`Download progress: ${event.percent}%`);
});
// Update available
updater.addListener('updateAvailable', (event) => {
console.log('New version available:', event.bundle.version);
});
// Download completed
updater.addListener('downloadComplete', (event) => {
console.log('Download finished:', event.bundle.id);
});
// Update failed
updater.addListener('updateFailed', (event) => {
console.error('Update failed:', event.bundle.version);
});
```
## Deploying Updates
[Section titled âDeploying Updatesâ](#deploying-updates)
Use the Capgo CLI to upload updates:
```bash
# Build your app
npm run build
# Upload to Capgo
npx @capgo/cli@latest bundle upload --channel=production
```
Your Electron app will automatically detect and download the new bundle on next check.
## Debug Menu
[Section titled âDebug Menuâ](#debug-menu)
Enable the debug menu during development:
```typescript
const updater = new ElectronUpdater({
appId: 'YOUR_CAPGO_APP_ID',
debugMenu: true, // Enable debug menu
});
```
Press `Ctrl+Shift+D` (or `Cmd+Shift+D` on Mac) to open the debug menu and:
* View current bundle information
* Switch between available bundles
* Reset to builtin version
* View device and channel info
## Configuration Options
[Section titled âConfiguration Optionsâ](#configuration-options)
```typescript
const updater = new ElectronUpdater({
// Required
appId: 'com.example.app',
// Server URLs (defaults to Capgo Cloud)
updateUrl: 'https://plugin.capgo.app/updates',
channelUrl: 'https://plugin.capgo.app/channel_self',
statsUrl: 'https://plugin.capgo.app/stats',
// Behavior
autoUpdate: true, // Enable auto-updates
appReadyTimeout: 10000, // MS before rollback (default: 10s)
autoDeleteFailed: true, // Delete failed bundles
autoDeletePrevious: true, // Delete old bundles after successful update
// Channels
defaultChannel: 'production',
// Security
publicKey: '...', // For end-to-end encryption
// Debug
debugMenu: false, // Enable debug menu
disableJSLogging: false, // Disable console logs
// Periodic Updates
periodCheckDelay: 0, // Seconds between checks (0 = disabled, min 600)
});
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* [API Reference](/docs/plugins/electron-updater/api/) - Explore all available methods
* [Channels](/docs/live-updates/channels/) - Learn about deployment channels
* [Rollbacks](/docs/live-updates/rollbacks/) - Understand rollback protection
# @capgo/capacitor-env
> Capacitor plugin for accessing environment variables in native code.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for accessing environment variables in native code.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getKey` - Retrieves the value of a specific environment variable by key.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | -------------------------------------------------------------- |
| `getKey` | Retrieves the value of a specific environment variable by key. |
| `getPluginVersion` | Get the version of the native Capacitor plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-env](https://github.com/Cap-go/capacitor-env/).
# Getting Started
> Install @capgo/capacitor-env and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-env
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { Env } from '@capgo/capacitor-env';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getKey`
[Section titled âgetKeyâ](#getkey)
Retrieves the value of a specific environment variable by key.
This method fetches environment variables that were set during the native build process. The variables must be configured in the native project before they can be accessed at runtime.
```typescript
import { Env } from '@capgo/capacitor-env';
const result = await EnvPlugin.getKey({ key: 'API_URL' });
console.log(result.value); // 'https://api.example.com'
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-facebook-analytics
> Log Meta/Facebook App Events, purchases, value-bearing standard events, and advertiser tracking status from Capacitor.
## Overview
[Section titled âOverviewâ](#overview)
`@capgo/capacitor-facebook-analytics` wraps Meta App Events for Capacitor apps on iOS and Android.
Use it to log standard Facebook events, custom events, purchases, and value-bearing events with currency metadata. It also exposes advertiser tracking controls for Android and legacy iOS, while reporting App Tracking Transparency authorization on iOS 17 and above.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `initAppEvents` - Activate Facebook App Events manually when automatic app event logging is disabled.
* `logEvent` - Log standard or custom App Events with optional parameters, value, and currency.
* `logPurchase` - Log purchase events with amount, currency, and optional parameters.
* `enableAdvertiserTracking` - Enable advertiser ID collection where the native SDK still supports explicit toggling.
* `disableAdvertiserTracking` - Disable advertiser ID collection where the native SDK still supports explicit toggling.
* `getAdvertiserTrackingStatus` - Read the current advertiser tracking status.
## Platform Support
[Section titled âPlatform Supportâ](#platform-support)
| Platform | Support |
| -------- | ---------------- |
| iOS | Supported |
| Android | Supported |
| Web | Unsupported stub |
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------------- | ------------------------------------------- |
| `initAppEvents` | Activate Facebook App Events. |
| `logEvent` | Log a Facebook App Event. |
| `logPurchase` | Log a Facebook purchase event. |
| `enableAdvertiserTracking` | Enable advertiser tracking. |
| `disableAdvertiserTracking` | Disable advertiser tracking. |
| `getAdvertiserTrackingStatus` | Get the current advertiser tracking status. |
| `getPluginVersion` | Return the native plugin version marker. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-facebook-analytics](https://github.com/Cap-go/capacitor-facebook-analytics/).
# Getting Started
> Install @capgo/capacitor-facebook-analytics and log Meta/Facebook App Events from Capacitor.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-facebook-analytics
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import {
FacebookAnalytics,
FacebookEventName,
FacebookEventParameterName,
} from '@capgo/capacitor-facebook-analytics';
```
## Native Setup
[Section titled âNative Setupâ](#native-setup)
Configure your Meta app id and client token in the native app. The plugin does not create these values for you.
### iOS
[Section titled âiOSâ](#ios)
Add your Meta values to `Info.plist`:
```xml
FacebookAppIDYOUR_FACEBOOK_APP_IDFacebookClientTokenYOUR_FACEBOOK_CLIENT_TOKENFacebookDisplayNameYOUR_APP_NAME
```
### Android
[Section titled âAndroidâ](#android)
Add your Meta values to `AndroidManifest.xml`:
```xml
```
Add the string resources in `android/app/src/main/res/values/strings.xml`:
```xml
YOUR_FACEBOOK_APP_IDYOUR_FACEBOOK_CLIENT_TOKEN
```
## Enable Advertiser Tracking
[Section titled âEnable Advertiser Trackingâ](#enable-advertiser-tracking)
Call this after your consent flow allows tracking.
```typescript
await FacebookAnalytics.enableAdvertiserTracking();
```
On iOS 17 and above, FBSDK v17+ reads App Tracking Transparency directly. Use your appâs ATT flow before logging tracking-dependent events.
## Log A Standard Event
[Section titled âLog A Standard Eventâ](#log-a-standard-event)
```typescript
await FacebookAnalytics.logEvent({
event: FacebookEventName.CompletedRegistration,
params: {
[FacebookEventParameterName.RegistrationMethod]: 'email',
},
});
```
## Log A Value Event With Currency
[Section titled âLog A Value Event With Currencyâ](#log-a-value-event-with-currency)
```typescript
await FacebookAnalytics.logEvent({
event: FacebookEventName.AddedToCart,
valueToSum: 19.99,
currency: 'USD',
params: {
[FacebookEventParameterName.ContentType]: 'product',
[FacebookEventParameterName.ContentId]: 'sku-123',
},
});
```
## Log A Purchase
[Section titled âLog A Purchaseâ](#log-a-purchase)
```typescript
await FacebookAnalytics.logPurchase({
amount: 9.99,
currency: 'USD',
});
```
## Read Tracking Status
[Section titled âRead Tracking Statusâ](#read-tracking-status)
```typescript
const { status } = await FacebookAnalytics.getAdvertiserTrackingStatus();
console.log('Advertiser tracking enabled:', status);
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-fast-sql
> Fast SQL Plugin for high-performance SQLite database access.
## Overview
[Section titled âOverviewâ](#overview)
Fast SQL Plugin for high-performance SQLite database access.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `connect` - Initialize the database connection and start the HTTP server.
* `disconnect` - Close database connection and stop the HTTP server.
* `getServerInfo` - Get the HTTP server port and token for direct communication.
* `execute` - Execute a SQL query via Capacitor bridge (for simple queries). For better performance with large datasets, use the HTTP protocol directly via SQLConnection class.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `connect` | Initialize the database connection and start the HTTP server. |
| `disconnect` | Close database connection and stop the HTTP server. |
| `getServerInfo` | Get the HTTP server port and token for direct communication. |
| `execute` | Execute a SQL query via Capacitor bridge (for simple queries). For better performance with large datasets, use the HTTP protocol directly via SQLConnection class. |
| `beginTransaction` | Begin a database transaction. |
| `commitTransaction` | Commit the current transaction. |
| `rollbackTransaction` | Rollback the current transaction. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `configureWeb` | Configure web-specific options for the sql.js WASM module. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-fast-sql](https://github.com/Cap-go/capacitor-fast-sql/).
# Getting Started
> Install @capgo/capacitor-fast-sql and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-fast-sql
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `connect`
[Section titled âconnectâ](#connect)
Initialize the database connection and start the HTTP server.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
const conn = await CapgoCapacitorFastSql.connect({ database: 'myapp' });
console.log('Connected on port:', conn.port);
```
### `disconnect`
[Section titled âdisconnectâ](#disconnect)
Close database connection and stop the HTTP server.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
await CapgoCapacitorFastSql.disconnect({ database: 'myapp' });
```
### `getServerInfo`
[Section titled âgetServerInfoâ](#getserverinfo)
Get the HTTP server port and token for direct communication.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
const info = await CapgoCapacitorFastSql.getServerInfo({ database: 'myapp' });
console.log('Server port:', info.port);
```
### `execute`
[Section titled âexecuteâ](#execute)
Execute a SQL query via Capacitor bridge (for simple queries). For better performance with large datasets, use the HTTP protocol directly via SQLConnection class.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
const result = await CapgoCapacitorFastSql.execute({
database: 'myapp',
statement: 'SELECT * FROM users WHERE age > ?',
params: [18]
});
console.log('Rows:', result.rows);
```
### `beginTransaction`
[Section titled âbeginTransactionâ](#begintransaction)
Begin a database transaction.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
await CapgoCapacitorFastSql.beginTransaction({ database: 'myapp' });
// Execute multiple operations
await CapgoCapacitorFastSql.commitTransaction({ database: 'myapp' });
```
### `commitTransaction`
[Section titled âcommitTransactionâ](#committransaction)
Commit the current transaction.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
await CapgoCapacitorFastSql.commitTransaction({ database: 'myapp' });
```
### `rollbackTransaction`
[Section titled ârollbackTransactionâ](#rollbacktransaction)
Rollback the current transaction.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
try {
await CapgoCapacitorFastSql.beginTransaction({ database: 'myapp' });
// Operations...
await CapgoCapacitorFastSql.commitTransaction({ database: 'myapp' });
} catch (error) {
await CapgoCapacitorFastSql.rollbackTransaction({ database: 'myapp' });
}
```
### `configureWeb`
[Section titled âconfigureWebâ](#configureweb)
Configure web-specific options for the sql.js WASM module.
Call this **before** the first `connect()` call to load sql.js from a locally bundled path instead of the default CDN. This method is a no-op on iOS and Android.
```typescript
import { CapgoCapacitorFastSql } from '@capgo/capacitor-fast-sql';
// Configure once at app startup (web only)
await CapgoCapacitorFastSql.configureWeb({
sqlJsUrl: '/assets/sql-wasm.js',
wasmUrl: '/assets/sql-wasm.wasm',
});
const db = await FastSQL.connect({ database: 'myapp' });
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `SQLConnectionOptions`
[Section titled âSQLConnectionOptionsâ](#sqlconnectionoptions)
Database connection options.
```typescript
export interface SQLConnectionOptions {
/**
* Database name (file will be created in app data directory)
*/
database: string;
/**
* Enable encryption (iOS/Android only)
*/
encrypted?: boolean;
/**
* Encryption key (required if encrypted is true)
*/
encryptionKey?: string;
/**
* Read-only mode
*/
readOnly?: boolean;
}
```
### `SQLValue`
[Section titled âSQLValueâ](#sqlvalue)
SQL value types supported by the plugin.
```typescript
export type SQLValue = string | number | boolean | null | Uint8Array;
```
### `SQLResult`
[Section titled âSQLResultâ](#sqlresult)
Result of a SQL query execution.
```typescript
export interface SQLResult {
/**
* Rows returned by the query (for SELECT statements)
*/
rows: SQLRow[];
/**
* Number of rows affected by the query (for INSERT/UPDATE/DELETE)
*/
rowsAffected: number;
/**
* ID of the last inserted row (for INSERT statements with auto-increment)
*/
insertId?: number;
}
```
### `IsolationLevel`
[Section titled âIsolationLevelâ](#isolationlevel)
Transaction isolation levels.
```typescript
export enum IsolationLevel {
ReadUncommitted = 'READ UNCOMMITTED',
ReadCommitted = 'READ COMMITTED',
RepeatableRead = 'REPEATABLE READ',
Serializable = 'SERIALIZABLE',
}
```
### `WebConfig`
[Section titled âWebConfigâ](#webconfig)
Web platform configuration for the sql.js WASM module. Use with `configureWeb()` to load sql.js from a locally bundled path instead of the default CDN.
```typescript
export interface WebConfig {
/**
* URL to the sql.js JavaScript file (`sql-wasm.js`).
* When omitted, the plugin loads from the cdnjs CDN.
* @example '/assets/sql-wasm.js'
*/
sqlJsUrl?: string;
/**
* URL to the sql.js WebAssembly binary (`sql-wasm.wasm`).
* When omitted, the plugin loads from the cdnjs CDN.
* @example '/assets/sql-wasm.wasm'
*/
wasmUrl?: string;
}
```
### `SQLRow`
[Section titled âSQLRowâ](#sqlrow)
SQL row result - values indexed by column name.
```typescript
export interface SQLRow {
[column: string]: SQLValue;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-ffmpeg
> Exposes the FFmpeg API to Capacitor.
## Overview
[Section titled âOverviewâ](#overview)
Exposes the FFmpeg API to Capacitor.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getCapabilities` - Return the machine-readable capability matrix for the current platform.
* `reencodeVideo` - Queue a video re-encode job.
* `convertImage` - Convert a still image into another format.
* `convertAudio` - Convert audio into another container or codec.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------------------------------------------- |
| `getCapabilities` | Return the machine-readable capability matrix for the current platform. |
| `reencodeVideo` | Queue a video re-encode job. |
| `convertImage` | Convert a still image into another format. |
| `convertAudio` | Convert audio into another container or codec. |
| `addListener` | Listen for media job progress. |
| `getPluginVersion` | Get the plugin package version reported by the current platform implementation. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-ffmpeg](https://github.com/Cap-go/capacitor-ffmpeg/).
# Getting Started
> Install @capgo/capacitor-ffmpeg and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-ffmpeg
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getCapabilities`
[Section titled âgetCapabilitiesâ](#getcapabilities)
Return the machine-readable capability matrix for the current platform.
```typescript
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
await CapacitorFFmpeg.getCapabilities();
```
### `reencodeVideo`
[Section titled âreencodeVideoâ](#reencodevideo)
Queue a video re-encode job.
On iOS, the returned promise resolves when the native layer accepts the job. Final success or failure is delivered through the `progress` listener.
Android and web currently reject with `UNIMPLEMENTED`.
```typescript
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
await CapacitorFFmpeg.reencodeVideo({} as ReencodeVideoOptions);
```
### `convertImage`
[Section titled âconvertImageâ](#convertimage)
Convert a still image into another format.
iOS currently supports `jpeg` and `.png`. Android currently supports `.webp`, `jpeg`, and `.png`. Web currently rejects with `UNIMPLEMENTED`.
```typescript
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
await CapacitorFFmpeg.convertImage({} as ConvertImageOptions);
```
### `convertAudio`
[Section titled âconvertAudioâ](#convertaudio)
Convert audio into another container or codec.
iOS currently supports `m4a`. Android and web currently reject with `UNIMPLEMENTED`.
```typescript
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
await CapacitorFFmpeg.convertAudio({} as ConvertAudioOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `FFmpegCapabilitiesResult`
[Section titled âFFmpegCapabilitiesResultâ](#ffmpegcapabilitiesresult)
```typescript
export interface FFmpegCapabilitiesResult {
platform: string;
features: FFmpegCapabilitiesFeatures;
}
```
### `ReencodeVideoOptions`
[Section titled âReencodeVideoOptionsâ](#reencodevideooptions)
```typescript
export interface ReencodeVideoOptions {
inputPath: string;
outputPath: string;
width: number;
height: number;
bitrate?: number;
}
```
### `FFmpegAcceptedJob`
[Section titled âFFmpegAcceptedJobâ](#ffmpegacceptedjob)
```typescript
export interface FFmpegAcceptedJob {
jobId: string;
status: 'queued';
}
```
### `ConvertImageOptions`
[Section titled âConvertImageOptionsâ](#convertimageoptions)
```typescript
export interface ConvertImageOptions {
inputPath: string;
outputPath: string;
format: ImageOutputFormat;
/**
* Compression quality in the inclusive range `0.0..1.0`.
*
* Native platforms reject values outside that range.
*/
quality?: number;
}
```
### `ConvertImageResult`
[Section titled âConvertImageResultâ](#convertimageresult)
```typescript
export interface ConvertImageResult {
outputPath: string;
format: ImageOutputFormat;
}
```
### `ConvertAudioOptions`
[Section titled âConvertAudioOptionsâ](#convertaudiooptions)
```typescript
export interface ConvertAudioOptions {
inputPath: string;
outputPath: string;
format: AudioOutputFormat;
}
```
### `ConvertAudioResult`
[Section titled âConvertAudioResultâ](#convertaudioresult)
```typescript
export interface ConvertAudioResult {
outputPath: string;
format: AudioOutputFormat;
}
```
### `FFmpegProgressEvent`
[Section titled âFFmpegProgressEventâ](#ffmpegprogressevent)
```typescript
export interface FFmpegProgressEvent {
jobId: string;
/**
* Normalized progress as a floating-point value in the inclusive range `0.0..1.0`.
*/
progress: number;
state: FFmpegProgressState;
message?: string;
outputPath?: string;
/**
* Legacy alias kept for compatibility while callers migrate to `jobId`.
*/
fileId?: string;
}
```
### `PluginVersionResult`
[Section titled âPluginVersionResultâ](#pluginversionresult)
```typescript
export interface PluginVersionResult {
version: string;
}
```
### `FFmpegCapabilitiesFeatures`
[Section titled âFFmpegCapabilitiesFeaturesâ](#ffmpegcapabilitiesfeatures)
```typescript
export interface FFmpegCapabilitiesFeatures {
getPluginVersion: FFmpegCapability;
getCapabilities: FFmpegCapability;
reencodeVideo: FFmpegCapability;
convertImage: FFmpegCapability;
convertAudio?: FFmpegCapability;
progressEvents: FFmpegCapability;
probeMedia: FFmpegCapability;
generateThumbnail: FFmpegCapability;
extractAudio: FFmpegCapability;
remux: FFmpegCapability;
trim: FFmpegCapability;
}
```
### `ImageOutputFormat`
[Section titled âImageOutputFormatâ](#imageoutputformat)
```typescript
export type ImageOutputFormat = '.webp' | 'jpeg' | '.png';
```
### `AudioOutputFormat`
[Section titled âAudioOutputFormatâ](#audiooutputformat)
```typescript
export type AudioOutputFormat = 'm4a';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-file
> Capacitor File Plugin Implements file system operations similar to the Cordova File plugin.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor File Plugin Implements file system operations similar to the Cordova File plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `requestFileSystem` - Request a file system.
* `resolveLocalFileSystemURL` - Resolve a file URL to an entry.
* `getFile` - Get a file entry.
* `getDirectory` - Get a directory entry.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requestFileSystem` | Request a file system. |
| `resolveLocalFileSystemURL` | Resolve a file URL to an entry. |
| `getFile` | Get a file entry. |
| `getDirectory` | Get a directory entry. |
| `readFile` | Read a file as text or base64. |
| `readAsDataURL` | Read a file as a data URL (base64 with MIME type prefix). |
| `writeFile` | Write data to a file. |
| `appendFile` | Append data to a file. |
| `deleteFile` | Delete a file. |
| `mkdir` | Create a directory. |
| `rmdir` | Delete a directory. |
| `readdir` | Read directory contents. |
| `stat` | Get metadata about a file or directory. |
| `getMetadata` | Get metadata about a file or directory. Alias for stat(). |
| `rename` | Rename or move a file or directory. |
| `move` | Move a file or directory. Alias for rename(). |
| `copy` | Copy a file or directory. |
| `exists` | Check if a file or directory exists. |
| `getUri` | Get the URI for a file. |
| `truncate` | Truncate a file to a specified size. |
| `getDirectories` | Get all known file system directories. |
| `getFreeDiskSpace` | Get the free disk space in bytes. |
| `addListener` | Listen for read progress events. |
| `addListener` | Listen for write progress events. |
| `removeAllListeners` | Remove all event listeners. |
| `getPluginVersion` | Get the plugin version. |
| `checkPermissions` | Check the current permission status for file operations. On Android, this checks for external storage permissions. On iOS and web, this always returns âgrantedâ as no special permissions are needed. |
| `requestPermissions` | Request permissions for file operations. On Android, this requests external storage permissions needed for accessing files outside the appâs private directories. On iOS and web, this always returns âgrantedâ as no special permissions are needed. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-file](https://github.com/Cap-go/capacitor-file/).
# @capgo/capacitor-file-compressor
> Capacitor File Compressor Plugin interface for image compression.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor File Compressor Plugin interface for image compression.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `compressImage` - Compresses an image file with specified dimensions and quality settings.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------------------------------------ |
| `compressImage` | Compresses an image file with specified dimensions and quality settings. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-file-compressor](https://github.com/Cap-go/capacitor-file-compressor/).
# Getting Started
> Install @capgo/capacitor-file-compressor and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-file-compressor
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FileCompressor } from '@capgo/capacitor-file-compressor';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `compressImage`
[Section titled âcompressImageâ](#compressimage)
Compresses an image file with specified dimensions and quality settings.
This method compresses images to reduce file size while maintaining acceptable quality. It supports resizing and format conversion (JPEG/WebP depending on platform).
**Important Notes:**
* EXIF metadata is removed during compression on all platforms
* Aspect ratio is automatically maintained if only one dimension is provided
* Compressed files are saved to temporary directories on native platforms
```typescript
import { FileCompressor } from '@capgo/capacitor-file-compressor';
// Web - Compress from file input
const fileInput = document.getElementById('file') as HTMLInputElement;
const file = fileInput.files[0];
const result = await FileCompressor.compressImage({
blob: file,
quality: 0.8,
width: 1200,
mimeType: 'image/jpeg'
});
const url = URL.createObjectURL(result.blob);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CompressImageOptions`
[Section titled âCompressImageOptionsâ](#compressimageoptions)
Options for compressing an image.
````typescript
export interface CompressImageOptions {
/**
* The file path of the image to compress.
*
* **Platform:** Android, iOS only (not supported on Web)
*
* Accepts various path formats:
* - iOS: `file://` URLs or absolute paths
* - Android: `content://` URIs, `file://` URLs, or absolute paths
*
* @since 7.0.0
* @example "file:///var/mobile/Containers/Data/Application/image.jpg" // iOS
* @example "content://com.android.providers.downloads.documents/document/msf%3A1000000485" // Android
* @example "/storage/emulated/0/Download/photo.png" // Android absolute path
*/
path?: string;
/**
* The file blob of the image to compress.
*
* **Platform:** Web only (not supported on iOS/Android)
*
* Use this when compressing images from file inputs, fetch responses,
* or any other Blob source in web applications.
*
* @since 7.0.0
* @example
* ```typescript
* // From file input
* const fileInput = document.getElementById('file') as HTMLInputElement;
* const blob = fileInput.files[0];
* ```
* @example
* ```typescript
* // From fetch
* const response = await fetch('https://example.com/image.jpg');
* const blob = await response.blob();
* ```
*/
blob?: Blob;
/**
* The quality of the compressed image.
*
* **Range:** 0.0 to 1.0
* - `0.0` = Maximum compression (lowest quality, smallest file)
* - `1.0` = Minimum compression (highest quality, largest file)
* - `0.6` = Default balanced compression
*
* **Platform:** All platforms
*
* Higher quality values result in larger files but better visual quality.
* The actual compression ratio depends on the image content and format.
*
* @since 7.0.0
* @default 0.6
* @example 0.8 // High quality
* @example 0.5 // Medium quality, smaller file
* @example 0.3 // Low quality, very small file
*/
quality?: number;
/**
* The width of the compressed image in pixels.
*
* **Platform:** All platforms
*
* If only width is specified, height is calculated automatically
* to maintain the original aspect ratio.
*
* If both width and height are specified, the image is resized
* to exact dimensions (may distort if ratio differs).
*
* @since 7.0.0
* @example 1920 // Full HD width
* @example 1200 // Common web image width
* @example 800 // Mobile-optimized width
*/
width?: number;
/**
* The height of the compressed image in pixels.
*
* **Platform:** All platforms
*
* If only height is specified, width is calculated automatically
* to maintain the original aspect ratio.
*
* If both width and height are specified, the image is resized
* to exact dimensions (may distort if ratio differs).
*
* @since 7.0.0
* @example 1080 // Full HD height
* @example 800 // Common web image height
* @example 600 // Mobile-optimized height
*/
height?: number;
/**
* The MIME type of the compressed output image.
*
* **Platform Support:**
* - **iOS:** `image/jpeg` only
* - **Android:** `image/jpeg`, `image/.webp`
* - **Web:** `image/jpeg`, `image/.webp`
*
* **Format Characteristics:**
* - **JPEG:** Universal support, good for photos, no transparency
* - **WebP:** Better compression, supports transparency, not on iOS
*
* @since 7.0.0
* @default "image/jpeg"
* @example "image/jpeg" // JPEG format (all platforms)
* @example "image/.webp" // WebP format (Android/Web only)
*/
mimeType?: string;
}
````
### `CompressImageResult`
[Section titled âCompressImageResultâ](#compressimageresult)
The result of compressing an image.
````typescript
export interface CompressImageResult {
/**
* The file path of the compressed image.
*
* **Platform:** Android, iOS only (undefined on Web)
*
* Points to a temporary file containing the compressed image.
* On iOS, typically in `NSTemporaryDirectory()`.
* On Android, typically in app cache directory.
*
* **Important:** These files may be cleaned up by the OS.
* Copy to permanent storage if needed for long-term use.
*
* @since 7.0.0
* @example "/var/mobile/Containers/Data/tmp/compressed_abc123.jpg" // iOS
* @example "/data/user/0/com.app/cache/compressed_xyz789.jpg" // Android
*/
path?: string;
/**
* The blob of the compressed image.
*
* **Platform:** Web only (undefined on iOS/Android)
*
* A Blob object containing the compressed image data.
* Can be used to:
* - Create object URLs for preview: `URL.createObjectURL(blob)`
* - Upload to server via FormData
* - Save to IndexedDB or other storage
* - Convert to base64 with FileReader
*
* @since 7.0.0
* @example
* ```typescript
* // Create preview URL
* const url = URL.createObjectURL(result.blob);
* imageElement.src = url;
* ```
* @example
* ```typescript
* // Upload to server
* const formData = new FormData();
* formData.append('image', result.blob, 'compressed.jpg');
* await fetch('/upload', { method: 'POST', body: formData });
* ```
*/
blob?: Blob;
}
````
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-file-picker
> Capacitor File Picker Plugin interface for selecting files, images, videos, and directories.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor File Picker Plugin interface for selecting files, images, videos, and directories.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `pickFiles` - Pick one or more files from the device.
* `pickImages` - Pick one or more images from the gallery. Android/iOS only.
* `pickVideos` - Pick one or more videos from the gallery. Android/iOS only.
* `pickMedia` - Pick one or more images or videos from the gallery. Android/iOS only.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | --------------------------------------------------------------------- |
| `pickFiles` | Pick one or more files from the device. |
| `pickImages` | Pick one or more images from the gallery. Android/iOS only. |
| `pickVideos` | Pick one or more videos from the gallery. Android/iOS only. |
| `pickMedia` | Pick one or more images or videos from the gallery. Android/iOS only. |
| `pickDirectory` | Pick a directory from the device. Android/iOS only. |
| `convertHeicToJpeg` | Convert a HEIC image to JPEG format. iOS only. |
| `copyFile` | Copy a file to a new location. |
| `checkPermissions` | Check permissions for reading files. Android only. |
| `requestPermissions` | Request permissions for reading files. Android only. |
| `addListener` | Add a listener for the picker dismissed event. iOS only. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-file-picker](https://github.com/Cap-go/capacitor-file-picker/).
# Getting Started
> Install @capgo/capacitor-file-picker and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-file-picker
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `pickFiles`
[Section titled âpickFilesâ](#pickfiles)
Pick one or more files from the device.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.pickFiles({
types: ['application/pdf', 'image/*'],
limit: 5,
readData: false
});
console.log('Picked files:', result.files);
```
### `pickImages`
[Section titled âpickImagesâ](#pickimages)
Pick one or more images from the gallery. Android/iOS only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.pickImages({
limit: 10,
readData: false
});
console.log('Picked images:', result.files);
```
### `pickVideos`
[Section titled âpickVideosâ](#pickvideos)
Pick one or more videos from the gallery. Android/iOS only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.pickVideos({
limit: 3,
skipTranscoding: true
});
console.log('Picked videos:', result.files);
```
### `pickMedia`
[Section titled âpickMediaâ](#pickmedia)
Pick one or more images or videos from the gallery. Android/iOS only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.pickMedia({
limit: 5,
readData: true
});
console.log('Picked media:', result.files);
```
### `pickDirectory`
[Section titled âpickDirectoryâ](#pickdirectory)
Pick a directory from the device. Android/iOS only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.pickDirectory();
console.log('Selected directory:', result.path);
```
### `convertHeicToJpeg`
[Section titled âconvertHeicToJpegâ](#convertheictojpeg)
Convert a HEIC image to JPEG format. iOS only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const result = await CapgoFilePicker.convertHeicToJpeg({
path: '/path/to/image.heic',
quality: 0.9
});
console.log('Converted file:', result.path);
```
### `copyFile`
[Section titled âcopyFileâ](#copyfile)
Copy a file to a new location.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
await CapgoFilePicker.copyFile({
from: '/source/file.pdf',
to: '/destination/file.pdf',
overwrite: true
});
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check permissions for reading files. Android only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const status = await CapgoFilePicker.checkPermissions();
console.log('Read permission:', status.readExternalStorage);
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permissions for reading files. Android only.
```typescript
import { CapgoFilePicker } from '@capgo/capacitor-file-picker';
const status = await CapgoFilePicker.requestPermissions();
if (status.readExternalStorage === 'granted') {
console.log('Permission granted');
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `PickFilesOptions`
[Section titled âPickFilesOptionsâ](#pickfilesoptions)
Options for picking files.
```typescript
export interface PickFilesOptions {
/**
* List of accepted MIME types or file extensions.
* On iOS, only MIME types are supported.
* Examples: ['image/*'], ['application/pdf'], ['.pdf', '.doc']
*/
types?: string[];
/**
* Maximum number of files to pick.
* Set to 0 for unlimited (platform default).
* @default 0
*/
limit?: number;
/**
* Whether to read the file data as base64.
* Note: Reading large files may cause memory issues.
* @default false
*/
readData?: boolean;
}
```
### `PickFilesResult`
[Section titled âPickFilesResultâ](#pickfilesresult)
Result of picking files.
```typescript
export interface PickFilesResult {
/** Array of picked files */
files: PickedFile[];
}
```
### `PickMediaOptions`
[Section titled âPickMediaOptionsâ](#pickmediaoptions)
Options for picking media (images/videos).
```typescript
export interface PickMediaOptions {
/**
* Maximum number of files to pick.
* Set to 0 for unlimited (platform default).
* @default 0
*/
limit?: number;
/**
* Whether to read the file data as base64.
* Note: Reading large files may cause memory issues.
* @default false
*/
readData?: boolean;
/**
* iOS only: Skip transcoding of videos.
* @default false
*/
skipTranscoding?: boolean;
/**
* iOS 15+ only: Show ordered selection badges.
* @default false
*/
ordered?: boolean;
}
```
### `PickDirectoryResult`
[Section titled âPickDirectoryResultâ](#pickdirectoryresult)
Result of picking a directory.
```typescript
export interface PickDirectoryResult {
/** The path to the selected directory */
path: string;
}
```
### `ConvertHeicToJpegOptions`
[Section titled âConvertHeicToJpegOptionsâ](#convertheictojpegoptions)
Options for converting HEIC to JPEG.
```typescript
export interface ConvertHeicToJpegOptions {
/** The path to the HEIC file to convert */
path: string;
/**
* The compression quality for JPEG (0.0 - 1.0).
* @default 0.9
*/
quality?: number;
}
```
### `ConvertHeicToJpegResult`
[Section titled âConvertHeicToJpegResultâ](#convertheictojpegresult)
Result of HEIC to JPEG conversion.
```typescript
export interface ConvertHeicToJpegResult {
/** The path to the converted JPEG file */
path: string;
}
```
### `CopyFileOptions`
[Section titled âCopyFileOptionsâ](#copyfileoptions)
Options for copying a file.
```typescript
export interface CopyFileOptions {
/** Source file path */
from: string;
/** Destination file path */
to: string;
/**
* Whether to overwrite if destination exists.
* @default false
*/
overwrite?: boolean;
}
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Permission status for file access.
```typescript
export interface PermissionStatus {
/** Whether permission to read media files is granted */
readExternalStorage: PermissionState;
/** Whether permission to access media location is granted */
accessMediaLocation?: PermissionState;
}
```
### `PickerDismissedListener`
[Section titled âPickerDismissedListenerâ](#pickerdismissedlistener)
Listener callback for picker dismissed event.
```typescript
export type PickerDismissedListener = (event: null) => void;
```
### `PickedFile`
[Section titled âPickedFileâ](#pickedfile)
Represents a picked file.
```typescript
export interface PickedFile {
/** The name of the file */
name: string;
/** The path to the file */
path?: string;
/** The MIME type of the file */
mimeType: string;
/** The size of the file in bytes */
size: number;
/**
* The base64 encoded data of the file.
* Only present if readData was true.
*/
data?: string;
/**
* The Blob instance of the file.
* Web only.
*/
blob?: Blob;
/** Width in pixels (images/videos only) */
width?: number;
/** Height in pixels (images/videos only) */
height?: number;
/** Duration in seconds (videos only) */
duration?: number;
/** Last modified timestamp in milliseconds */
modifiedAt?: number;
}
```
### `PermissionState`
[Section titled âPermissionStateâ](#permissionstate)
Permission state values.
```typescript
export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-file-sharer
> Share and save files with native sheets, Android MediaStore, and browser downloads.
## Overview
[Section titled âOverviewâ](#overview)
`@capgo/capacitor-file-sharer` shares or saves files from base64 data, data URLs, local file paths, `file://` URLs, `content://` URIs, and Capacitor `_capacitor_file_` URLs.
Use it when an app needs to export reports, backups, images, videos, PDFs, ZIP archives, or other generated files without forcing every platform through the same storage path.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `share` - Open the native share sheet on Android and iOS, or download the file on Web.
* `save` - Save into Android public collections, open the iOS save/share sheet, or download on Web.
* `getPluginVersion` - Return the native/web plugin implementation version.
## Platform Behavior
[Section titled âPlatform Behaviorâ](#platform-behavior)
| Platform | Share behavior | Save behavior |
| -------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Android | Uses a `FileProvider`, `ClipData`, and URI grants so chooser previews and thumbnails can read the file. | Uses MediaStore on Android 10+ and public directories on Android 9 and below. |
| iOS | Uses `UIActivityViewController` with base64 or direct path-backed files. | Opens the native share sheet so the user can choose Save to Files or another destination. |
| Web | Downloads the file. | Downloads the file. |
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------------------- |
| `share` | Share a file using the native share sheet on Android and iOS, or download on Web. |
| `save` | Save a file locally on Android/Web, or open the iOS save/share sheet. |
| `getPluginVersion` | Returns the platform implementation version marker. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-file-sharer](https://github.com/Cap-go/capacitor-file-sharer/).
# Getting Started
> Install @capgo/capacitor-file-sharer and share or save files from base64 data and local paths.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-file-sharer
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FileSharer } from '@capgo/capacitor-file-sharer';
```
## Share A Base64 File
[Section titled âShare A Base64 Fileâ](#share-a-base64-file)
```typescript
import { FileSharer } from '@capgo/capacitor-file-sharer';
await FileSharer.share({
filename: 'report.pdf',
contentType: 'application/pdf',
base64Data: reportBase64,
title: 'Quarterly report',
text: 'Attached report',
});
```
`base64Data` can be a raw base64 string or a data URL such as `data:application/pdf;base64,...`.
## Share A Local File
[Section titled âShare A Local Fileâ](#share-a-local-file)
```typescript
await FileSharer.share({
filename: 'export.zip',
contentType: 'application/zip',
path: fileUri,
});
```
The native implementations accept local paths, `file://` URLs, Android `content://` URIs, and Capacitor `_capacitor_file_` URLs.
## Save A File
[Section titled âSave A Fileâ](#save-a-file)
```typescript
const result = await FileSharer.save({
filename: 'backup.zip',
contentType: 'application/zip',
base64Data: zipBase64,
android: {
saveDirectory: 'downloads',
relativePath: 'Download/My App',
},
});
console.log(result.uri);
```
Android save directories are `downloads`, `pictures`, `movies`, `music`, and `documents`. On Android 10 and newer, the plugin writes through MediaStore. On Android 9 and below, public saves use the manifest `WRITE_EXTERNAL_STORAGE` permission with `maxSdkVersion=28`.
## Share Text With A File
[Section titled âShare Text With A Fileâ](#share-text-with-a-file)
```typescript
await FileSharer.share({
filename: 'photo.jpg',
contentType: 'image/jpeg',
path: photoUri,
title: 'Site photo',
subject: 'Photo export',
text: 'Captured during inspection.',
});
```
`text` is passed as `EXTRA_TEXT` on Android and as a second activity item on iOS.
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ShareFileOptions`
[Section titled âShareFileOptionsâ](#sharefileoptions)
```typescript
export interface ShareFileOptions {
filename: string;
base64Data?: string;
path?: string;
contentType?: string;
text?: string;
title?: string;
subject?: string;
android?: AndroidFileSharerOptions;
}
```
### `AndroidFileSharerOptions`
[Section titled âAndroidFileSharerOptionsâ](#androidfileshareroptions)
```typescript
export interface AndroidFileSharerOptions {
chooserTitle?: string;
saveDirectory?: 'downloads' | 'pictures' | 'movies' | 'music' | 'documents';
relativePath?: string;
}
```
### `SaveFileResult`
[Section titled âSaveFileResultâ](#savefileresult)
```typescript
export interface SaveFileResult {
uri?: string;
}
```
## Error Codes
[Section titled âError Codesâ](#error-codes)
* `ERR_PARAM_NO_FILENAME` - `filename` is missing or blank.
* `ERR_PARAM_NO_DATA` - neither `base64Data` nor `path` was provided.
* `ERR_PARAM_DATA_INVALID` - base64 input could not be decoded.
* `ERR_LOCAL_FILE_NOT_FOUND` - the provided local path or content URI could not be opened.
* `ERR_FILE_CACHING_FAILED` - the native temporary file could not be written.
* `ERR_FILE_SAVE_FAILED` - Android could not save the file to public storage.
* `ERR_ACTIVITY_NOT_FOUND` - Android could not open a share target.
* `USER_CANCELLED` - the iOS share sheet was dismissed without completing.
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page tracks the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# Getting Started
> Install @capgo/capacitor-file and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-file
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `requestFileSystem`
[Section titled ârequestFileSystemâ](#requestfilesystem)
Request a file system.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.requestFileSystem({} as RequestFileSystemOptions);
```
### `resolveLocalFileSystemURL`
[Section titled âresolveLocalFileSystemURLâ](#resolvelocalfilesystemurl)
Resolve a file URL to an entry.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.resolveLocalFileSystemURL({} as ResolveURLOptions);
```
### `getFile`
[Section titled âgetFileâ](#getfile)
Get a file entry.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getFile({} as GetFileOptions);
```
### `getDirectory`
[Section titled âgetDirectoryâ](#getdirectory)
Get a directory entry.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getDirectory({} as GetDirectoryOptions);
```
### `readFile`
[Section titled âreadFileâ](#readfile)
Read a file as text or base64.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.readFile({} as ReadFileOptions);
```
### `readAsDataURL`
[Section titled âreadAsDataURLâ](#readasdataurl)
Read a file as a data URL (base64 with MIME type prefix).
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.readAsDataURL({} as ReadFileOptions);
```
### `writeFile`
[Section titled âwriteFileâ](#writefile)
Write data to a file.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.writeFile({} as WriteFileOptions);
```
### `appendFile`
[Section titled âappendFileâ](#appendfile)
Append data to a file.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.appendFile({} as WriteFileOptions);
```
### `deleteFile`
[Section titled âdeleteFileâ](#deletefile)
Delete a file.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.deleteFile({} as DeleteFileOptions);
```
### `mkdir`
[Section titled âmkdirâ](#mkdir)
Create a directory.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.mkdir({} as MkdirOptions);
```
### `rmdir`
[Section titled ârmdirâ](#rmdir)
Delete a directory.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.rmdir({} as DeleteDirectoryOptions);
```
### `readdir`
[Section titled âreaddirâ](#readdir)
Read directory contents.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.readdir({} as ReaddirOptions);
```
### `stat`
[Section titled âstatâ](#stat)
Get metadata about a file or directory.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.stat({} as StatOptions);
```
### `getMetadata`
[Section titled âgetMetadataâ](#getmetadata)
Get metadata about a file or directory. Alias for stat().
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getMetadata({} as StatOptions);
```
### `rename`
[Section titled ârenameâ](#rename)
Rename or move a file or directory.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.rename({} as RenameOptions);
```
### `move`
[Section titled âmoveâ](#move)
Move a file or directory. Alias for rename().
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.move({} as RenameOptions);
```
### `copy`
[Section titled âcopyâ](#copy)
Copy a file or directory.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.copy({} as CopyOptions);
```
### `exists`
[Section titled âexistsâ](#exists)
Check if a file or directory exists.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.exists({} as ExistsOptions);
```
### `getUri`
[Section titled âgetUriâ](#geturi)
Get the URI for a file.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getUri({} as GetUriOptions);
```
### `truncate`
[Section titled âtruncateâ](#truncate)
Truncate a file to a specified size.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.truncate({} as TruncateOptions);
```
### `getDirectories`
[Section titled âgetDirectoriesâ](#getdirectories)
Get all known file system directories.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getDirectories();
```
### `getFreeDiskSpace`
[Section titled âgetFreeDiskSpaceâ](#getfreediskspace)
Get the free disk space in bytes.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.getFreeDiskSpace();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission status for file operations. On Android, this checks for external storage permissions. On iOS and web, this always returns âgrantedâ as no special permissions are needed.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permissions for file operations. On Android, this requests external storage permissions needed for accessing files outside the appâs private directories. On iOS and web, this always returns âgrantedâ as no special permissions are needed.
```typescript
import { CapacitorFile } from '@capgo/capacitor-file';
await CapacitorFile.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `RequestFileSystemOptions`
[Section titled âRequestFileSystemOptionsâ](#requestfilesystemoptions)
Options for requesting a file system.
```typescript
export interface RequestFileSystemOptions {
/** The type of file system to request */
type: FileSystemType;
/** Requested size in bytes (may not be enforced on all platforms) */
size?: number;
}
```
### `FileSystem`
[Section titled âFileSystemâ](#filesystem)
Represents a file system.
```typescript
export interface FileSystem {
/** The name of the file system */
name: string;
/** The root directory of the file system */
root: DirectoryEntry;
}
```
### `ResolveURLOptions`
[Section titled âResolveURLOptionsâ](#resolveurloptions)
Options for resolving a URL to an entry.
```typescript
export interface ResolveURLOptions {
/** The URL to resolve (file:// or cdvfile://) */
url: string;
}
```
### `Entry`
[Section titled âEntryâ](#entry)
Represents a file or directory entry.
```typescript
export interface Entry {
/** True if this is a file */
isFile: boolean;
/** True if this is a directory */
isDirectory: boolean;
/** The name of the file or directory */
name: string;
/** The full path relative to the filesystem root */
fullPath: string;
/** The native file:// URI */
nativeURL: string;
}
```
### `GetFileOptions`
[Section titled âGetFileOptionsâ](#getfileoptions)
Options for getting a file.
```typescript
export interface GetFileOptions {
/** Path to the file */
path: string;
/** Base directory */
directory?: Directory;
/** Options for creating the file */
options?: GetOptions;
}
```
### `FileEntry`
[Section titled âFileEntryâ](#fileentry)
Represents a file entry.
```typescript
export interface FileEntry extends Entry {
isFile: true;
isDirectory: false;
}
```
### `GetDirectoryOptions`
[Section titled âGetDirectoryOptionsâ](#getdirectoryoptions)
Options for getting a directory.
```typescript
export interface GetDirectoryOptions {
/** Path to the directory */
path: string;
/** Base directory */
directory?: Directory;
/** Options for creating the directory */
options?: GetOptions;
}
```
### `DirectoryEntry`
[Section titled âDirectoryEntryâ](#directoryentry)
Represents a directory entry.
```typescript
export interface DirectoryEntry extends Entry {
isFile: false;
isDirectory: true;
}
```
### `ReadFileOptions`
[Section titled âReadFileOptionsâ](#readfileoptions)
Options for reading a file.
```typescript
export interface ReadFileOptions {
/** Path to the file */
path: string;
/** Base directory */
directory?: Directory;
/** Encoding for text files (omit for binary/base64) */
encoding?: Encoding;
/** Byte offset to start reading from (default: 0) */
offset?: number;
/** Number of bytes to read (default: read to end of file) */
length?: number;
}
```
### `ReadFileResult`
[Section titled âReadFileResultâ](#readfileresult)
Result of reading a file.
```typescript
export interface ReadFileResult {
/** File contents as string (text) or base64 (binary) */
data: string;
}
```
### `WriteFileOptions`
[Section titled âWriteFileOptionsâ](#writefileoptions)
Options for writing a file.
```typescript
export interface WriteFileOptions {
/** Path to the file */
path: string;
/** Base directory */
directory?: Directory;
/** Data to write (string for text, base64 for binary) */
data: string;
/** Encoding for text files */
encoding?: Encoding;
/** If true, append to existing file instead of overwriting */
append?: boolean;
/** Create intermediate directories if they don't exist */
recursive?: boolean;
/** Byte position to start writing at (for random access writes). If not specified, writes from beginning or appends based on 'append' flag */
position?: number;
}
```
### `WriteFileResult`
[Section titled âWriteFileResultâ](#writefileresult)
Result of writing a file.
```typescript
export interface WriteFileResult {
/** The URI of the written file */
uri: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-analytics
> Capacitor plugin for Firebase Analytics.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Analytics.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getAppInstanceId` - Retrieves the app instance id.
* `getSessionId` - Retrieves the current session id (`ga_session_id`).
* `setConsent` - Sets the userâs consent mode.
* `setUserId` - Sets the user ID property.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `getAppInstanceId` | Retrieves the app instance id. |
| `getSessionId` | Retrieves the current session id (`ga_session_id`). |
| `setConsent` | Sets the userâs consent mode. |
| `setUserId` | Sets the user ID property. |
| `setUserProperty` | Sets a custom user property to a given value. |
| `setCurrentScreen` | Sets the current screen name. |
| `logEvent` | Logs an app event. |
| `setSessionTimeoutDuration` | Sets the duration of inactivity that terminates the current session. |
| `setEnabled` | Enables/disables automatic data collection. The value does not apply until the next run of the app. |
| `isEnabled` | Returns whether or not automatic data collection is enabled. |
| `resetAnalyticsData` | Clears all analytics data for this app from the device. Resets the app instance id. |
| `initiateOnDeviceConversionMeasurementWithEmailAddress` | Initiates on-device conversion measurement with an email address. |
| `initiateOnDeviceConversionMeasurementWithPhoneNumber` | Initiates on-device conversion measurement with a phone number. |
| `initiateOnDeviceConversionMeasurementWithHashedEmailAddress` | Initiates on-device conversion measurement with a hashed email address. |
| `initiateOnDeviceConversionMeasurementWithHashedPhoneNumber` | Initiates on-device conversion measurement with a hashed phone number. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-analytics and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-analytics
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getAppInstanceId`
[Section titled âgetAppInstanceIdâ](#getappinstanceid)
Retrieves the app instance id.
Only available for Android and iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.getAppInstanceId();
```
### `getSessionId`
[Section titled âgetSessionIdâ](#getsessionid)
Retrieves the current session id (`ga_session_id`).
Only available for Android and iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.getSessionId();
```
### `setConsent`
[Section titled âsetConsentâ](#setconsent)
Sets the userâs consent mode.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setConsent({} as SetConsentOptions);
```
### `setUserId`
[Section titled âsetUserIdâ](#setuserid)
Sets the user ID property.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setUserId({} as SetUserIdOptions);
```
### `setUserProperty`
[Section titled âsetUserPropertyâ](#setuserproperty)
Sets a custom user property to a given value.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setUserProperty({} as SetUserPropertyOptions);
```
### `setCurrentScreen`
[Section titled âsetCurrentScreenâ](#setcurrentscreen)
Sets the current screen name.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setCurrentScreen({} as SetCurrentScreenOptions);
```
### `logEvent`
[Section titled âlogEventâ](#logevent)
Logs an app event.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.logEvent({} as LogEventOptions);
```
### `setSessionTimeoutDuration`
[Section titled âsetSessionTimeoutDurationâ](#setsessiontimeoutduration)
Sets the duration of inactivity that terminates the current session.
Only available for Android and iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setSessionTimeoutDuration({} as SetSessionTimeoutDurationOptions);
```
### `setEnabled`
[Section titled âsetEnabledâ](#setenabled)
Enables/disables automatic data collection. The value does not apply until the next run of the app.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.setEnabled({} as SetEnabledOptions);
```
### `isEnabled`
[Section titled âisEnabledâ](#isenabled)
Returns whether or not automatic data collection is enabled.
Only available for Web.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.isEnabled();
```
### `resetAnalyticsData`
[Section titled âresetAnalyticsDataâ](#resetanalyticsdata)
Clears all analytics data for this app from the device. Resets the app instance id.
Only available for Android and iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.resetAnalyticsData();
```
### `initiateOnDeviceConversionMeasurementWithEmailAddress`
[Section titled âinitiateOnDeviceConversionMeasurementWithEmailAddressâ](#initiateondeviceconversionmeasurementwithemailaddress)
Initiates on-device conversion measurement with an email address.
Only available for iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.initiateOnDeviceConversionMeasurementWithEmailAddress({} as InitiateOnDeviceConversionMeasurementWithEmailAddressOptions);
```
### `initiateOnDeviceConversionMeasurementWithPhoneNumber`
[Section titled âinitiateOnDeviceConversionMeasurementWithPhoneNumberâ](#initiateondeviceconversionmeasurementwithphonenumber)
Initiates on-device conversion measurement with a phone number.
Only available for iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.initiateOnDeviceConversionMeasurementWithPhoneNumber({} as InitiateOnDeviceConversionMeasurementWithPhoneNumberOptions);
```
### `initiateOnDeviceConversionMeasurementWithHashedEmailAddress`
[Section titled âinitiateOnDeviceConversionMeasurementWithHashedEmailAddressâ](#initiateondeviceconversionmeasurementwithhashedemailaddress)
Initiates on-device conversion measurement with a hashed email address.
Only available for iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.initiateOnDeviceConversionMeasurementWithHashedEmailAddress({} as InitiateOnDeviceConversionMeasurementWithHashedEmailAddressOptions);
```
### `initiateOnDeviceConversionMeasurementWithHashedPhoneNumber`
[Section titled âinitiateOnDeviceConversionMeasurementWithHashedPhoneNumberâ](#initiateondeviceconversionmeasurementwithhashedphonenumber)
Initiates on-device conversion measurement with a hashed phone number.
Only available for iOS.
```typescript
import { FirebaseAnalytics } from '@capgo/capacitor-firebase-analytics';
await FirebaseAnalytics.initiateOnDeviceConversionMeasurementWithHashedPhoneNumber({} as InitiateOnDeviceConversionMeasurementWithHashedPhoneNumberOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetAppInstanceIdResult`
[Section titled âGetAppInstanceIdResultâ](#getappinstanceidresult)
```typescript
export interface GetAppInstanceIdResult {
/**
* The app instance id.
*
* Not defined if `FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE` has been set to `FirebaseAnalytics.ConsentStatus.DENIED`.
*
* @since 1.4.0
*/
appInstanceId?: string;
}
```
### `GetSessionIdResult`
[Section titled âGetSessionIdResultâ](#getsessionidresult)
```typescript
export interface GetSessionIdResult {
/**
* The current session id.
*
* Matches Firebase Analytics `ga_session_id`.
*
* Not defined if `FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE` has been set to `FirebaseAnalytics.ConsentStatus.DENIED`.
*
* @since 8.0.1
*/
sessionId?: number;
}
```
### `SetConsentOptions`
[Section titled âSetConsentOptionsâ](#setconsentoptions)
```typescript
export interface SetConsentOptions {
/**
* The consent type.
*
* @since 6.0.0
*/
type: ConsentType;
/**
* The consent status.
*
* @since 6.0.0
*/
status: ConsentStatus;
}
```
### `SetUserIdOptions`
[Section titled âSetUserIdOptionsâ](#setuseridoptions)
```typescript
export interface SetUserIdOptions {
/**
* @since 0.1.0
*/
userId: string | null;
}
```
### `SetUserPropertyOptions`
[Section titled âSetUserPropertyOptionsâ](#setuserpropertyoptions)
```typescript
export interface SetUserPropertyOptions {
/**
* @since 0.1.0
*/
key: string;
/**
* @since 0.1.0
*/
value: string | null;
}
```
### `SetCurrentScreenOptions`
[Section titled âSetCurrentScreenOptionsâ](#setcurrentscreenoptions)
```typescript
export interface SetCurrentScreenOptions {
/**
* @since 0.1.0
*/
screenName: string | null;
/**
* Only available for Android and iOS.
*
* @default null
* @since 0.1.0
*/
screenClassOverride?: string | null;
}
```
### `LogEventOptions`
[Section titled âLogEventOptionsâ](#logeventoptions)
```typescript
export interface LogEventOptions {
/**
* The event name.
*
* @since 0.1.0
*/
name: string;
/**
* The optional event params.
*
* @since 0.1.0
*/
params?: { [key: string]: any };
}
```
### `SetSessionTimeoutDurationOptions`
[Section titled âSetSessionTimeoutDurationOptionsâ](#setsessiontimeoutdurationoptions)
```typescript
export interface SetSessionTimeoutDurationOptions {
/**
* Duration in seconds.
*
* @default 1800
* @since 0.1.0
*/
duration: number;
}
```
### `SetEnabledOptions`
[Section titled âSetEnabledOptionsâ](#setenabledoptions)
```typescript
export interface SetEnabledOptions {
/**
* @since 0.1.0
*/
enabled: boolean;
}
```
### `IsEnabledResult`
[Section titled âIsEnabledResultâ](#isenabledresult)
```typescript
export interface IsEnabledResult {
/**
* @since 0.1.0
*/
enabled: boolean;
}
```
### `InitiateOnDeviceConversionMeasurementWithEmailAddressOptions`
[Section titled âInitiateOnDeviceConversionMeasurementWithEmailAddressOptionsâ](#initiateondeviceconversionmeasurementwithemailaddressoptions)
```typescript
export interface InitiateOnDeviceConversionMeasurementWithEmailAddressOptions {
/**
* The email address to initiate on-device conversion measurement with.
*
* @since 7.2.0
*/
emailAddress: string;
}
```
### `InitiateOnDeviceConversionMeasurementWithPhoneNumberOptions`
[Section titled âInitiateOnDeviceConversionMeasurementWithPhoneNumberOptionsâ](#initiateondeviceconversionmeasurementwithphonenumberoptions)
```typescript
export interface InitiateOnDeviceConversionMeasurementWithPhoneNumberOptions {
/**
* The phone number to initiate on-device conversion measurement with.
*
* @since 7.2.0
*/
phoneNumber: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-app
> Capacitor plugin for Firebase App.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase App.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getName` - Get the name for this app.
* `getOptions` - Get the configuration options for this app.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------- |
| `getName` | Get the name for this app. |
| `getOptions` | Get the configuration options for this app. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# @capgo/capacitor-firebase-app-check
> Capacitor plugin for Firebase App Check.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase App Check.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getToken` - Get the current App Check token.
* `initialize` - Activate App Check for the given app. Can be called only once per app.
* `setTokenAutoRefreshEnabled` - Set whether the App Check token should be refreshed automatically or not.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------- | ------------------------------------------------------------------------- |
| `getToken` | Get the current App Check token. |
| `initialize` | Activate App Check for the given app. Can be called only once per app. |
| `setTokenAutoRefreshEnabled` | Set whether the App Check token should be refreshed automatically or not. |
| `addListener` | Called when the App Check token changed. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-app-check and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-app-check
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseAppCheck } from '@capgo/capacitor-firebase-app-check';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getToken`
[Section titled âgetTokenâ](#gettoken)
Get the current App Check token.
```typescript
import { FirebaseAppCheck } from '@capgo/capacitor-firebase-app-check';
await FirebaseAppCheck.getToken();
```
### `initialize`
[Section titled âinitializeâ](#initialize)
Activate App Check for the given app. Can be called only once per app.
```typescript
import { FirebaseAppCheck } from '@capgo/capacitor-firebase-app-check';
await FirebaseAppCheck.initialize();
```
### `setTokenAutoRefreshEnabled`
[Section titled âsetTokenAutoRefreshEnabledâ](#settokenautorefreshenabled)
Set whether the App Check token should be refreshed automatically or not.
```typescript
import { FirebaseAppCheck } from '@capgo/capacitor-firebase-app-check';
await FirebaseAppCheck.setTokenAutoRefreshEnabled({} as SetTokenAutoRefreshEnabledOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetTokenOptions`
[Section titled âGetTokenOptionsâ](#gettokenoptions)
```typescript
export interface GetTokenOptions {
/**
* If `true`, will always try to fetch a fresh token.
* If `false`, will use a cached token if found in storage.
*
* @since 1.3.0
* @default false
*/
forceRefresh?: boolean;
}
```
### `GetTokenResult`
[Section titled âGetTokenResultâ](#gettokenresult)
```typescript
export interface GetTokenResult {
/**
* The App Check token in JWT format.
*
* @since 1.3.0
*/
token: string;
/**
* The timestamp after which the token will expire in milliseconds since epoch.
*
* Only available for Android and iOS.
*
* @since 1.3.0
*/
expireTimeMillis?: number;
}
```
### `InitializeOptions`
[Section titled âInitializeOptionsâ](#initializeoptions)
```typescript
export interface InitializeOptions {
/**
* If `true`, the debug provider is used.
*
* â ď¸ **Attention**: The debug provider allows access to your Firebase resources from unverified devices.
* Don't use the debug provider in production builds of your app, and don't share your debug builds with untrusted parties.
*
* â ď¸ **Deprecated**: Use `debugToken` instead. This option will be removed in the next major version.
*
* Read more: https://firebase.google.com/docs/app-check/web/debug-provider
*
* @since 1.3.0
* @deprecated Use `debugToken` instead. This option will be removed in the next major version.
* @default false
*/
debug?: boolean;
/**
* If `true`, the debug provider is used.
*
* On **Web**, you can also set a predefined debug token string instead of `true`. On Android and iOS, you have to use environment variables for this.
*
* â ď¸ **Attention**: The debug provider allows access to your Firebase resources from unverified devices.
* Don't use the debug provider in production builds of your app, and don't share your debug builds with untrusted parties.
*
* @since 7.1.0
* @default false
* @see https://firebase.google.com/docs/app-check/android/debug-provider#ci
* @see https://firebase.google.com/docs/app-check/ios/debug-provider#ci
* @see https://firebase.google.com/docs/app-check/web/debug-provider
*/
debugToken?: boolean | string;
/**
* If `true`, the SDK automatically refreshes App Check tokens as needed.
*
* @since 1.3.0
* @default false
*/
isTokenAutoRefreshEnabled?: boolean;
/**
* The provider to use for App Check. Must be an instance of
* `ReCaptchaV3Provider`, `ReCaptchaEnterpriseProvider`, or `CustomProvider`.
*
* Only available for Web.
*
* @since 7.1.0
* @default ReCaptchaV3Provider
* @see https://firebase.google.com/docs/app-check/web/custom-provider
*/
provider?: any;
/**
* The reCAPTCHA v3 site key (public key). This option is ignored when `provider` is set.
*
* Only available for Web.
*
* @deprecated Use `provider` instead.
* @since 1.3.0
*/
siteKey?: string;
}
```
### `SetTokenAutoRefreshEnabledOptions`
[Section titled âSetTokenAutoRefreshEnabledOptionsâ](#settokenautorefreshenabledoptions)
```typescript
export interface SetTokenAutoRefreshEnabledOptions {
/**
* If `true`, the SDK automatically refreshes App Check tokens as needed.
* This overrides any value set during initializeAppCheck().
*
* @since 1.3.0
*/
enabled: boolean;
}
```
### `TokenChangedListener`
[Section titled âTokenChangedListenerâ](#tokenchangedlistener)
Callback to receive the token change event.
```typescript
export type TokenChangedListener = (event: TokenChangedEvent) => void;
```
### `GetPluginVersionResult`
[Section titled âGetPluginVersionResultâ](#getpluginversionresult)
```typescript
export interface GetPluginVersionResult {
/**
* The semantic version of this plugin.
*
* @since 8.0.1
*/
version: string;
}
```
### `TokenChangedEvent`
[Section titled âTokenChangedEventâ](#tokenchangedevent)
```typescript
export interface TokenChangedEvent {
/**
* The App Check token in JWT format.
*
* @since 1.3.0
*/
token: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# Getting Started
> Install @capgo/capacitor-firebase-app and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-app
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseApp } from '@capgo/capacitor-firebase-app';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `getName`
[Section titled âgetNameâ](#getname)
Get the name for this app.
```typescript
import { FirebaseApp } from '@capgo/capacitor-firebase-app';
await FirebaseApp.getName();
```
### `getOptions`
[Section titled âgetOptionsâ](#getoptions)
Get the configuration options for this app.
```typescript
import { FirebaseApp } from '@capgo/capacitor-firebase-app';
await FirebaseApp.getOptions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `GetNameResult`
[Section titled âGetNameResultâ](#getnameresult)
```typescript
export interface GetNameResult {
/**
* The unique name of this app.
*
* @since 0.1.0
*/
name: string;
}
```
### `GetOptionsResult`
[Section titled âGetOptionsResultâ](#getoptionsresult)
```typescript
export interface GetOptionsResult {
/**
* API key used for authenticating requests from your app.
*
* @since 0.1.0
*/
apiKey: string;
/**
* Google App ID used to uniquely identify an instance of an app.
*
* @since 0.1.0
*/
applicationId: string;
/**
* The database root URL.
*
* @since 0.1.0
*/
databaseUrl: string;
/**
* The Project Number.
*
* @since 0.1.0
*/
gcmSenderId: string;
/**
* The Google Cloud project ID.
*
* @since 0.1.0
*/
projectId: string;
/**
* The Google Cloud Storage bucket name.
*
* @since 0.1.0
*/
storageBucket: string;
}
```
### `GetPluginVersionResult`
[Section titled âGetPluginVersionResultâ](#getpluginversionresult)
```typescript
export interface GetPluginVersionResult {
/**
* The semantic version of this plugin.
*
* @since 8.0.1
*/
version: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-authentication
> Capacitor plugin for Firebase Authentication.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Authentication.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `applyActionCode` - Applies a verification code sent to the user by email.
* `confirmPasswordReset` - Completes the password reset process.
* `confirmVerificationCode` - Finishes the phone number verification process.
* `createUserWithEmailAndPassword` - Creates a new user account with email and password. If the new account was created, the user is signed in automatically.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `applyActionCode` | Applies a verification code sent to the user by email. |
| `confirmPasswordReset` | Completes the password reset process. |
| `confirmVerificationCode` | Finishes the phone number verification process. |
| `createUserWithEmailAndPassword` | Creates a new user account with email and password. If the new account was created, the user is signed in automatically. |
| `deleteUser` | Deletes and signs out the user. |
| `fetchSignInMethodsForEmail` | Fetches the sign-in methods for an email address. |
| `getCurrentUser` | Fetches the currently signed-in user. |
| `getPendingAuthResult` | Returns the `SignInResult` if your app launched a web sign-in flow and the OS cleans up the app while in the background. |
| `getIdToken` | Fetches the Firebase Auth ID Token for the currently signed-in user. |
| `getIdTokenResult` | Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service. |
| `getRedirectResult` | Returns the `SignInResult` from the redirect-based sign-in flow. |
| `getTenantId` | Get the tenant id. |
| `isSignInWithEmailLink` | Checks if an incoming link is a sign-in with email link suitable for `signInWithEmailLink`. |
| `linkWithApple` | Links the user account with Apple authentication provider. |
| `linkWithEmailAndPassword` | Links the user account with Email authentication provider. |
| `linkWithEmailLink` | Links the user account with Email authentication provider. |
| `linkWithFacebook` | Links the user account with Facebook authentication provider. |
| `linkWithGameCenter` | Links the user account with Game Center authentication provider. |
| `linkWithGithub` | Links the user account with GitHub authentication provider. |
| `linkWithGoogle` | Links the user account with Google authentication provider. |
| `linkWithMicrosoft` | Links the user account with Microsoft authentication provider. |
| `linkWithOpenIdConnect` | Links the user account with an OpenID Connect provider. |
| `linkWithPhoneNumber` | Links the user account with Phone Number authentication provider. |
| `linkWithPlayGames` | Links the user account with Play Games authentication provider. |
| `linkWithTwitter` | Links the user account with Twitter authentication provider. |
| `linkWithYahoo` | Links the user account with Yahoo authentication provider. |
| `reload` | Reloads user account data, if signed in. |
| `revokeAccessToken` | Revokes the given access token. Currently only supports Apple OAuth access tokens. |
| `sendEmailVerification` | Sends a verification email to the currently signed in user. |
| `sendPasswordResetEmail` | Sends a password reset email. |
| `sendSignInLinkToEmail` | Sends a sign-in email link to the user with the specified email. |
| `setLanguageCode` | Sets the user-facing language code for auth operations. |
| `setPersistence` | Sets the type of persistence for the currently saved auth session. |
| `setTenantId` | Sets the tenant id. |
| `signInAnonymously` | Signs in as an anonymous user. |
| `signInWithApple` | Starts the Apple sign-in flow. |
| `signInWithCustomToken` | Starts the Custom Token sign-in flow. |
| `signInWithEmailAndPassword` | Starts the sign-in flow using an email and password. |
| `signInWithEmailLink` | Signs in using an email and sign-in email link. |
| `signInWithFacebook` | Starts the Facebook sign-in flow. |
| `signInWithGameCenter` | Starts the Game Center sign-in flow. |
| `signInWithGithub` | Starts the GitHub sign-in flow. |
| `signInWithGoogle` | Starts the Google sign-in flow. |
| `signInWithMicrosoft` | Starts the Microsoft sign-in flow. |
| `signInWithOpenIdConnect` | Starts the OpenID Connect sign-in flow. |
| `signInWithPhoneNumber` | Starts the sign-in flow using a phone number. |
| `signInWithPlayGames` | Starts the Play Games sign-in flow. |
| `signInWithTwitter` | Starts the Twitter sign-in flow. |
| `signInWithYahoo` | Starts the Yahoo sign-in flow. |
| `signOut` | Starts the sign-out flow. |
| `unlink` | Unlinks a provider from a user account. |
| `updateEmail` | Updates the email address of the currently signed in user. |
| `updatePassword` | Updates the password of the currently signed in user. |
| `updateProfile` | Updates a userâs profile data. |
| `useAppLanguage` | Sets the user-facing language code to be the default app language. |
| `useEmulator` | Instrument your app to talk to the Authentication emulator. |
| `verifyBeforeUpdateEmail` | Verifies the new email address before updating the email address of the currently signed in user. |
| `checkAppTrackingTransparencyPermission` | Checks the current status of app tracking transparency. |
| `requestAppTrackingTransparencyPermission` | Opens the system dialog to authorize app tracking transparency. |
| `addListener` | Listen for the userâs sign-in state changes. |
| `addListener` | Listen to ID token changes for the currently signed-in user. |
| `addListener` | Listen for a completed phone verification. |
| `addListener` | Listen for a failed phone verification. |
| `addListener` | Listen for a phone verification code. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-authentication and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-authentication
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `applyActionCode`
[Section titled âapplyActionCodeâ](#applyactioncode)
Applies a verification code sent to the user by email.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.applyActionCode({} as ApplyActionCodeOptions);
```
### `confirmPasswordReset`
[Section titled âconfirmPasswordResetâ](#confirmpasswordreset)
Completes the password reset process.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.confirmPasswordReset({} as ConfirmPasswordResetOptions);
```
### `confirmVerificationCode`
[Section titled âconfirmVerificationCodeâ](#confirmverificationcode)
Finishes the phone number verification process.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.confirmVerificationCode({} as ConfirmVerificationCodeOptions);
```
### `createUserWithEmailAndPassword`
[Section titled âcreateUserWithEmailAndPasswordâ](#createuserwithemailandpassword)
Creates a new user account with email and password. If the new account was created, the user is signed in automatically.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.createUserWithEmailAndPassword({} as CreateUserWithEmailAndPasswordOptions);
```
### `deleteUser`
[Section titled âdeleteUserâ](#deleteuser)
Deletes and signs out the user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.deleteUser();
```
### `fetchSignInMethodsForEmail`
[Section titled âfetchSignInMethodsForEmailâ](#fetchsigninmethodsforemail)
Fetches the sign-in methods for an email address.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.fetchSignInMethodsForEmail({} as FetchSignInMethodsForEmailOptions);
```
### `getCurrentUser`
[Section titled âgetCurrentUserâ](#getcurrentuser)
Fetches the currently signed-in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getCurrentUser();
```
### `getPendingAuthResult`
[Section titled âgetPendingAuthResultâ](#getpendingauthresult)
Returns the `SignInResult` if your app launched a web sign-in flow and the OS cleans up the app while in the background.
Only available for Android.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getPendingAuthResult();
```
### `getIdToken`
[Section titled âgetIdTokenâ](#getidtoken)
Fetches the Firebase Auth ID Token for the currently signed-in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getIdToken();
```
### `getIdTokenResult`
[Section titled âgetIdTokenResultâ](#getidtokenresult)
Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getIdTokenResult();
```
### `getRedirectResult`
[Section titled âgetRedirectResultâ](#getredirectresult)
Returns the `SignInResult` from the redirect-based sign-in flow.
If sign-in was unsuccessful, fails with an error. If no redirect operation was called, returns a `SignInResult` with a null user.
Only available for Web.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getRedirectResult();
```
### `getTenantId`
[Section titled âgetTenantIdâ](#gettenantid)
Get the tenant id.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.getTenantId();
```
### `isSignInWithEmailLink`
[Section titled âisSignInWithEmailLinkâ](#issigninwithemaillink)
Checks if an incoming link is a sign-in with email link suitable for `signInWithEmailLink`.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.isSignInWithEmailLink({} as IsSignInWithEmailLinkOptions);
```
### `linkWithApple`
[Section titled âlinkWithAppleâ](#linkwithapple)
Links the user account with Apple authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithApple();
```
### `linkWithEmailAndPassword`
[Section titled âlinkWithEmailAndPasswordâ](#linkwithemailandpassword)
Links the user account with Email authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithEmailAndPassword({} as LinkWithEmailAndPasswordOptions);
```
### `linkWithEmailLink`
[Section titled âlinkWithEmailLinkâ](#linkwithemaillink)
Links the user account with Email authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithEmailLink({} as LinkWithEmailLinkOptions);
```
### `linkWithFacebook`
[Section titled âlinkWithFacebookâ](#linkwithfacebook)
Links the user account with Facebook authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithFacebook();
```
### `linkWithGameCenter`
[Section titled âlinkWithGameCenterâ](#linkwithgamecenter)
Links the user account with Game Center authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
Only available for iOS.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithGameCenter();
```
### `linkWithGithub`
[Section titled âlinkWithGithubâ](#linkwithgithub)
Links the user account with GitHub authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithGithub();
```
### `linkWithGoogle`
[Section titled âlinkWithGoogleâ](#linkwithgoogle)
Links the user account with Google authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithGoogle();
```
### `linkWithMicrosoft`
[Section titled âlinkWithMicrosoftâ](#linkwithmicrosoft)
Links the user account with Microsoft authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithMicrosoft();
```
### `linkWithOpenIdConnect`
[Section titled âlinkWithOpenIdConnectâ](#linkwithopenidconnect)
Links the user account with an OpenID Connect provider.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithOpenIdConnect({} as LinkWithOpenIdConnectOptions);
```
### `linkWithPhoneNumber`
[Section titled âlinkWithPhoneNumberâ](#linkwithphonenumber)
Links the user account with Phone Number authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
Use the `phoneVerificationCompleted` listener to be notified when the verification is completed. Use the `phoneVerificationFailed` listener to be notified when the verification is failed. Use the `phoneCodeSent` listener to get the verification id.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithPhoneNumber({} as LinkWithPhoneNumberOptions);
```
### `linkWithPlayGames`
[Section titled âlinkWithPlayGamesâ](#linkwithplaygames)
Links the user account with Play Games authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
Only available for Android.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithPlayGames();
```
### `linkWithTwitter`
[Section titled âlinkWithTwitterâ](#linkwithtwitter)
Links the user account with Twitter authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithTwitter();
```
### `linkWithYahoo`
[Section titled âlinkWithYahooâ](#linkwithyahoo)
Links the user account with Yahoo authentication provider.
The user must be logged in on the native layer. The `skipNativeAuth` configuration option has no effect here.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.linkWithYahoo();
```
### `reload`
[Section titled âreloadâ](#reload)
Reloads user account data, if signed in.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.reload();
```
### `revokeAccessToken`
[Section titled ârevokeAccessTokenâ](#revokeaccesstoken)
Revokes the given access token. Currently only supports Apple OAuth access tokens.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.revokeAccessToken({} as RevokeAccessTokenOptions);
```
### `sendEmailVerification`
[Section titled âsendEmailVerificationâ](#sendemailverification)
Sends a verification email to the currently signed in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.sendEmailVerification();
```
### `sendPasswordResetEmail`
[Section titled âsendPasswordResetEmailâ](#sendpasswordresetemail)
Sends a password reset email.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.sendPasswordResetEmail({} as SendPasswordResetEmailOptions);
```
### `sendSignInLinkToEmail`
[Section titled âsendSignInLinkToEmailâ](#sendsigninlinktoemail)
Sends a sign-in email link to the user with the specified email.
To complete sign in with the email link, call `signInWithEmailLink` with the email address and the email link supplied in the email sent to the user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.sendSignInLinkToEmail({} as SendSignInLinkToEmailOptions);
```
### `setLanguageCode`
[Section titled âsetLanguageCodeâ](#setlanguagecode)
Sets the user-facing language code for auth operations.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.setLanguageCode({} as SetLanguageCodeOptions);
```
### `setPersistence`
[Section titled âsetPersistenceâ](#setpersistence)
Sets the type of persistence for the currently saved auth session.
Only available for Web.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.setPersistence({} as SetPersistenceOptions);
```
### `setTenantId`
[Section titled âsetTenantIdâ](#settenantid)
Sets the tenant id.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.setTenantId({} as SetTenantIdOptions);
```
### `signInAnonymously`
[Section titled âsignInAnonymouslyâ](#signinanonymously)
Signs in as an anonymous user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInAnonymously();
```
### `signInWithApple`
[Section titled âsignInWithAppleâ](#signinwithapple)
Starts the Apple sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithApple();
```
### `signInWithCustomToken`
[Section titled âsignInWithCustomTokenâ](#signinwithcustomtoken)
Starts the Custom Token sign-in flow.
This method cannot be used in combination with `skipNativeAuth` on Android and iOS. In this case you have to use the `signInWithCustomToken` interface of the Firebase JS SDK directly.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithCustomToken({} as SignInWithCustomTokenOptions);
```
### `signInWithEmailAndPassword`
[Section titled âsignInWithEmailAndPasswordâ](#signinwithemailandpassword)
Starts the sign-in flow using an email and password.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithEmailAndPassword({} as SignInWithEmailAndPasswordOptions);
```
### `signInWithEmailLink`
[Section titled âsignInWithEmailLinkâ](#signinwithemaillink)
Signs in using an email and sign-in email link.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithEmailLink({} as SignInWithEmailLinkOptions);
```
### `signInWithFacebook`
[Section titled âsignInWithFacebookâ](#signinwithfacebook)
Starts the Facebook sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithFacebook();
```
### `signInWithGameCenter`
[Section titled âsignInWithGameCenterâ](#signinwithgamecenter)
Starts the Game Center sign-in flow.
Only available for iOS.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithGameCenter();
```
### `signInWithGithub`
[Section titled âsignInWithGithubâ](#signinwithgithub)
Starts the GitHub sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithGithub();
```
### `signInWithGoogle`
[Section titled âsignInWithGoogleâ](#signinwithgoogle)
Starts the Google sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithGoogle();
```
### `signInWithMicrosoft`
[Section titled âsignInWithMicrosoftâ](#signinwithmicrosoft)
Starts the Microsoft sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithMicrosoft();
```
### `signInWithOpenIdConnect`
[Section titled âsignInWithOpenIdConnectâ](#signinwithopenidconnect)
Starts the OpenID Connect sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithOpenIdConnect({} as SignInWithOpenIdConnectOptions);
```
### `signInWithPhoneNumber`
[Section titled âsignInWithPhoneNumberâ](#signinwithphonenumber)
Starts the sign-in flow using a phone number.
Use the `phoneVerificationCompleted` listener to be notified when the verification is completed. Use the `phoneVerificationFailed` listener to be notified when the verification is failed. Use the `phoneCodeSent` listener to get the verification id.
Only available for Android and iOS.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithPhoneNumber({} as SignInWithPhoneNumberOptions);
```
### `signInWithPlayGames`
[Section titled âsignInWithPlayGamesâ](#signinwithplaygames)
Starts the Play Games sign-in flow.
Only available for Android.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithPlayGames();
```
### `signInWithTwitter`
[Section titled âsignInWithTwitterâ](#signinwithtwitter)
Starts the Twitter sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithTwitter();
```
### `signInWithYahoo`
[Section titled âsignInWithYahooâ](#signinwithyahoo)
Starts the Yahoo sign-in flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signInWithYahoo();
```
### `signOut`
[Section titled âsignOutâ](#signout)
Starts the sign-out flow.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.signOut();
```
### `unlink`
[Section titled âunlinkâ](#unlink)
Unlinks a provider from a user account.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.unlink({} as UnlinkOptions);
```
### `updateEmail`
[Section titled âupdateEmailâ](#updateemail)
Updates the email address of the currently signed in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.updateEmail({} as UpdateEmailOptions);
```
### `updatePassword`
[Section titled âupdatePasswordâ](#updatepassword)
Updates the password of the currently signed in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.updatePassword({} as UpdatePasswordOptions);
```
### `updateProfile`
[Section titled âupdateProfileâ](#updateprofile)
Updates a userâs profile data.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.updateProfile({} as UpdateProfileOptions);
```
### `useAppLanguage`
[Section titled âuseAppLanguageâ](#useapplanguage)
Sets the user-facing language code to be the default app language.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.useAppLanguage();
```
### `useEmulator`
[Section titled âuseEmulatorâ](#useemulator)
Instrument your app to talk to the Authentication emulator.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.useEmulator({} as UseEmulatorOptions);
```
### `verifyBeforeUpdateEmail`
[Section titled âverifyBeforeUpdateEmailâ](#verifybeforeupdateemail)
Verifies the new email address before updating the email address of the currently signed in user.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.verifyBeforeUpdateEmail({} as VerifyBeforeUpdateEmailOptions);
```
### `checkAppTrackingTransparencyPermission`
[Section titled âcheckAppTrackingTransparencyPermissionâ](#checkapptrackingtransparencypermission)
Checks the current status of app tracking transparency.
Only available on iOS.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.checkAppTrackingTransparencyPermission();
```
### `requestAppTrackingTransparencyPermission`
[Section titled ârequestAppTrackingTransparencyPermissionâ](#requestapptrackingtransparencypermission)
Opens the system dialog to authorize app tracking transparency.
**Attention:** The user may have disabled the tracking request in the device settings, see [Appleâs documentation](https://support.apple.com/guide/iphone/iph4f4cbd242/ios).
Only available on iOS.
```typescript
import { FirebaseAuthentication } from '@capgo/capacitor-firebase-authentication';
await FirebaseAuthentication.requestAppTrackingTransparencyPermission();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ApplyActionCodeOptions`
[Section titled âApplyActionCodeOptionsâ](#applyactioncodeoptions)
```typescript
export interface ApplyActionCodeOptions {
/**
* A verification code sent to the user.
*
* @since 0.2.2
*/
oobCode: string;
}
```
### `ConfirmPasswordResetOptions`
[Section titled âConfirmPasswordResetOptionsâ](#confirmpasswordresetoptions)
```typescript
export interface ConfirmPasswordResetOptions {
/**
* A verification code sent to the user.
*
* @since 0.2.2
*/
oobCode: string;
/**
* The new password.
*
* @since 0.2.2
*/
newPassword: string;
}
```
### `ConfirmVerificationCodeOptions`
[Section titled âConfirmVerificationCodeOptionsâ](#confirmverificationcodeoptions)
```typescript
export interface ConfirmVerificationCodeOptions {
/**
* The verification ID received from the `phoneCodeSent` listener.
*
* The `verificationCode` option must also be provided.
*
* @since 5.0.0
*/
verificationId: string;
/**
* The verification code either received from the `phoneCodeSent` listener or entered by the user.
*
* The `verificationId` option must also be provided.
*
* @since 5.0.0
*/
verificationCode: string;
}
```
### `SignInResult`
[Section titled âSignInResultâ](#signinresult)
```typescript
export interface SignInResult {
/**
* The currently signed-in user, or null if there isn't any.
*
* @since 0.1.0
*/
user: User | null;
/**
* Credentials returned by an auth provider.
*
* @since 0.1.0
*/
credential: AuthCredential | null;
/**
* Additional user information from a federated identity provider.
*
* @since 0.5.1
*/
additionalUserInfo: AdditionalUserInfo | null;
}
```
### `CreateUserWithEmailAndPasswordOptions`
[Section titled âCreateUserWithEmailAndPasswordOptionsâ](#createuserwithemailandpasswordoptions)
```typescript
export interface CreateUserWithEmailAndPasswordOptions {
/**
* @since 0.2.2
*/
email: string;
/**
* @since 0.2.2
*/
password: string;
}
```
### `FetchSignInMethodsForEmailOptions`
[Section titled âFetchSignInMethodsForEmailOptionsâ](#fetchsigninmethodsforemailoptions)
```typescript
export interface FetchSignInMethodsForEmailOptions {
/**
* The user's email address.
*
* @since 6.0.0
*/
email: string;
}
```
### `FetchSignInMethodsForEmailResult`
[Section titled âFetchSignInMethodsForEmailResultâ](#fetchsigninmethodsforemailresult)
```typescript
export interface FetchSignInMethodsForEmailResult {
/**
* The sign-in methods for the specified email address.
*
* This list is empty when [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
* is enabled, irrespective of the number of authentication methods available for the given email.
*
* @since 6.0.0
*/
signInMethods: string[];
}
```
### `GetCurrentUserResult`
[Section titled âGetCurrentUserResultâ](#getcurrentuserresult)
```typescript
export interface GetCurrentUserResult {
/**
* The currently signed-in user, or null if there isn't any.
*
* @since 0.1.0
*/
user: User | null;
}
```
### `GetIdTokenOptions`
[Section titled âGetIdTokenOptionsâ](#getidtokenoptions)
```typescript
export interface GetIdTokenOptions {
/**
* Force refresh regardless of token expiration.
*
* @since 0.1.0
*/
forceRefresh: boolean;
}
```
### `GetIdTokenResult`
[Section titled âGetIdTokenResultâ](#getidtokenresult-1)
```typescript
export interface GetIdTokenResult {
/**
* The Firebase Auth ID token JWT string.
*
* @since 0.1.0
*/
token: string;
}
```
### `GetIdTokenResultOptions`
[Section titled âGetIdTokenResultOptionsâ](#getidtokenresultoptions)
```typescript
export interface GetIdTokenResultOptions {
/**
* Force refresh regardless of token expiration.
*
* @since 7.4.0
*/
forceRefresh: boolean;
}
```
### `GetIdTokenResultResult`
[Section titled âGetIdTokenResultResultâ](#getidtokenresultresult)
```typescript
export interface GetIdTokenResultResult {
/**
* The authentication time in milliseconds since the epoch.
*
* This is the time the user authenticated (signed in) and not the time the token was refreshed.
*
* @since 7.4.0
*/
authTime: number;
/**
* The ID token expiration time in milliseconds since the epoch.
*
* @since 7.4.0
*/
expirationTime: number;
/**
* The ID token issuance time in milliseconds since the epoch.
*
* @since 7.4.0
*/
issuedAtTime: number;
/**
* The sign-in provider through which the ID token was obtained.
*
* @since 7.4.0
*/
signInProvider: string | null;
/**
* The type of second factor associated with this session, provided the user was multi-factor
* authenticated (eg. phone, etc).
*
* @since 7.4.0
*/
signInSecondFactor: string | null;
/**
* The entire payload claims of the ID token including the standard reserved claims as well as
* the custom claims.
*
* @since 7.4.0
*/
claims: Record;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-crashlytics
> Capacitor plugin for Firebase Crashlytics.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Crashlytics.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `crash` - Forces a crash to test the implementation.
* `setCustomKey` - Sets a custom key and value that is associated with subsequent fatal and non-fatal reports.
* `setUserId` - Sets a user ID (identifier) that is associated with subsequent fatal and non-fatal reports.
* `log` - Adds a custom log message that is sent with your crash data to give yourself more context for the events leading up to a crash.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `crash` | Forces a crash to test the implementation. |
| `setCustomKey` | Sets a custom key and value that is associated with subsequent fatal and non-fatal reports. |
| `setUserId` | Sets a user ID (identifier) that is associated with subsequent fatal and non-fatal reports. |
| `log` | Adds a custom log message that is sent with your crash data to give yourself more context for the events leading up to a crash. |
| `setEnabled` | Enables/disables automatic data collection. The value does not apply until the next run of the app. |
| `isEnabled` | Returns whether automatic data collection is enabled. |
| `didCrashOnPreviousExecution` | Returns whether the app crashed during the previous execution. |
| `sendUnsentReports` | Uploads any unsent reports to Crashlytics at next startup. |
| `deleteUnsentReports` | Deletes any unsent reports on the device. |
| `recordException` | Records a non-fatal report to send to Crashlytics. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-crashlytics and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-crashlytics
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `crash`
[Section titled âcrashâ](#crash)
Forces a crash to test the implementation.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.crash({} as CrashOptions);
```
### `setCustomKey`
[Section titled âsetCustomKeyâ](#setcustomkey)
Sets a custom key and value that is associated with subsequent fatal and non-fatal reports.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.setCustomKey({} as SetCustomKeyOptions);
```
### `setUserId`
[Section titled âsetUserIdâ](#setuserid)
Sets a user ID (identifier) that is associated with subsequent fatal and non-fatal reports.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.setUserId({} as SetUserIdOptions);
```
### `log`
[Section titled âlogâ](#log)
Adds a custom log message that is sent with your crash data to give yourself more context for the events leading up to a crash.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.log({} as LogOptions);
```
### `setEnabled`
[Section titled âsetEnabledâ](#setenabled)
Enables/disables automatic data collection. The value does not apply until the next run of the app.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.setEnabled({} as SetEnabledOptions);
```
### `isEnabled`
[Section titled âisEnabledâ](#isenabled)
Returns whether or not automatic data collection is enabled.
Only available for iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.isEnabled();
```
### `didCrashOnPreviousExecution`
[Section titled âdidCrashOnPreviousExecutionâ](#didcrashonpreviousexecution)
Returns whether the app crashed during the previous execution.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.didCrashOnPreviousExecution();
```
### `sendUnsentReports`
[Section titled âsendUnsentReportsâ](#sendunsentreports)
Uploads any unsent reports to Crashlytics at next startup.
When automatic data collection is enabled, Crashlytics automatically uploads reports at startup.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.sendUnsentReports();
```
### `deleteUnsentReports`
[Section titled âdeleteUnsentReportsâ](#deleteunsentreports)
Deletes any unsent reports on the device.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.deleteUnsentReports();
```
### `recordException`
[Section titled ârecordExceptionâ](#recordexception)
Records a non-fatal report to send to Crashlytics.
Only available for Android and iOS.
```typescript
import { FirebaseCrashlytics } from '@capgo/capacitor-firebase-crashlytics';
await FirebaseCrashlytics.recordException({} as RecordExceptionOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CrashOptions`
[Section titled âCrashOptionsâ](#crashoptions)
```typescript
export interface CrashOptions {
/**
* @since 0.1.0
*/
message: string;
}
```
### `SetCustomKeyOptions`
[Section titled âSetCustomKeyOptionsâ](#setcustomkeyoptions)
```typescript
export type SetCustomKeyOptions = CustomKeyAndValue;
```
### `SetUserIdOptions`
[Section titled âSetUserIdOptionsâ](#setuseridoptions)
```typescript
export interface SetUserIdOptions {
/**
* @since 0.1.0
*/
userId: string;
}
```
### `LogOptions`
[Section titled âLogOptionsâ](#logoptions)
```typescript
export interface LogOptions {
/**
* @since 0.1.0
*/
message: string;
}
```
### `SetEnabledOptions`
[Section titled âSetEnabledOptionsâ](#setenabledoptions)
```typescript
export interface SetEnabledOptions {
/**
* @since 0.1.0
*/
enabled: boolean;
}
```
### `IsEnabledResult`
[Section titled âIsEnabledResultâ](#isenabledresult)
```typescript
export interface IsEnabledResult {
/**
* @since 0.1.0
*/
enabled: boolean;
}
```
### `DidCrashOnPreviousExecutionResult`
[Section titled âDidCrashOnPreviousExecutionResultâ](#didcrashonpreviousexecutionresult)
```typescript
export interface DidCrashOnPreviousExecutionResult {
/**
* @since 0.1.0
*/
crashed: boolean;
}
```
### `RecordExceptionOptions`
[Section titled âRecordExceptionOptionsâ](#recordexceptionoptions)
```typescript
export interface RecordExceptionOptions {
/**
* The message to record as a non-fatal exception.
*
* @since 0.1.0
*/
message: string;
/**
* Error code within a specific error domain.
*
* **Attention:** This option is ignored on iOS if `stacktrace` is provided.
*
* Only available for iOS.
*
* @since 0.1.0
*/
code?: number;
/**
* A string containing the error domain.
*
* **Attention:** This option is ignored on iOS if `stacktrace` is provided.
*
* Only available for iOS.
*
* @since 0.1.0
*/
domain?: string;
/**
* An array of keys and the values to associate with the non fatal exception,
* in addition to the app level custom keys.
*
* **Attention:** This option is ignored on iOS if `stacktrace` is provided.
*
* @since 7.1.0
*/
keysAndValues?: CustomKeyAndValue[];
/**
* A stacktrace generated by stacktrace.js.
*
* @since 1.1.0
*/
stacktrace?: StackFrame[];
}
```
### `GetPluginVersionResult`
[Section titled âGetPluginVersionResultâ](#getpluginversionresult)
```typescript
export interface GetPluginVersionResult {
/**
* The semantic version of this plugin.
*
* @since 8.0.2
*/
version: string;
}
```
### `CustomKeyAndValue`
[Section titled âCustomKeyAndValueâ](#customkeyandvalue)
```typescript
export interface CustomKeyAndValue {
/**
* @since 7.1.0
*/
key: string;
/**
* @since 7.1.0
*/
value: string | number | boolean;
/**
* @since 7.1.0
*/
type: 'string' | 'long' | 'double' | 'boolean' | 'int' | 'float';
}
```
### `StackFrame`
[Section titled âStackFrameâ](#stackframe)
Subset of the Stacktrace generated by stacktrace.js.
```typescript
export interface StackFrame {
lineNumber?: number;
fileName?: string;
functionName?: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-firestore
> Capacitor plugin for Firebase Cloud Firestore.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Cloud Firestore.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `addDocument` - Adds a new document to a collection with the given data.
* `setDocument` - Writes to the document referred to by the specified reference. If the document does not yet exist, it will be created.
* `getDocument` - Reads the document referred to by the specified reference.
* `updateDocument` - Updates fields in the document referred to by the specified reference.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `addDocument` | Adds a new document to a collection with the given data. |
| `setDocument` | Writes to the document referred to by the specified reference. If the document does not yet exist, it will be created. |
| `getDocument` | Reads the document referred to by the specified reference. |
| `updateDocument` | Updates fields in the document referred to by the specified reference. |
| `deleteDocument` | Deletes the document referred to by the specified reference. |
| `writeBatch` | Execute multiple write operations as a single batch. |
| `getCollection` | Reads the collection referenced by the specified reference. |
| `getCollectionGroup` | Reads the collection group referenced by the specified reference. |
| `getCountFromServer` | Fetches the number of documents in a collection. |
| `clearPersistence` | Clears the persistent storage. This includes pending writes and cached documents. |
| `enableNetwork` | Re-enables use of the network. |
| `disableNetwork` | Disables use of the network. |
| `useEmulator` | Instrument your app to talk to the Firestore emulator. |
| `addDocumentSnapshotListener` | Adds a listener for document snapshot events. |
| `addCollectionSnapshotListener` | Adds a listener for collection snapshot events. |
| `addCollectionGroupSnapshotListener` | Adds a listener for collection group snapshot events. |
| `removeSnapshotListener` | Remove a listener for document or collection snapshot events. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-firestore and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-firestore
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `addDocument`
[Section titled âaddDocumentâ](#adddocument)
Adds a new document to a collection with the given data.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.addDocument({} as AddDocumentOptions);
```
### `setDocument`
[Section titled âsetDocumentâ](#setdocument)
Writes to the document referred to by the specified reference. If the document does not yet exist, it will be created.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.setDocument({} as SetDocumentOptions);
```
### `getDocument`
[Section titled âgetDocumentâ](#getdocument)
Reads the document referred to by the specified reference.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.getDocument({} as GetDocumentOptions);
```
### `updateDocument`
[Section titled âupdateDocumentâ](#updatedocument)
Updates fields in the document referred to by the specified reference.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.updateDocument({} as UpdateDocumentOptions);
```
### `deleteDocument`
[Section titled âdeleteDocumentâ](#deletedocument)
Deletes the document referred to by the specified reference.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.deleteDocument({} as DeleteDocumentOptions);
```
### `writeBatch`
[Section titled âwriteBatchâ](#writebatch)
Execute multiple write operations as a single batch.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.writeBatch({} as WriteBatchOptions);
```
### `getCollection`
[Section titled âgetCollectionâ](#getcollection)
Reads the collection referenced by the specified reference.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.getCollection({} as GetCollectionOptions);
```
### `getCollectionGroup`
[Section titled âgetCollectionGroupâ](#getcollectiongroup)
Reads the collection group referenced by the specified reference.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.getCollectionGroup({} as GetCollectionGroupOptions);
```
### `getCountFromServer`
[Section titled âgetCountFromServerâ](#getcountfromserver)
Fetches the number of documents in a collection.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.getCountFromServer({} as GetCountFromServerOptions);
```
### `clearPersistence`
[Section titled âclearPersistenceâ](#clearpersistence)
Clears the persistent storage. This includes pending writes and cached documents.
Must be called after the app is shutdown or when the app is first initialized.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.clearPersistence();
```
### `enableNetwork`
[Section titled âenableNetworkâ](#enablenetwork)
Re-enables use of the network.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.enableNetwork();
```
### `disableNetwork`
[Section titled âdisableNetworkâ](#disablenetwork)
Disables use of the network.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.disableNetwork();
```
### `useEmulator`
[Section titled âuseEmulatorâ](#useemulator)
Instrument your app to talk to the Firestore emulator.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.useEmulator({} as UseEmulatorOptions);
```
### `addDocumentSnapshotListener`
[Section titled âaddDocumentSnapshotListenerâ](#adddocumentsnapshotlistener)
Adds a listener for document snapshot events.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.addDocumentSnapshotListener({} as AddDocumentSnapshotListenerOptions, {} as AddDocumentSnapshotListenerCallback);
```
### `addCollectionSnapshotListener`
[Section titled âaddCollectionSnapshotListenerâ](#addcollectionsnapshotlistener)
Adds a listener for collection snapshot events.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.addCollectionSnapshotListener({} as AddCollectionSnapshotListenerOptions, {} as AddCollectionSnapshotListenerCallback);
```
### `addCollectionGroupSnapshotListener`
[Section titled âaddCollectionGroupSnapshotListenerâ](#addcollectiongroupsnapshotlistener)
Adds a listener for collection group snapshot events.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.addCollectionGroupSnapshotListener({} as AddCollectionGroupSnapshotListenerOptions, {} as AddCollectionGroupSnapshotListenerCallback);
```
### `removeSnapshotListener`
[Section titled âremoveSnapshotListenerâ](#removesnapshotlistener)
Remove a listener for document or collection snapshot events.
```typescript
import { FirebaseFirestore } from '@capgo/capacitor-firebase-firestore';
await FirebaseFirestore.removeSnapshotListener({} as RemoveSnapshotListenerOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AddDocumentOptions`
[Section titled âAddDocumentOptionsâ](#adddocumentoptions)
```typescript
export interface AddDocumentOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
* @example 'users'
*/
reference: string;
/**
* An object containing the data for the new document.
*
* @since 5.2.0
* @example { first: 'Alan', last: 'Turing', born: 1912 }
*/
data: DocumentData;
}
```
### `AddDocumentResult`
[Section titled âAddDocumentResultâ](#adddocumentresult)
```typescript
export interface AddDocumentResult {
/**
* The reference of the newly added document.
*
* @since 5.2.0
*/
reference: DocumentReference;
}
```
### `SetDocumentOptions`
[Section titled âSetDocumentOptionsâ](#setdocumentoptions)
```typescript
export interface SetDocumentOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
* @example 'users/Aorq09lkt1ynbR7xhTUx'
*/
reference: string;
/**
* An object containing the data for the new document.
*
* @since 5.2.0
* @example { first: 'Alan', last: 'Turing', born: 1912 }
*/
data: DocumentData;
/**
* Whether to merge the provided data with an existing document.
*
* @since 5.2.0
* @example true
* @default false
*/
merge?: boolean;
}
```
### `DocumentData`
[Section titled âDocumentDataâ](#documentdata)
```typescript
export interface DocumentData {
/**
* A mapping between a field and its value.
*
* @since 5.2.0
*/
[field: string]: any;
}
```
### `GetDocumentOptions`
[Section titled âGetDocumentOptionsâ](#getdocumentoptions)
```typescript
export interface GetDocumentOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
*/
reference: string;
}
```
### `GetDocumentResult`
[Section titled âGetDocumentResultâ](#getdocumentresult)
```typescript
export interface GetDocumentResult {
/**
* The current document contents.
*
* @since 5.2.0
*/
snapshot: DocumentSnapshot;
}
```
### `UpdateDocumentOptions`
[Section titled âUpdateDocumentOptionsâ](#updatedocumentoptions)
```typescript
export interface UpdateDocumentOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
*/
reference: string;
/**
* An object containing the data for the new document.
*
* @since 5.2.0
* @example { first: 'Alan', last: 'Turing', born: 1912 }
*/
data: DocumentData;
}
```
### `DeleteDocumentOptions`
[Section titled âDeleteDocumentOptionsâ](#deletedocumentoptions)
```typescript
export interface DeleteDocumentOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
*/
reference: string;
}
```
### `WriteBatchOptions`
[Section titled âWriteBatchOptionsâ](#writebatchoptions)
```typescript
export interface WriteBatchOptions {
/**
* The operations to execute in the batch.
*
* @since 6.1.0
*/
operations: WriteBatchOperation[];
}
```
### `GetCollectionOptions`
[Section titled âGetCollectionOptionsâ](#getcollectionoptions)
```typescript
export interface GetCollectionOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
*/
reference: string;
/**
* The filter to apply.
*
* @since 5.2.0
*/
compositeFilter?: QueryCompositeFilterConstraint;
/**
* Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.
*
* @since 5.2.0
*/
queryConstraints?: QueryNonFilterConstraint[];
}
```
### `GetCollectionResult`
[Section titled âGetCollectionResultâ](#getcollectionresult)
```typescript
export interface GetCollectionResult {
/**
* The documents in the collection.
*
* @since 5.2.0
*/
snapshots: DocumentSnapshot[];
}
```
### `GetCollectionGroupOptions`
[Section titled âGetCollectionGroupOptionsâ](#getcollectiongroupoptions)
```typescript
export interface GetCollectionGroupOptions {
/**
* The reference as a string, with path components separated by a forward slash (`/`).
*
* @since 5.2.0
*/
reference: string;
/**
* The filter to apply.
*
* @since 5.2.0
*/
compositeFilter?: QueryCompositeFilterConstraint;
/**
* Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.
*
* @since 5.2.0
*/
queryConstraints?: QueryNonFilterConstraint[];
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-functions
> Capacitor plugin for Firebase Cloud Functions.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Cloud Functions.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `callByName` - Call a callable function by name.
* `callByUrl` - Call a callable function by URL.
* `useEmulator` - Instrument your app to talk to the Cloud Functions emulator.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------------------------ |
| `callByName` | Call a callable function by name. |
| `callByUrl` | Call a callable function by URL. |
| `useEmulator` | Instrument your app to talk to the Cloud Functions emulator. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-functions and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-functions
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseFunctions } from '@capgo/capacitor-firebase-functions';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `callByName`
[Section titled âcallByNameâ](#callbyname)
Call a callable function by name.
```typescript
import { FirebaseFunctions } from '@capgo/capacitor-firebase-functions';
await FirebaseFunctions.callByName({} as CallByNameOptions);
```
### `callByUrl`
[Section titled âcallByUrlâ](#callbyurl)
Call a callable function by URL.
```typescript
import { FirebaseFunctions } from '@capgo/capacitor-firebase-functions';
await FirebaseFunctions.callByUrl({} as CallByUrlOptions);
```
### `useEmulator`
[Section titled âuseEmulatorâ](#useemulator)
Instrument your app to talk to the Cloud Functions emulator.
On Android, the cleartext traffic must be allowed. On the Capacitor configuration:
```plaintext
{
server: {
cleartext: true
}
}
```
**The cleartext traffic is not intended for use in production.**
```typescript
import { FirebaseFunctions } from '@capgo/capacitor-firebase-functions';
await FirebaseFunctions.useEmulator({} as UseEmulatorOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CallByNameOptions`
[Section titled âCallByNameOptionsâ](#callbynameoptions)
```typescript
export interface CallByNameOptions extends CallOptions {
/**
* The name of the callable function.
*
* @example 'myFunction'
* @since 6.1.0
*/
name: string;
/**
* The region of the callable function.
*
* @example 'us-central1'
* @since 6.1.0
*/
region?: string;
}
```
### `CallByNameResult`
[Section titled âCallByNameResultâ](#callbynameresult)
```typescript
export type CallByNameResult = CallResult;
```
### `CallByUrlOptions`
[Section titled âCallByUrlOptionsâ](#callbyurloptions)
```typescript
export interface CallByUrlOptions extends CallOptions {
/**
* The URL of the callable function.
*
* @example 'https://us-central1-my-project.cloudfunctions.net/myFunction'
* @since 6.1.0
*/
url: string;
}
```
### `CallByUrlResult`
[Section titled âCallByUrlResultâ](#callbyurlresult)
```typescript
export type CallByUrlResult = CallResult;
```
### `UseEmulatorOptions`
[Section titled âUseEmulatorOptionsâ](#useemulatoroptions)
```typescript
export interface UseEmulatorOptions {
/**
* The emulator host without any port or scheme.
*
* Note when using a Android Emulator device: 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer.
*
* @since 6.1.0
* @example "127.0.0.1"
*/
host: string;
/**
* The emulator port.
*
* @since 6.1.0
* @default 5001
* @example 5001
*/
port?: number;
/**
* The region the callable functions are located in or a custom domain hosting the callable functions.
*
* @example 'us-central1'
* @example 'https://mydomain.com'
*/
regionOrCustomDomain?: string;
}
```
### `GetPluginVersionResult`
[Section titled âGetPluginVersionResultâ](#getpluginversionresult)
```typescript
export interface GetPluginVersionResult {
/**
* The semantic version of this plugin.
*
* @since 8.0.1
*/
version: string;
}
```
### `CallResult`
[Section titled âCallResultâ](#callresult)
```typescript
export interface CallResult {
/**
* The result of the callable function.
*
* @since 6.1.0
*/
data: ResponseData;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-messaging
> Capacitor plugin for Firebase Cloud Messaging (FCM).
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Cloud Messaging (FCM).
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `checkPermissions` - Check permission to receive push notifications.
* `requestPermissions` - Request permission to receive push notifications.
* `isSupported` - Checks if all required APIs exist.
* `getToken` - Register the app to receive push notifications. Returns a FCM token that can be used to send push messages to that Messaging instance.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `checkPermissions` | Check permission to receive push notifications. |
| `requestPermissions` | Request permission to receive push notifications. |
| `isSupported` | Checks if all required APIs exist. |
| `getToken` | Register the app to receive push notifications. Returns a FCM token that can be used to send push messages to that Messaging instance. |
| `deleteToken` | Delete the FCM token and unregister the app to stop receiving push notifications. Can be called, for example, when a user signs out. |
| `getDeliveredNotifications` | Get a list of notifications that are visible on the notifications screen. |
| `removeDeliveredNotifications` | Remove specific notifications from the notifications screen. |
| `removeAllDeliveredNotifications` | Remove all notifications from the notifications screen. |
| `subscribeToTopic` | Subscribes to topic in the background. |
| `unsubscribeFromTopic` | Unsubscribes from topic in the background. |
| `createChannel` | Create a notification channel. |
| `deleteChannel` | Delete a notification channel. |
| `listChannels` | List the available notification channels. |
| `addListener` | Called when a new FCM token is received. |
| `addListener` | Called when a new push notification is received. |
| `addListener` | Called when a new push notification action is performed. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-messaging and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-messaging
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check permission to receive push notifications.
On **Android**, this method only needs to be called on Android 13+.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission to receive push notifications.
On **Android**, this method only needs to be called on Android 13+.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.requestPermissions();
```
### `isSupported`
[Section titled âisSupportedâ](#issupported)
Checks if all required APIs exist.
Always returns `true` on Android and iOS.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.isSupported();
```
### `getToken`
[Section titled âgetTokenâ](#gettoken)
Register the app to receive push notifications. Returns a FCM token that can be used to send push messages to that Messaging instance.
This method also re-enables FCM auto-init.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.getToken();
```
### `deleteToken`
[Section titled âdeleteTokenâ](#deletetoken)
Delete the FCM token and unregister the app to stop receiving push notifications. Can be called, for example, when a user signs out.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.deleteToken();
```
### `getDeliveredNotifications`
[Section titled âgetDeliveredNotificationsâ](#getdeliverednotifications)
Get a list of notifications that are visible on the notifications screen.
Note: This will return all delivered notifications, including local notifications, and not just FCM notifications.
On Android, the data field of the FCM notification will NOT be included.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.getDeliveredNotifications();
```
### `removeDeliveredNotifications`
[Section titled âremoveDeliveredNotificationsâ](#removedeliverednotifications)
Remove specific notifications from the notifications screen.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.removeDeliveredNotifications({} as RemoveDeliveredNotificationsOptions);
```
### `removeAllDeliveredNotifications`
[Section titled âremoveAllDeliveredNotificationsâ](#removealldeliverednotifications)
Remove all notifications from the notifications screen.
Note: This will remove all delivered notifications, including local notifications, and not just FCM notifications.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.removeAllDeliveredNotifications();
```
### `subscribeToTopic`
[Section titled âsubscribeToTopicâ](#subscribetotopic)
Subscribes to topic in the background.
Only available for Android and iOS.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.subscribeToTopic({} as SubscribeToTopicOptions);
```
### `unsubscribeFromTopic`
[Section titled âunsubscribeFromTopicâ](#unsubscribefromtopic)
Unsubscribes from topic in the background.
Only available for Android and iOS.
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.unsubscribeFromTopic({} as UnsubscribeFromTopicOptions);
```
### `createChannel`
[Section titled âcreateChannelâ](#createchannel)
Create a notification channel.
Only available for Android (SDK 26+).
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.createChannel({} as CreateChannelOptions);
```
### `deleteChannel`
[Section titled âdeleteChannelâ](#deletechannel)
Delete a notification channel.
Only available for Android (SDK 26+).
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.deleteChannel({} as DeleteChannelOptions);
```
### `listChannels`
[Section titled âlistChannelsâ](#listchannels)
List the available notification channels.
Only available for Android (SDK 26+).
```typescript
import { FirebaseMessaging } from '@capgo/capacitor-firebase-messaging';
await FirebaseMessaging.listChannels();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
```typescript
export interface PermissionStatus {
/**
* @since 0.2.2
*/
receive: PermissionState;
}
```
### `IsSupportedResult`
[Section titled âIsSupportedResultâ](#issupportedresult)
```typescript
export interface IsSupportedResult {
/**
* @since 0.3.1
*/
isSupported: boolean;
}
```
### `GetTokenOptions`
[Section titled âGetTokenOptionsâ](#gettokenoptions)
```typescript
export interface GetTokenOptions {
/**
* Your VAPID public key, which is required to retrieve the current registration token on the web.
*
* Only available for Web.
*/
vapidKey?: string;
/**
* The service worker registration for receiving push messaging.
* If the registration is not provided explicitly, you need to have a `firebase-messaging-sw.js` at your root location.
*
* Only available for Web.
*/
serviceWorkerRegistration?: ServiceWorkerRegistration;
}
```
### `GetTokenResult`
[Section titled âGetTokenResultâ](#gettokenresult)
```typescript
export interface GetTokenResult {
/**
* @since 0.2.2
*/
token: string;
}
```
### `GetDeliveredNotificationsResult`
[Section titled âGetDeliveredNotificationsResultâ](#getdeliverednotificationsresult)
```typescript
export interface GetDeliveredNotificationsResult {
/**
* @since 0.2.2
*/
notifications: Notification[];
}
```
### `RemoveDeliveredNotificationsOptions`
[Section titled âRemoveDeliveredNotificationsOptionsâ](#removedeliverednotificationsoptions)
```typescript
export interface RemoveDeliveredNotificationsOptions {
/**
* @since 0.4.0
*/
notifications: Notification[];
}
```
### `SubscribeToTopicOptions`
[Section titled âSubscribeToTopicOptionsâ](#subscribetotopicoptions)
```typescript
export interface SubscribeToTopicOptions {
/**
* The name of the topic to subscribe.
*
* @since 0.2.2
*/
topic: string;
}
```
### `UnsubscribeFromTopicOptions`
[Section titled âUnsubscribeFromTopicOptionsâ](#unsubscribefromtopicoptions)
```typescript
export interface UnsubscribeFromTopicOptions {
/**
* The name of the topic to unsubscribe from.
*
* @since 0.2.2
*/
topic: string;
}
```
### `CreateChannelOptions`
[Section titled âCreateChannelOptionsâ](#createchanneloptions)
```typescript
export type CreateChannelOptions = Channel;
```
### `DeleteChannelOptions`
[Section titled âDeleteChannelOptionsâ](#deletechanneloptions)
```typescript
export interface DeleteChannelOptions {
/**
* The channel identifier.
*
* @since 1.4.0
*/
id: string;
}
```
### `ListChannelsResult`
[Section titled âListChannelsResultâ](#listchannelsresult)
```typescript
export interface ListChannelsResult {
channels: Channel[];
}
```
### `TokenReceivedListener`
[Section titled âTokenReceivedListenerâ](#tokenreceivedlistener)
Callback to receive the token received event.
```typescript
export type TokenReceivedListener = (event: TokenReceivedEvent) => void;
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-performance
> Capacitor plugin for Firebase Performance Monitoring.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Performance Monitoring.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startTrace` - Starts a trace.
* `stopTrace` - Stops a trace.
* `incrementMetric` - Atomically increments the metric with the given name for the selected trace by the `incrementBy` value.
* `setEnabled` - Enables or disables performance monitoring. Will be applied with the next start of the app.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| `startTrace` | Starts a trace. |
| `stopTrace` | Stops a trace. |
| `incrementMetric` | Atomically increments the metric with the given name for the selected trace by the `incrementBy` value. |
| `setEnabled` | Enables or disables performance monitoring. Will be applied with the next start of the app. |
| `isEnabled` | Determines whether performance monitoring is enabled or disabled. |
| `putAttribute` | Sets a custom attribute of a trace to a given value. |
| `getAttribute` | Returns the value of a custom attribute of a trace. |
| `getAttributes` | Gets the all the custom attributes of a trace with their values. |
| `removeAttribute` | Removes a custom attribute from a trace given its name. |
| `putMetric` | Sets the value of a custom metric. |
| `getMetric` | Get the value of a custom metric by name. |
| `record` | Records a trace given its name and options. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-performance and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-performance
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `startTrace`
[Section titled âstartTraceâ](#starttrace)
Starts a trace.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.startTrace({} as StartTraceOptions);
```
### `stopTrace`
[Section titled âstopTraceâ](#stoptrace)
Stops a trace.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.stopTrace({} as StopTraceOptions);
```
### `incrementMetric`
[Section titled âincrementMetricâ](#incrementmetric)
Atomically increments the metric with the given name for the selected trace by the `incrementBy` value.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.incrementMetric({} as IncrementMetricOptions);
```
### `setEnabled`
[Section titled âsetEnabledâ](#setenabled)
Enables or disables performance monitoring. Will be applied with the next start of the app.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.setEnabled({} as SetEnabledOptions);
```
### `isEnabled`
[Section titled âisEnabledâ](#isenabled)
Determines whether performance monitoring is enabled or disabled.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.isEnabled();
```
### `putAttribute`
[Section titled âputAttributeâ](#putattribute)
Sets a custom attribute of a trace to a given value.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.putAttribute({} as PutAttributeOptions);
```
### `getAttribute`
[Section titled âgetAttributeâ](#getattribute)
Returns the value of a custom attribute of a trace.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.getAttribute({} as GetAttributeOptions);
```
### `getAttributes`
[Section titled âgetAttributesâ](#getattributes)
Gets the all the custom attributes of a trace with their values.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.getAttributes({} as GetAttributesOptions);
```
### `removeAttribute`
[Section titled âremoveAttributeâ](#removeattribute)
Removes a custom attribute from a trace given its name.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.removeAttribute({} as RemoveAttributeOptions);
```
### `putMetric`
[Section titled âputMetricâ](#putmetric)
Sets the value of a custom metric.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.putMetric({} as PutMetricOptions);
```
### `getMetric`
[Section titled âgetMetricâ](#getmetric)
Get the value of a custom metric by name.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.getMetric({} as GetMetricOptions);
```
### `record`
[Section titled ârecordâ](#record)
Records a trace given its name and options.
Only available on web.
```typescript
import { FirebasePerformance } from '@capgo/capacitor-firebase-performance';
await FirebasePerformance.record({} as RecordOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `StartTraceOptions`
[Section titled âStartTraceOptionsâ](#starttraceoptions)
```typescript
export interface StartTraceOptions {
/**
* Custom trace name.
*
* Names for custom code traces must meet the following requirements:
* no leading or trailing whitespace, no leading underscore (_) character,
* and max length is 100 characters.
*
* @since 0.1.0
*/
traceName: string;
}
```
### `StopTraceOptions`
[Section titled âStopTraceOptionsâ](#stoptraceoptions)
```typescript
export interface StopTraceOptions {
/**
* Name of the trace that was set with `startTrace`.
*
* @since 0.1.0
*/
traceName: string;
}
```
### `IncrementMetricOptions`
[Section titled âIncrementMetricOptionsâ](#incrementmetricoptions)
```typescript
export interface IncrementMetricOptions {
/**
* Name of the trace that was set with `startTrace`.
*
* @since 0.1.0
*/
traceName: string;
/**
* Name of the metric to be incremented.
*
* @since 0.1.0
*/
metricName: string;
/**
* Amount by which the metric has to be incremented.
*
* @default 1
* @since 0.1.0
*/
incrementBy?: number;
}
```
### `SetEnabledOptions`
[Section titled âSetEnabledOptionsâ](#setenabledoptions)
```typescript
export interface SetEnabledOptions {
/**
* Should performance monitoring be enabled.
*
* @since 0.1.0
*/
enabled: boolean;
}
```
### `IsEnabledResult`
[Section titled âIsEnabledResultâ](#isenabledresult)
```typescript
export interface IsEnabledResult {
/**
* `true` if performance monitoring is enabled, otherwise `false`.
*
* @since 0.1.0
*/
enabled: boolean;
}
```
### `PutAttributeOptions`
[Section titled âPutAttributeOptionsâ](#putattributeoptions)
```typescript
export interface PutAttributeOptions {
/**
* Name of the trace to set its attribute.
*
* @since 6.3.0
*/
traceName: string;
/**
* Name of the attribute to set its value.
*
* @since 6.3.0
* @example "experiment"
*/
attribute: string;
/**
* The value to set to the attribute.
*
* @since 6.3.0
* @example "A"
*/
value: string;
}
```
### `GetAttributeOptions`
[Section titled âGetAttributeOptionsâ](#getattributeoptions)
```typescript
export interface GetAttributeOptions {
/**
* Name of the trace to set its attribute.
*
* @since 6.3.0
*/
traceName: string;
/**
* Name of the attribute to retrieve its value.
*
* @since 6.3.0
*/
attribute: string;
}
```
### `GetAttributeResult`
[Section titled âGetAttributeResultâ](#getattributeresult)
```typescript
export interface GetAttributeResult {
/**
* The value of the custom attribute.
*
* @since 6.3.0
*/
value: string | null;
}
```
### `GetAttributesOptions`
[Section titled âGetAttributesOptionsâ](#getattributesoptions)
```typescript
export interface GetAttributesOptions {
/**
* Name of the trace to get its attributes.
*
* @since 6.3.0
*/
traceName: string;
}
```
### `GetAttributesResult`
[Section titled âGetAttributesResultâ](#getattributesresult)
```typescript
export interface GetAttributesResult {
/**
* A map of all custom attributes of a trace with their values.
*
* @since 6.3.0
*/
attributes: { [key: string]: string };
}
```
### `RemoveAttributeOptions`
[Section titled âRemoveAttributeOptionsâ](#removeattributeoptions)
```typescript
export type RemoveAttributeOptions = GetAttributeOptions;
```
### `PutMetricOptions`
[Section titled âPutMetricOptionsâ](#putmetricoptions)
```typescript
export interface PutMetricOptions {
/**
* Name of the trace to set its metric.
*
* @since 6.3.0
*/
traceName: string;
/**
* The metric name.
*
* @since 6.3.0
*/
metricName: string;
/**
* The value to set for the metric.
* The given value is floored down to the nearest integer.
*
* @since 6.3.0
*/
num: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-remote-config
> Capacitor plugin for Firebase Remote Config.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Remote Config.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `activate` - Make the last fetched configuration available to the getters.
* `fetchAndActivate` - Perform fetch and activate operations.
* `fetchConfig` - Fetch and cache configuration from the Remote Config service.
* `getBoolean` - Get the value for the given key as a boolean.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------- | ------------------------------------------------------------- |
| `activate` | Make the last fetched configuration available to the getters. |
| `fetchAndActivate` | Perform fetch and activate operations. |
| `fetchConfig` | Fetch and cache configuration from the Remote Config service. |
| `getBoolean` | Get the value for the given key as a boolean. |
| `getNumber` | Get the value for the given key as a number. |
| `getString` | Get the value for the given key as a string. |
| `getInfo` | Get information about the last fetch operation. |
| `setMinimumFetchInterval` | Set the minimum fetch interval. |
| `setSettings` | Set the remote config settings. |
| `addConfigUpdateListener` | Add a listener for the config update event. |
| `removeConfigUpdateListener` | Remove a listener for the config update event. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-remote-config and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-remote-config
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `activate`
[Section titled âactivateâ](#activate)
Make the last fetched configuration available to the getters.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.activate();
```
### `fetchAndActivate`
[Section titled âfetchAndActivateâ](#fetchandactivate)
Perform fetch and activate operations.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.fetchAndActivate();
```
### `fetchConfig`
[Section titled âfetchConfigâ](#fetchconfig)
Fetch and cache configuration from the Remote Config service.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.fetchConfig();
```
### `getBoolean`
[Section titled âgetBooleanâ](#getboolean)
Get the value for the given key as a boolean.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.getBoolean({} as GetBooleanOptions);
```
### `getNumber`
[Section titled âgetNumberâ](#getnumber)
Get the value for the given key as a number.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.getNumber({} as GetNumberOptions);
```
### `getString`
[Section titled âgetStringâ](#getstring)
Get the value for the given key as a string.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.getString({} as GetStringOptions);
```
### `getInfo`
[Section titled âgetInfoâ](#getinfo)
Get information about the last fetch operation.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.getInfo();
```
### `setMinimumFetchInterval`
[Section titled âsetMinimumFetchIntervalâ](#setminimumfetchinterval)
Set the minimum fetch interval.
Only available for Web.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.setMinimumFetchInterval({} as SetMinimumFetchIntervalOptions);
```
### `setSettings`
[Section titled âsetSettingsâ](#setsettings)
Set the remote config settings.
On Android, the settings values are persisted in SharedPreferences.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.setSettings({} as SetSettingsOptions);
```
### `addConfigUpdateListener`
[Section titled âaddConfigUpdateListenerâ](#addconfigupdatelistener)
Add a listener for the config update event.
Only available for Android and iOS.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.addConfigUpdateListener({} as AddConfigUpdateListenerOptionsCallback);
```
### `removeConfigUpdateListener`
[Section titled âremoveConfigUpdateListenerâ](#removeconfigupdatelistener)
Remove a listener for the config update event.
Only available for Android and iOS.
```typescript
import { FirebaseRemoteConfig } from '@capgo/capacitor-firebase-remote-config';
await FirebaseRemoteConfig.removeConfigUpdateListener({} as RemoveConfigUpdateListenerOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `FetchConfigOptions`
[Section titled âFetchConfigOptionsâ](#fetchconfigoptions)
```typescript
export interface FetchConfigOptions {
/**
* Define the maximum age in seconds of an entry in the config cache before it is considered stale.
* During development, it's recommended to set a relatively low minimum fetch interval.
*
* Only available for Android and iOS.
*
* @since 1.3.0
* @default 43200
* @see https://firebase.google.com/docs/reference/js/firebase.remoteconfig.RemoteConfigSettings#minimumfetchintervalmillis
*/
minimumFetchIntervalInSeconds?: number;
}
```
### `GetBooleanOptions`
[Section titled âGetBooleanOptionsâ](#getbooleanoptions)
```typescript
export type GetBooleanOptions = GetOptions;
```
### `GetBooleanResult`
[Section titled âGetBooleanResultâ](#getbooleanresult)
```typescript
export interface GetBooleanResult {
/**
* The value for the given key as a boolean.
*
* @since 1.3.0
*/
value: boolean;
/**
* Indicates at which source this value came from.
*
* Only available for Android and iOS.
*
* @since 1.3.0
*/
source?: GetValueSource;
}
```
### `GetNumberOptions`
[Section titled âGetNumberOptionsâ](#getnumberoptions)
```typescript
export type GetNumberOptions = GetOptions;
```
### `GetNumberResult`
[Section titled âGetNumberResultâ](#getnumberresult)
```typescript
export interface GetNumberResult {
/**
* The value for the given key as a number.
*
* @since 1.3.0
*/
value: number;
/**
* Indicates at which source this value came from.
*
* Only available for Android and iOS.
*
* @since 1.3.0
*/
source?: GetValueSource;
}
```
### `GetStringOptions`
[Section titled âGetStringOptionsâ](#getstringoptions)
```typescript
export type GetStringOptions = GetOptions;
```
### `GetStringResult`
[Section titled âGetStringResultâ](#getstringresult)
```typescript
export interface GetStringResult {
/**
* The value for the given key as a string.
*
* @since 1.3.0
*/
value: string;
/**
* Indicates at which source this value came from.
*
* Only available for Android and iOS.
*
* @since 1.3.0
*/
source?: GetValueSource;
}
```
### `GetInfoResult`
[Section titled âGetInfoResultâ](#getinforesult)
```typescript
export interface GetInfoResult {
/**
* The Unix timestamp in milliseconds of the last successful fetch, or -1 if no fetch has occurred or initialization is incomplete.
* @since 7.5.0
* @example 1762864760
*/
lastFetchTime: number;
/**
* The status of the last fetch attempt.
* @since 7.5.0
* @example 1
*/
lastFetchStatus: LastFetchStatus;
}
```
### `SetMinimumFetchIntervalOptions`
[Section titled âSetMinimumFetchIntervalOptionsâ](#setminimumfetchintervaloptions)
```typescript
export interface SetMinimumFetchIntervalOptions {
/**
* Define the maximum age in seconds of an entry in the config cache before it is considered stale.
* During development, it's recommended to set a relatively low minimum fetch interval.
*
* @since 1.3.0
* @default 43200
* @see https://firebase.google.com/docs/reference/js/remote-config.remoteconfigsettings#remoteconfigsettingsminimumfetchintervalmillis
*/
minimumFetchIntervalInSeconds: number;
}
```
### `SetSettingsOptions`
[Section titled âSetSettingsOptionsâ](#setsettingsoptions)
```typescript
export interface SetSettingsOptions {
/**
* Defines the maximum amount of milliseconds to wait for a response when fetching configuration from the Remote Config server.
*
* @since 6.2.0
* @default 60
* @see https://firebase.google.com/docs/reference/js/remote-config.remoteconfigsettings#remoteconfigsettingsfetchtimeoutmillis
*/
fetchTimeoutInSeconds?: number;
/**
* Define the maximum age in seconds of an entry in the config cache before it is considered stale.
* During development, it's recommended to set a relatively low minimum fetch interval.
*
* @since 6.2.0
* @default 43200
* @see https://firebase.google.com/docs/reference/js/remote-config.remoteconfigsettings#remoteconfigsettingsminimumfetchintervalmillis
*/
minimumFetchIntervalInSeconds?: number;
}
```
### `AddConfigUpdateListenerOptionsCallback`
[Section titled âAddConfigUpdateListenerOptionsCallbackâ](#addconfigupdatelisteneroptionscallback)
```typescript
export type AddConfigUpdateListenerOptionsCallback = (
event: AddConfigUpdateListenerOptionsCallbackEvent | null,
error: any,
) => void;
```
### `CallbackId`
[Section titled âCallbackIdâ](#callbackid)
```typescript
export type CallbackId = string;
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-firebase-storage
> Capacitor plugin for Firebase Cloud Storage.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Firebase Cloud Storage.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `deleteFile` - Delete a file.
* `getDownloadUrl` - Get the download url for a file.
* `getMetadata` - Get the metadata for a file.
* `listFiles` - List files in a directory.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ---------------------------------------------------------- |
| `deleteFile` | Delete a file. |
| `getDownloadUrl` | Get the download url for a file. |
| `getMetadata` | Get the metadata for a file. |
| `listFiles` | List files in a directory. |
| `updateMetadata` | Update the metadata for a file. |
| `uploadFile` | Upload a file. |
| `useEmulator` | Instrument your app to talk to the Cloud Storage emulator. |
| `getPluginVersion` | Get the version of this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-firebase](https://github.com/Cap-go/capacitor-firebase/).
# Getting Started
> Install @capgo/capacitor-firebase-storage and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-firebase-storage
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `deleteFile`
[Section titled âdeleteFileâ](#deletefile)
Delete a file.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.deleteFile({} as DeleteFileOptions);
```
### `getDownloadUrl`
[Section titled âgetDownloadUrlâ](#getdownloadurl)
Get the download url for a file.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.getDownloadUrl({} as GetDownloadUrlOptions);
```
### `getMetadata`
[Section titled âgetMetadataâ](#getmetadata)
Get the metadata for a file.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.getMetadata({} as GetMetadataOptions);
```
### `listFiles`
[Section titled âlistFilesâ](#listfiles)
List files in a directory.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.listFiles({} as ListFilesOptions);
```
### `updateMetadata`
[Section titled âupdateMetadataâ](#updatemetadata)
Update the metadata for a file.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.updateMetadata({} as UpdateMetadataOptions);
```
### `uploadFile`
[Section titled âuploadFileâ](#uploadfile)
Upload a file.
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.uploadFile({} as UploadFileOptions, {} as UploadFileCallback);
```
### `useEmulator`
[Section titled âuseEmulatorâ](#useemulator)
Instrument your app to talk to the Cloud Storage emulator.
On Android, the cleartext traffic must be allowed. On the Capacitor configuration:
```plaintext
{
server: {
cleartext: true
}
}
```
**The cleartext traffic is not intended for use in production.**
```typescript
import { FirebaseStorage } from '@capgo/capacitor-firebase-storage';
await FirebaseStorage.useEmulator({} as UseEmulatorOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `DeleteFileOptions`
[Section titled âDeleteFileOptionsâ](#deletefileoptions)
```typescript
export interface DeleteFileOptions {
/**
* The full path to the file to delete, including the file name.
*
* @since 5.3.0
* @example 'mountains.png'
* @example 'images/mountains.png'
*/
path: string;
}
```
### `GetDownloadUrlOptions`
[Section titled âGetDownloadUrlOptionsâ](#getdownloadurloptions)
```typescript
export interface GetDownloadUrlOptions {
/**
* The full path to the file to get the download url for, including the file name.
*
* @since 5.3.0
* @example 'mountains.png'
* @example 'images/mountains.png'
*/
path: string;
}
```
### `GetDownloadUrlResult`
[Section titled âGetDownloadUrlResultâ](#getdownloadurlresult)
```typescript
export interface GetDownloadUrlResult {
/**
* The download url for the file.
*
* @since 5.3.0
*/
downloadUrl: string;
}
```
### `GetMetadataOptions`
[Section titled âGetMetadataOptionsâ](#getmetadataoptions)
```typescript
export interface GetMetadataOptions {
/**
* The full path to the file to get the metadata for, including the file name.
*
* @since 5.3.0
* @example 'mountains.png'
* @example 'images/mountains.png'
*/
path: string;
}
```
### `GetMetadataResult`
[Section titled âGetMetadataResultâ](#getmetadataresult)
```typescript
export interface GetMetadataResult {
/**
* The bucket this file is contained in.
*
* @since 5.3.0
*/
bucket: string;
/**
* The timestamp at which the file was created in milliseconds since the epoch.
*
* @since 5.3.0
* @example 1697304435933
*/
createdAt?: number;
/**
* The object's generation.
*
* @since 5.3.0
* @see https://cloud.google.com/storage/docs/metadata#generation-number
*/
generation: string;
/**
* The md5 hash of the file.
*
* @since 5.3.0
*/
md5Hash?: string;
/**
* The object's metadata generation.
*
* @since 5.3.0
* @see https://cloud.google.com/storage/docs/metadata#generation-number
*/
metadataGeneration: string;
/**
* The short name of this file, which is the last component of the full path.
*
* @since 5.3.0
* @example 'mountains.png'
*/
name?: string;
/**
* The full path to the file, including the file name.
*
* @since 5.3.0
* @example 'images/mountains.png'
*/
path?: string;
/**
* The size of the file in bytes.
*
* @since 5.3.0
*/
size: number;
/**
* The timestamp at which the file was last updated in milliseconds since the epoch.
*
* @since 5.3.0
* @example 1697304435933
*/
updatedAt: number;
/**
* Served as the `Cache-Control` header on object download.
*
* @since 6.1.0
*/
cacheControl?: string;
/**
* Served as the `Content-Disposition` header on object download.
*
* @since 6.1.0
*/
contentDisposition?: string;
/**
* Served as the `Content-Encoding` header on object download.
*
* @since 6.1.0
*/
contentEncoding?: string;
/**
* Served as the `Content-Language` header on object download.
*
* @since 6.1.0
*/
contentLanguage?: string;
/**
* Served as the `Content-Type` header on object download.
*
* @since 6.1.0
*/
contentType?: string;
/**
* Additional user-defined custom metadata.
*
* @since 6.1.0
*/
customMetadata?: { [key: string]: string };
}
```
### `ListFilesOptions`
[Section titled âListFilesOptionsâ](#listfilesoptions)
```typescript
export interface ListFilesOptions {
/**
* The full path to the directory to list files for.
*
* @since 5.3.0
*/
path: string;
/**
* The maximum number of results to return.
*
* @since 5.3.0
* @default 1000
*/
maxResults?: number;
/**
* The page token, returned by a previous call to this method.
* If provided, listing is resumed from the previous position.
*
* @since 5.3.0
*/
pageToken?: string;
}
```
### `ListFilesResult`
[Section titled âListFilesResultâ](#listfilesresult)
```typescript
export interface ListFilesResult {
/**
* The list of files in the directory.
*
* @since 5.3.0
*/
items: StorageReference[];
/**
* If set, there might be more results for this list.
* Use this token to resume the list.
*
* @since 5.3.0
*/
nextPageToken?: string;
}
```
### `UpdateMetadataOptions`
[Section titled âUpdateMetadataOptionsâ](#updatemetadataoptions)
```typescript
export interface UpdateMetadataOptions {
/**
* The full path to the file to update the metadata for, including the file name.
*
* @since 5.3.0
*/
path: string;
/**
* The metadata to update.
*
* @since 5.3.0
*/
metadata: SettableMetadata;
}
```
### `UploadFileOptions`
[Section titled âUploadFileOptionsâ](#uploadfileoptions)
```typescript
export interface UploadFileOptions {
/**
* The data to upload.
*
* Only available for Web.
*
* @since 5.3.0
*/
blob?: Blob;
/**
* The full path where data should be uploaded, including the file name.
*
* @since 5.3.0
* @example 'mountains.png'
* @example 'images/mountains.png'
*/
path: string;
/**
* The uri to the file to upload.
*
* Only available for Android and iOS.
*
* @since 5.3.0
* @example 'content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/1000000214/ORIGINAL/NONE/image/.png/mountains'
* @example 'file:///var/mobile/Containers/Data/Application/E397A70D-67E4-4258-236E-W1D9E12111D4/Library/Caches/092F8464-DE60-40B3-8A23-EB83160D9F9F/mountains.png'
*/
uri?: string;
/**
* The metadata to set for the file.
*
* @since 5.4.0
*/
metadata?: UploadMetadata;
}
```
### `UploadFileCallback`
[Section titled âUploadFileCallbackâ](#uploadfilecallback)
```typescript
export type UploadFileCallback = (event: UploadFileCallbackEvent | null, error: any) => void;
```
### `CallbackId`
[Section titled âCallbackIdâ](#callbackid)
```typescript
export type CallbackId = string;
```
### `UseEmulatorOptions`
[Section titled âUseEmulatorOptionsâ](#useemulatoroptions)
```typescript
export interface UseEmulatorOptions {
/**
* The emulator host without any port or scheme.
*
* Note when using a Android Emulator device: 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer.
*
* @since 6.1.0
* @example "127.0.0.1"
*/
host: string;
/**
* The emulator port.
*
* @since 6.1.0
* @default 9199
* @example 9199
*/
port?: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-flash
> Capacitor Flash Plugin for controlling device flashlight/torch.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Flash Plugin for controlling device flashlight/torch.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isAvailable` - Checks if flashlight is available on the device.
* `switchOn` - Turns the flashlight on.
* `switchOff` - Turns the flashlight off.
* `isSwitchedOn` - Checks if the flashlight is currently turned on or off.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------------------- |
| `isAvailable` | Checks if flashlight is available on the device. |
| `switchOn` | Turns the flashlight on. |
| `switchOff` | Turns the flashlight off. |
| `isSwitchedOn` | Checks if the flashlight is currently turned on or off. |
| `toggle` | Toggle the flashlight on or off. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-flash](https://github.com/Cap-go/capacitor-flash/).
# Getting Started
> Install @capgo/capacitor-flash and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-flash
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Checks if flashlight is available on the device.
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
const { value } = await CapacitorFlash.isAvailable();
if (value) {
console.log('Flashlight is available');
}
```
### `switchOn`
[Section titled âswitchOnâ](#switchon)
Turns the flashlight on.
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
// Turn on at full brightness
await CapacitorFlash.switchOn({ intensity: 1.0 });
// Turn on at half brightness
await CapacitorFlash.switchOn({ intensity: 0.5 });
```
### `switchOff`
[Section titled âswitchOffâ](#switchoff)
Turns the flashlight off.
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
await CapacitorFlash.switchOff();
```
### `isSwitchedOn`
[Section titled âisSwitchedOnâ](#isswitchedon)
Checks if the flashlight is currently turned on or off.
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
const { value } = await CapacitorFlash.isSwitchedOn();
console.log('Flashlight is on:', value);
```
### `toggle`
[Section titled âtoggleâ](#toggle)
Toggle the flashlight on or off.
```typescript
import { CapacitorFlash } from '@capgo/capacitor-flash';
const { value } = await CapacitorFlash.toggle();
console.log('Flashlight toggled, now on:', value);
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-gtm
> The main interface for the Google Tag Manager plugin.
## Overview
[Section titled âOverviewâ](#overview)
The main interface for the Google Tag Manager plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `initialize` - Initializes Google Tag Manager with the specified container ID.
* `push` - Pushes an event to the Google Tag Manager dataLayer.
* `setUserProperty` - Sets a user property in the Google Tag Manager dataLayer.
* `getValue` - Gets a value from the Google Tag Manager dataLayer. Searches through the dataLayer for the most recent value of the specified key.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| `initialize` | Initializes Google Tag Manager with the specified container ID. |
| `push` | Pushes an event to the Google Tag Manager dataLayer. |
| `setUserProperty` | Sets a user property in the Google Tag Manager dataLayer. |
| `getValue` | Gets a value from the Google Tag Manager dataLayer. Searches through the dataLayer for the most recent value of the specified key. |
| `reset` | Resets the Google Tag Manager instance and clears all data. This will remove all data from the dataLayer and require re-initialization. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-gtm](https://github.com/Cap-go/capacitor-gtm/).
# Getting Started
> Install @capgo/capacitor-gtm and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-gtm
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `initialize`
[Section titled âinitializeâ](#initialize)
Initializes Google Tag Manager with the specified container ID.
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
await GoogleTagManager.initialize({} as { containerId: string; timeout?: number });
```
### `push`
[Section titled âpushâ](#push)
Pushes an event to the Google Tag Manager dataLayer.
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
await GoogleTagManager.push({
event: 'purchase',
parameters: {
value: 99.99,
currency: 'USD'
}
});
```
### `setUserProperty`
[Section titled âsetUserPropertyâ](#setuserproperty)
Sets a user property in the Google Tag Manager dataLayer.
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
await GoogleTagManager.setUserProperty({
key: 'user_type',
value: 'premium'
});
```
### `getValue`
[Section titled âgetValueâ](#getvalue)
Gets a value from the Google Tag Manager dataLayer. Searches through the dataLayer for the most recent value of the specified key.
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
await GoogleTagManager.getValue({} as { key: string });
```
### `reset`
[Section titled âresetâ](#reset)
Resets the Google Tag Manager instance and clears all data. This will remove all data from the dataLayer and require re-initialization.
```typescript
import { GoogleTagManager } from '@capgo/capacitor-gtm';
await GoogleTagManager.reset();
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-health
> Capacitor plugin to interact with data from Apple HealthKit and Health Connect.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin to interact with data from Apple HealthKit and Health Connect.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isAvailable` - Returns whether the current platform supports the native health SDK.
* `requestAuthorization` - Requests read/write access to the provided data types.
* `checkAuthorization` - Checks authorization status for the provided data types without prompting the user.
* `readSamples` - Reads samples for the given data type within the specified time frame.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `isAvailable` | Returns whether the current platform supports the native health SDK. |
| `requestAuthorization` | Requests read/write access to the provided data types. |
| `checkAuthorization` | Checks authorization status for the provided data types without prompting the user. |
| `readSamples` | Reads samples for the given data type within the specified time frame. |
| `saveSample` | Writes a single sample to the native health store. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `openHealthConnectSettings` | Opens the Health Connect settings screen (Android only). On iOS, this method does nothing. |
| `showPrivacyPolicy` | Shows the appâs privacy policy for Health Connect (Android only). On iOS, this method does nothing. |
| `queryWorkouts` | Queries workout sessions from the native health store. Supported on iOS (HealthKit) and Android (Health Connect). |
| `queryAggregated` | Queries aggregated health data from the native health store. Aggregates data into time buckets (hour, day, week, month) with operations like sum, average, min, or max. This is more efficient than fetching individual samples for large date ranges. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-health](https://github.com/Cap-go/capacitor-health/).
# Getting Started
> Install @capgo/capacitor-health and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-health
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { Health } from '@capgo/capacitor-health';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Returns whether the current platform supports the native health SDK.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.isAvailable();
```
### `requestAuthorization`
[Section titled ârequestAuthorizationâ](#requestauthorization)
Requests read/write access to the provided data types.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.requestAuthorization({} as AuthorizationOptions);
```
### `checkAuthorization`
[Section titled âcheckAuthorizationâ](#checkauthorization)
Checks authorization status for the provided data types without prompting the user.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.checkAuthorization({} as AuthorizationOptions);
```
### `readSamples`
[Section titled âreadSamplesâ](#readsamples)
Reads samples for the given data type within the specified time frame.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.readSamples({} as QueryOptions);
```
### `saveSample`
[Section titled âsaveSampleâ](#savesample)
Writes a single sample to the native health store.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.saveSample({} as WriteSampleOptions);
```
### `openHealthConnectSettings`
[Section titled âopenHealthConnectSettingsâ](#openhealthconnectsettings)
Opens the Health Connect settings screen (Android only). On iOS, this method does nothing.
Use this to direct users to manage their Health Connect permissions or to install Health Connect if not available.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.openHealthConnectSettings();
```
### `showPrivacyPolicy`
[Section titled âshowPrivacyPolicyâ](#showprivacypolicy)
Shows the appâs privacy policy for Health Connect (Android only). On iOS, this method does nothing.
This displays the same privacy policy screen that Health Connect shows when the user taps âPrivacy policyâ in the permissions dialog.
The privacy policy URL can be configured by adding a string resource named âhealth\_connect\_privacy\_policy\_urlâ in your appâs strings.xml, or by placing an HTML file at www/privacypolicy.html in your assets.
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.showPrivacyPolicy();
```
### `queryWorkouts`
[Section titled âqueryWorkoutsâ](#queryworkouts)
Queries workout sessions from the native health store. Supported on iOS (HealthKit) and Android (Health Connect).
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.queryWorkouts({} as QueryWorkoutsOptions);
```
### `queryAggregated`
[Section titled âqueryAggregatedâ](#queryaggregated)
Queries aggregated health data from the native health store. Aggregates data into time buckets (hour, day, week, month) with operations like sum, average, min, or max. This is more efficient than fetching individual samples for large date ranges.
Supported on iOS (HealthKit) and Android (Health Connect).
```typescript
import { Health } from '@capgo/capacitor-health';
await Health.queryAggregated({} as QueryAggregatedOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AvailabilityResult`
[Section titled âAvailabilityResultâ](#availabilityresult)
```typescript
export interface AvailabilityResult {
available: boolean;
/** Platform specific details (for debugging/diagnostics). */
platform?: 'ios' | 'android' | 'web';
reason?: string;
}
```
### `AuthorizationOptions`
[Section titled âAuthorizationOptionsâ](#authorizationoptions)
```typescript
export interface AuthorizationOptions {
/** Data types that should be readable after authorization. */
read?: HealthDataType[];
/** Data types that should be writable after authorization. */
write?: HealthDataType[];
}
```
### `AuthorizationStatus`
[Section titled âAuthorizationStatusâ](#authorizationstatus)
```typescript
export interface AuthorizationStatus {
readAuthorized: HealthDataType[];
readDenied: HealthDataType[];
writeAuthorized: HealthDataType[];
writeDenied: HealthDataType[];
}
```
### `QueryOptions`
[Section titled âQueryOptionsâ](#queryoptions)
```typescript
export interface QueryOptions {
/** The type of data to retrieve from the health store. */
dataType: HealthDataType;
/** Inclusive ISO 8601 start date (defaults to now - 1 day). */
startDate?: string;
/** Exclusive ISO 8601 end date (defaults to now). */
endDate?: string;
/** Maximum number of samples to return (defaults to 100). */
limit?: number;
/** Return results sorted ascending by start date (defaults to false). */
ascending?: boolean;
}
```
### `ReadSamplesResult`
[Section titled âReadSamplesResultâ](#readsamplesresult)
```typescript
export interface ReadSamplesResult {
samples: HealthSample[];
}
```
### `WriteSampleOptions`
[Section titled âWriteSampleOptionsâ](#writesampleoptions)
```typescript
export interface WriteSampleOptions {
dataType: HealthDataType;
value: number;
/**
* Optional unit override. If omitted, the default unit for the data type is used
* (count for `steps`, meter for `distance`, kilocalorie for `calories`, bpm for `heartRate`, kilogram for `weight`).
*/
unit?: HealthUnit;
/** ISO 8601 start date for the sample. Defaults to now. */
startDate?: string;
/** ISO 8601 end date for the sample. Defaults to startDate. */
endDate?: string;
/** Metadata key-value pairs forwarded to the native APIs where supported. */
metadata?: Record;
/** For blood pressure data, the systolic value in mmHg. Required when dataType is 'bloodPressure'. */
systolic?: number;
/** For blood pressure data, the diastolic value in mmHg. Required when dataType is 'bloodPressure'. */
diastolic?: number;
}
```
### `QueryWorkoutsOptions`
[Section titled âQueryWorkoutsOptionsâ](#queryworkoutsoptions)
```typescript
export interface QueryWorkoutsOptions {
/** Optional workout type filter. If omitted, all workout types are returned. */
workoutType?: WorkoutType;
/** Inclusive ISO 8601 start date (defaults to now - 1 day). */
startDate?: string;
/** Exclusive ISO 8601 end date (defaults to now). */
endDate?: string;
/** Maximum number of workouts to return (defaults to 100). */
limit?: number;
/** Return results sorted ascending by start date (defaults to false). */
ascending?: boolean;
/**
* Anchor for pagination. Use the anchor returned from a previous query to continue from that point.
* On iOS, this is the ISO 8601 cursor returned by the previous query. On Android, this uses
* Health Connect's pageToken.
* Omit this parameter to start from the beginning.
*/
anchor?: string;
}
```
### `QueryWorkoutsResult`
[Section titled âQueryWorkoutsResultâ](#queryworkoutsresult)
```typescript
export interface QueryWorkoutsResult {
workouts: Workout[];
/**
* Anchor for the next page of results. Pass this value as the anchor parameter in the next query
* to continue pagination. If undefined or null, there are no more results.
*/
anchor?: string;
}
```
### `QueryAggregatedOptions`
[Section titled âQueryAggregatedOptionsâ](#queryaggregatedoptions)
```typescript
export interface QueryAggregatedOptions {
/** The type of data to aggregate from the health store. */
dataType: HealthDataType;
/** Inclusive ISO 8601 start date (defaults to now - 1 day). */
startDate?: string;
/** Exclusive ISO 8601 end date (defaults to now). */
endDate?: string;
/** Time bucket for aggregation (defaults to 'day'). */
bucket?: BucketType;
/** Aggregation operation to perform (defaults to 'sum'). */
aggregation?: AggregationType;
}
```
### `QueryAggregatedResult`
[Section titled âQueryAggregatedResultâ](#queryaggregatedresult)
```typescript
export interface QueryAggregatedResult {
samples: AggregatedSample[];
}
```
### `HealthDataType`
[Section titled âHealthDataTypeâ](#healthdatatype)
```typescript
export type HealthDataType =
| 'steps'
| 'distance'
| 'calories'
| 'heartRate'
| 'weight'
| 'sleep'
| 'respiratoryRate'
| 'oxygenSaturation'
| 'restingHeartRate'
| 'heartRateVariability'
| 'bloodPressure'
| 'bloodGlucose'
| 'bodyTemperature'
| 'height'
| 'flightsClimbed'
| 'exerciseTime'
| 'distanceCycling'
| 'bodyFat'
| 'basalBodyTemperature'
| 'basalCalories'
| 'totalCalories'
| 'mindfulness'
| 'workouts';
```
### `HealthSample`
[Section titled âHealthSampleâ](#healthsample)
```typescript
export interface HealthSample {
dataType: HealthDataType;
value: number;
unit: HealthUnit;
startDate: string;
endDate: string;
sourceName?: string;
sourceId?: string;
/** Platform-specific unique identifier (HealthKit UUID on iOS, Health Connect metadata ID on Android). */
platformId?: string;
/** For sleep data, indicates the sleep state (e.g., 'asleep', 'awake', 'rem', 'deep', 'light'). */
sleepState?: SleepState;
/** For blood pressure data, the systolic value in mmHg. */
systolic?: number;
/** For blood pressure data, the diastolic value in mmHg. */
diastolic?: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-home-indicator
> Capacitor Home Indicator Plugin for controlling the iOS home indicator visibility. The home indicator is the horizontal bar at the bottom of iOS devices without a physical home button.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Home Indicator Plugin for controlling the iOS home indicator visibility. The home indicator is the horizontal bar at the bottom of iOS devices without a physical home button.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `hide` - Hide the home indicator at the bottom of the screen.
* `show` - Show the home indicator at the bottom of the screen.
* `isHidden` - Check whether the home indicator is currently hidden.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ----------------------------------------------------- |
| `hide` | Hide the home indicator at the bottom of the screen. |
| `show` | Show the home indicator at the bottom of the screen. |
| `isHidden` | Check whether the home indicator is currently hidden. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-home-indicator](https://github.com/Cap-go/capacitor-home-indicator/).
# Getting Started
> Install @capgo/capacitor-home-indicator and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-home-indicator
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { HomeIndicator } from '@capgo/capacitor-home-indicator';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `hide`
[Section titled âhideâ](#hide)
Hide the home indicator at the bottom of the screen.
This visually hides the iOS home indicator bar, providing a more immersive full-screen experience. Users can still swipe up to access home, but the indicator will not be visible until they start the gesture.
iOS only. Has no effect on Android or web.
```typescript
import { HomeIndicator } from '@capgo/capacitor-home-indicator';
await HomeIndicator.hide();
```
### `show`
[Section titled âshowâ](#show)
Show the home indicator at the bottom of the screen.
This restores the default iOS home indicator visibility, making it always visible to the user. This is the default behavior.
iOS only. Has no effect on Android or web.
```typescript
import { HomeIndicator } from '@capgo/capacitor-home-indicator';
await HomeIndicator.show();
```
### `isHidden`
[Section titled âisHiddenâ](#ishidden)
Check whether the home indicator is currently hidden.
Returns the current visibility state of the iOS home indicator.
```typescript
import { HomeIndicator } from '@capgo/capacitor-home-indicator';
const { hidden } = await HomeIndicator.isHidden();
if (hidden) {
console.log('Home indicator is hidden');
} else {
console.log('Home indicator is visible');
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-ibeacon
> Capacitor iBeacon Plugin - Proximity detection and beacon region monitoring.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor iBeacon Plugin - Proximity detection and beacon region monitoring.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startMonitoringForRegion` - Start monitoring for a beacon region. Triggers events when entering/exiting the region.
* `stopMonitoringForRegion` - Stop monitoring for a beacon region.
* `startRangingBeaconsInRegion` - Start ranging beacons in a region. Provides continuous distance updates.
* `stopRangingBeaconsInRegion` - Stop ranging beacons in a region.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `startMonitoringForRegion` | Start monitoring for a beacon region. Triggers events when entering/exiting the region. |
| `stopMonitoringForRegion` | Stop monitoring for a beacon region. |
| `startRangingBeaconsInRegion` | Start ranging beacons in a region. Provides continuous distance updates. |
| `stopRangingBeaconsInRegion` | Stop ranging beacons in a region. |
| `startAdvertising` | Start advertising the device as an iBeacon (iOS only). |
| `stopAdvertising` | Stop advertising the device as an iBeacon (iOS only). |
| `requestWhenInUseAuthorization` | Request âWhen In Useâ location authorization (required for ranging/monitoring). |
| `requestAlwaysAuthorization` | Request âAlwaysâ location authorization (required for background monitoring). |
| `getAuthorizationStatus` | Get current location authorization status. |
| `isBluetoothEnabled` | Check if Bluetooth is enabled on the device. |
| `isRangingAvailable` | Check if ranging is available on the device. |
| `enableARMAFilter` | Enable ARMA filtering for distance calculations (Android only). |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `enableBackgroundMode` | Enable or disable background beacon scanning mode (Android only). This enables a foreground service for reliable background beacon detection. Must be called after requesting âAlwaysâ location authorization. |
| `setBackgroundScanPeriod` | Configure background scan periods (Android only). Controls how often and how long the device scans for beacons when in background. |
| `addListener` | Listen for beacon ranging events. |
| `addListener` | Listen for region enter events. |
| `addListener` | Listen for region exit events. |
| `addListener` | Listen for region state determination events. |
| `addListener` | Listen for monitoring failure events. |
| `removeAllListeners` | Remove all listeners for this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-ibeacon](https://github.com/Cap-go/capacitor-ibeacon/).
# Getting Started
> Install @capgo/capacitor-ibeacon and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-ibeacon
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `startMonitoringForRegion`
[Section titled âstartMonitoringForRegionâ](#startmonitoringforregion)
Start monitoring for a beacon region. Triggers events when entering/exiting the region.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.startMonitoringForRegion({
identifier: 'MyBeaconRegion',
uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
});
```
### `stopMonitoringForRegion`
[Section titled âstopMonitoringForRegionâ](#stopmonitoringforregion)
Stop monitoring for a beacon region.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.stopMonitoringForRegion({
identifier: 'MyBeaconRegion',
uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
});
```
### `startRangingBeaconsInRegion`
[Section titled âstartRangingBeaconsInRegionâ](#startrangingbeaconsinregion)
Start ranging beacons in a region. Provides continuous distance updates.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.startRangingBeaconsInRegion({
identifier: 'MyBeaconRegion',
uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
});
```
### `stopRangingBeaconsInRegion`
[Section titled âstopRangingBeaconsInRegionâ](#stoprangingbeaconsinregion)
Stop ranging beacons in a region.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.stopRangingBeaconsInRegion({
identifier: 'MyBeaconRegion',
uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
});
```
### `startAdvertising`
[Section titled âstartAdvertisingâ](#startadvertising)
Start advertising the device as an iBeacon (iOS only).
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.startAdvertising({
uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
major: 1,
minor: 2,
identifier: 'MyBeacon'
});
```
### `stopAdvertising`
[Section titled âstopAdvertisingâ](#stopadvertising)
Stop advertising the device as an iBeacon (iOS only).
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.stopAdvertising();
```
### `requestWhenInUseAuthorization`
[Section titled ârequestWhenInUseAuthorizationâ](#requestwheninuseauthorization)
Request âWhen In Useâ location authorization (required for ranging/monitoring).
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
const { status } = await CapacitorIbeacon.requestWhenInUseAuthorization();
console.log('Authorization status:', status);
```
### `requestAlwaysAuthorization`
[Section titled ârequestAlwaysAuthorizationâ](#requestalwaysauthorization)
Request âAlwaysâ location authorization (required for background monitoring).
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
const { status } = await CapacitorIbeacon.requestAlwaysAuthorization();
console.log('Authorization status:', status);
```
### `getAuthorizationStatus`
[Section titled âgetAuthorizationStatusâ](#getauthorizationstatus)
Get current location authorization status.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
const { status } = await CapacitorIbeacon.getAuthorizationStatus();
console.log('Current status:', status);
```
### `isBluetoothEnabled`
[Section titled âisBluetoothEnabledâ](#isbluetoothenabled)
Check if Bluetooth is enabled on the device.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
const { enabled } = await CapacitorIbeacon.isBluetoothEnabled();
if (!enabled) {
console.log('Please enable Bluetooth');
}
```
### `isRangingAvailable`
[Section titled âisRangingAvailableâ](#israngingavailable)
Check if ranging is available on the device.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
const { available } = await CapacitorIbeacon.isRangingAvailable();
if (available) {
console.log('Ranging is supported');
}
```
### `enableARMAFilter`
[Section titled âenableARMAFilterâ](#enablearmafilter)
Enable ARMA filtering for distance calculations (Android only).
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
await CapacitorIbeacon.enableARMAFilter({
enabled: true
});
```
### `enableBackgroundMode`
[Section titled âenableBackgroundModeâ](#enablebackgroundmode)
Enable or disable background beacon scanning mode (Android only). This enables a foreground service for reliable background beacon detection. Must be called after requesting âAlwaysâ location authorization.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
// Enable background mode for beacon scanning
await CapacitorIbeacon.enableBackgroundMode({ enabled: true });
// Disable background mode
await CapacitorIbeacon.enableBackgroundMode({ enabled: false });
```
### `setBackgroundScanPeriod`
[Section titled âsetBackgroundScanPeriodâ](#setbackgroundscanperiod)
Configure background scan periods (Android only). Controls how often and how long the device scans for beacons when in background.
```typescript
import { CapacitorIbeacon } from '@capgo/capacitor-ibeacon';
// Set background scan to 10 seconds every 30 seconds
await CapacitorIbeacon.setBackgroundScanPeriod({
scanPeriod: 10000, // 10 seconds of scanning
betweenScanPeriod: 30000 // 30 seconds between scans
});
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `BeaconRegion`
[Section titled âBeaconRegionâ](#beaconregion)
Beacon region definition for monitoring and ranging.
```typescript
export interface BeaconRegion {
/**
* Unique identifier for this region.
*/
identifier: string;
/**
* UUID of the beacon(s) to detect.
*/
uuid: string;
/**
* Major value for filtering (optional).
*/
major?: number;
/**
* Minor value for filtering (optional).
*/
minor?: number;
/**
* Notify when device enters region (iOS only).
*/
notifyEntryStateOnDisplay?: boolean;
/**
* Enable Android background mode for this monitoring/ranging call.
* When true, the plugin will keep scanning in background using a foreground service.
*/
enableBackgroundMode?: boolean;
}
```
### `BeaconAdvertisingOptions`
[Section titled âBeaconAdvertisingOptionsâ](#beaconadvertisingoptions)
Beacon advertising options for transmitting as an iBeacon (iOS only).
```typescript
export interface BeaconAdvertisingOptions {
/**
* UUID to advertise.
*/
uuid: string;
/**
* Major value (0-65535).
*/
major: number;
/**
* Minor value (0-65535).
*/
minor: number;
/**
* Identifier for the advertising beacon.
*/
identifier: string;
/**
* Measured power (RSSI at 1 meter). Optional, defaults to -59.
*/
measuredPower?: number;
}
```
### `BackgroundScanPeriodOptions`
[Section titled âBackgroundScanPeriodOptionsâ](#backgroundscanperiodoptions)
Background scan period configuration options (Android only).
```typescript
export interface BackgroundScanPeriodOptions {
/**
* Duration of each scan period in milliseconds.
* Default: 10000 (10 seconds)
*/
scanPeriod?: number;
/**
* Duration between scan periods in milliseconds.
* Default: 15000 (15 seconds)
*/
betweenScanPeriod?: number;
}
```
### `RangingEventData`
[Section titled âRangingEventDataâ](#rangingeventdata)
Event data when beacons are ranged.
```typescript
export interface RangingEventData {
/**
* Region that was ranged.
*/
region: BeaconRegion;
/**
* Array of detected beacons.
*/
beacons: Beacon[];
}
```
### `MonitoringEventData`
[Section titled âMonitoringEventDataâ](#monitoringeventdata)
Event data when entering or exiting a region.
```typescript
export interface MonitoringEventData {
/**
* Region that triggered the event.
*/
region: BeaconRegion;
/**
* Event state: 'enter' or 'exit'.
*/
state: 'enter' | 'exit';
}
```
### `Beacon`
[Section titled âBeaconâ](#beacon)
Detected beacon information.
```typescript
export interface Beacon {
/**
* Beacon UUID.
*/
uuid: string;
/**
* Major value.
*/
major: number;
/**
* Minor value.
*/
minor: number;
/**
* RSSI (Received Signal Strength Indicator).
*/
rssi: number;
/**
* Proximity: 'immediate', 'near', 'far', or 'unknown'.
*/
proximity: 'immediate' | 'near' | 'far' | 'unknown';
/**
* Estimated distance in meters.
*/
accuracy: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-in-app-review
> Capacitor In-App Review Plugin interface for prompting users to submit app store ratings and reviews without leaving the app.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor In-App Review Plugin interface for prompting users to submit app store ratings and reviews without leaving the app.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `requestReview` - Request an in-app review from the user.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ---------------------------------------- |
| `requestReview` | Request an in-app review from the user. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-in-app-review](https://github.com/Cap-go/capacitor-in-app-review/).
# Getting Started
> Install @capgo/capacitor-in-app-review and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-in-app-review
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoInAppReview } from '@capgo/capacitor-in-app-review';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `requestReview`
[Section titled ârequestReviewâ](#requestreview)
Request an in-app review from the user.
This method triggers the native in-app review dialog provided by the platform. On iOS, it uses SKStoreReviewController. On Android, it uses the Play In-App Review API.
**Important Notes:**
* The review dialog may not be displayed every time this method is called. Both Apple and Google have guidelines that limit how often the prompt can appear.
* There is no guarantee that the user will see the review prompt.
* The method resolves successfully even if the dialog was not shown.
* Do not call this in response to a user action like a button tap. Instead, call it at natural points in your appâs user flow.
```typescript
import { CapgoInAppReview } from '@capgo/capacitor-in-app-review';
// Request a review at an appropriate moment in your app
await CapgoInAppReview.requestReview();
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/inappbrowser
> Capacitor plugin in app browser.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin in app browser.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `goBack` - Navigates back in the WebViewâs history if possible.
* `open` - Open url in a new window fullscreen, on android it use chrome custom tabs, on ios it use SFSafariViewController.
* `clearCookies` - Clear cookies of url When `id` is omitted, applies to all open webviews.
* `clearAllCookies` - Clear all cookies When `id` is omitted, applies to all open webviews.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `goBack` | Navigates back in the WebViewâs history if possible. |
| `open` | Open url in a new window fullscreen, on android it use chrome custom tabs, on ios it use SFSafariViewController. |
| `clearCookies` | Clear cookies of url When `id` is omitted, applies to all open webviews. |
| `clearAllCookies` | Clear all cookies When `id` is omitted, applies to all open webviews. |
| `clearCache` | Clear cache When `id` is omitted, applies to all open webviews. |
| `getCookies` | Get cookies for a specific URL. |
| `close` | Close the webview. When `id` is omitted, closes the active webview. |
| `hide` | Hide the webview without closing it. Use show() to bring it back. When `id` is omitted, targets the active webview. |
| `show` | Show a previously hidden webview. When `id` is omitted, targets the active webview. |
| `openWebView` | Open url in a new webview with toolbars, and enhanced capabilities, like camera access, file access, listen events, inject javascript, bi directional communication, etc. |
| `executeScript` | Injects JavaScript code into the InAppBrowser window. When `id` is omitted, executes in all open webviews. |
| `postMessage` | Sends an event to the webview (in-app browser). Listen in the page with `window.addEventListener('messageFromNative', listenerFunc)`. The `detail` payload must be JSON-serializable. When `id` is omitted, broadcasts to all open webviews. |
| `takeScreenshot` | Captures the current webview viewport as a PNG screenshot. When `id` is omitted, targets the active webview. |
| `setUrl` | Sets the URL of the webview. When `id` is omitted, targets the active webview. |
| `addListener` | Listen for url change, only for openWebView. |
| `addListener` | See the source definitions for current behavior. |
| `addListener` | Listen for close click only for openWebView. |
| `addListener` | Will be triggered when user clicks on confirm button when disclaimer is required, works with openWebView shareDisclaimer and closeModal. |
| `addListener` | Fires when the webview sends an event back to the app. Use `window.mobileApp.postMessage(...)` in the page, and keep the payload JSON-serializable. |
| `addListener` | Will be triggered whenever a screenshot is captured from the plugin API, the native screenshot button, or the injected JavaScript bridge. |
| `addListener` | Will be triggered when page is loaded. |
| `addListener` | Will be triggered when page load error. |
| `addListener` | Will be triggered after native download handling saves a file locally. Enable this with `handleDownloads: true` when opening the webview. |
| `addListener` | Will be triggered when native download handling fails. Enable this with `handleDownloads: true` when opening the webview. |
| `addListener` | Will be triggered whenever a page opens a popup/new window. Use the returned popup id with `executeScript`, `postMessage`, `show`, `hide`, and `close`. |
| `addListener` | Listen for proxied requests delegated by the native runtime. Prefer `addProxyHandler()` instead of calling this directly. |
| `addListener` | Listen for JavaScript console output emitted by the managed page. Enable this with `captureConsoleLogs: true` when opening the webview. |
| `handleProxyRequest` | Internal method used by `addProxyHandler()` to send a proxy decision back to native. Forward the original `phase` when replying to a manual `proxyRequest` listener. |
| `removeAllListeners` | Remove all listeners for this plugin. |
| `reload` | Reload the current web page. |
| `updateDimensions` | Update the dimensions of the webview. Allows changing the size and position of the webview at runtime. When `id` is omitted, targets the active webview. |
| `setEnabledSafeTopMargin` | Sets the enabled safe top margin of the webview at runtime. When `id` is omitted, targets the active webview. On Web, this method is a no-op and resolves without changing layout. |
| `setEnabledSafeBottomMargin` | Sets the enabled safe bottom margin of the webview at runtime. When `id` is omitted, targets the active webview. On Web, this method is a no-op and resolves without changing layout. |
| `openSecureWindow` | Opens a secure OAuth2 window. On web, return the redirected URL through a `BroadcastChannel`; on mobile, register a custom redirect URI in your app configuration. See the getting-started guide for the full HTML, Info.plist, and AndroidManifest examples. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-inappbrowser](https://github.com/Cap-go/capacitor-inappbrowser/).
# Getting Started
> Install @capgo/inappbrowser and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/inappbrowser
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `goBack`
[Section titled âgoBackâ](#goback)
Navigates back in the WebViewâs history if possible
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.goBack();
```
### `open`
[Section titled âopenâ](#open)
Open url in a new window fullscreen, on android it use chrome custom tabs, on ios it use SFSafariViewController
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.open({} as OpenOptions);
```
### `clearCookies`
[Section titled âclearCookiesâ](#clearcookies)
Clear cookies of url When `id` is omitted, applies to all open webviews.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.clearCookies({} as ClearCookieOptions);
```
### `clearAllCookies`
[Section titled âclearAllCookiesâ](#clearallcookies)
Clear all cookies When `id` is omitted, applies to all open webviews.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.clearAllCookies();
```
### `clearCache`
[Section titled âclearCacheâ](#clearcache)
Clear cache When `id` is omitted, applies to all open webviews.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.clearCache();
```
### `getCookies`
[Section titled âgetCookiesâ](#getcookies)
Get cookies for a specific URL.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.getCookies({} as GetCookieOptions);
```
### `close`
[Section titled âcloseâ](#close)
Close the webview. When `id` is omitted, closes the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.close();
```
### `hide`
[Section titled âhideâ](#hide)
Hide the webview without closing it. Use show() to bring it back. When `id` is omitted, targets the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.hide();
```
### `show`
[Section titled âshowâ](#show)
Show a previously hidden webview. When `id` is omitted, targets the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.show();
```
### `openWebView`
[Section titled âopenWebViewâ](#openwebview)
Open url in a new webview with toolbars, and enhanced capabilities, like camera access, file access, listen events, inject javascript, bi directional communication, etc.
JavaScript Interface: When you open a webview with this method, a JavaScript interface is automatically injected that provides:
* `window.mobileApp.close()`: Closes the webview from JavaScript
* `window.mobileApp.postMessage({detail: {message: "myMessage"}})`: Sends a message from the webview to the app, detail object is the data you want to send to the webview
* `window.mobileApp.takeScreenshot()` when `allowScreenshotsFromWebPage` is true
Promise timing differs by platform when `isPresentAfterPageLoad` is used. Android resolves with `{ id }` after the dialog is ready to control, while iOS resolves with `{ id }` immediately after creating the native webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.openWebView({} as OpenWebViewOptions);
```
### `executeScript`
[Section titled âexecuteScriptâ](#executescript)
Injects JavaScript code into the InAppBrowser window. When `id` is omitted, executes in all open webviews.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.executeScript({} as { code: string; id?: string });
```
### `postMessage`
[Section titled âpostMessageâ](#postmessage)
Sends an event to the webview (in-app browser). In the webview JavaScript, listen for it with `window.addEventListener('messageFromNative', listenerFunc)`. `detail` is the payload sent to the webview. Because it crosses the Capacitor bridge, it must be JSON-serializable. When `id` is omitted, broadcasts to all open webviews.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.postMessage({} as { detail: Record; id?: string });
```
### `takeScreenshot`
[Section titled âtakeScreenshotâ](#takescreenshot)
Captures the current webview viewport as a PNG screenshot. When `id` is omitted, targets the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.takeScreenshot();
```
### `setUrl`
[Section titled âsetUrlâ](#seturl)
Sets the URL of the webview. When `id` is omitted, targets the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.setUrl({} as { url: string; id?: string });
```
### `handleProxyRequest`
[Section titled âhandleProxyRequestâ](#handleproxyrequest)
Internal method used by `addProxyHandler()` to send a proxy decision back to native. Forward the original `phase` when replying to a manual `proxyRequest` listener.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.handleProxyRequest({} as {
requestId: string;
decision?: ProxyDecision | null;
response?: ProxyResponse | null;
webviewId?: string;
phase?: 'outbound' | 'inbound';
});
```
### `reload`
[Section titled âreloadâ](#reload)
Reload the current web page.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.reload();
```
### `updateDimensions`
[Section titled âupdateDimensionsâ](#updatedimensions)
Update the dimensions of the webview. Allows changing the size and position of the webview at runtime. When `id` is omitted, targets the active webview.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.updateDimensions({} as DimensionOptions & { id?: string });
```
### `setEnabledSafeTopMargin`
[Section titled âsetEnabledSafeTopMarginâ](#setenabledsafetopmargin)
Sets the enabled safe top margin of the webview at runtime. When `id` is omitted, targets the active webview. On Web, this method is a no-op and resolves without changing layout.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.setEnabledSafeTopMargin({} as { enabled: boolean; id?: string });
```
### `setEnabledSafeBottomMargin`
[Section titled âsetEnabledSafeBottomMarginâ](#setenabledsafebottommargin)
Sets the enabled safe bottom margin of the webview at runtime. When `id` is omitted, targets the active webview. On Web, this method is a no-op and resolves without changing layout.
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.setEnabledSafeBottomMargin({} as { enabled: boolean; id?: string });
```
### `openSecureWindow`
[Section titled âopenSecureWindowâ](#opensecurewindow)
Opens a secured window for OAuth2 authentication. For web, you should have the code in the redirected page to use a broadcast channel to send the redirected url to the app Something like:
```html
```
For mobile, you should have a redirect uri that opens the app, something like: `myapp://oauth_callback/` And make sure to register it in the appâs info.plist:
```xml
CFBundleURLTypesCFBundleURLSchemesmyapp
```
And in the AndroidManifest.xml file:
```xml
```
```typescript
import { InAppBrowser } from '@capgo/inappbrowser';
await InAppBrowser.openSecureWindow({} as OpenSecureWindowOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `OpenOptions`
[Section titled âOpenOptionsâ](#openoptions)
```typescript
export interface OpenOptions {
/**
* Target URL to load.
* @since 0.1.0
*/
url: string;
/**
* if true, the browser will be presented after the page is loaded, if false, the browser will be presented immediately.
* @since 0.1.0
*/
isPresentAfterPageLoad?: boolean;
/**
* if true the deeplink will not be opened, if false the deeplink will be opened when clicked on the link
* @since 0.1.0
*/
preventDeeplink?: boolean;
// --- Chrome Custom Tab customization (Android only, ignored on iOS) ---
/**
* Toolbar background color in hex format (e.g., "#1A1A2E").
* Applied to both light and dark color schemes.
* Also sets the navigation bar color to match.
* **Android only** â ignored on iOS.
* @since 8.2.0
*/
toolbarColor?: string;
/**
* Whether the URL bar should auto-hide when the user scrolls down.
* The bar reappears on any upward scroll.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
urlBarHidingEnabled?: boolean;
/**
* Show the page's HTML in the toolbar instead of the raw URL.
* The true URL is still visible when the user taps the title area.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
showTitle?: boolean;
/**
* Replace the default "X" close icon with a back arrow.
* Makes the Custom Tab feel like a native navigation push rather than a modal overlay.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
showArrow?: boolean;
/**
* Remove the share action from the overflow menu.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
disableShare?: boolean;
/**
* Hide the bookmark star icon in the overflow menu.
* Uses an undocumented Chromium intent extra â may stop working on future Chrome updates.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
disableBookmark?: boolean;
/**
* Hide the download icon in the overflow menu.
* Uses an undocumented Chromium intent extra â may stop working on future Chrome updates.
* **Android only** â ignored on iOS.
* @default false
* @since 8.2.0
*/
disableDownload?: boolean;
}
```
### `ClearCookieOptions`
[Section titled âClearCookieOptionsâ](#clearcookieoptions)
```typescript
export interface ClearCookieOptions {
/**
* Target webview id.
* When omitted, applies to all open webviews.
*/
id?: string;
url: string;
}
```
### `GetCookieOptions`
[Section titled âGetCookieOptionsâ](#getcookieoptions)
```typescript
export interface GetCookieOptions {
url: string;
includeHttpOnly?: boolean;
}
```
### `CloseWebviewOptions`
[Section titled âCloseWebviewOptionsâ](#closewebviewoptions)
```typescript
export interface CloseWebviewOptions {
/**
* Target webview id to close. If omitted, closes the active webview.
*/
id?: string;
/**
* Whether the webview closing is animated or not, ios only
* @default true
*/
isAnimated?: boolean;
}
```
### `OpenWebViewOptions`
[Section titled âOpenWebViewOptionsâ](#openwebviewoptions)
````typescript
export interface OpenWebViewOptions {
/**
* Target URL to load.
* @since 0.1.0
* @example "https://capgo.app"
*/
url: string;
/**
* Headers to send with the request.
* @since 0.1.0
* @example
* headers: {
* "Custom-Header": "test-value",
* "Authorization": "Bearer test-token"
* }
* Test URL: https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending/
*/
headers?: Headers;
/**
* Credentials to send with the request and all subsequent requests for the same host.
* @since 6.1.0
* @example
* credentials: {
* username: "test-user",
* password: "test-pass"
* }
* Test URL: https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending/
*/
credentials?: Credentials;
/**
* HTTP method to use for the initial request.
*
* **Optional parameter - defaults to GET if not specified.**
* Existing code that doesn't provide this parameter will continue to work unchanged with standard GET requests.
*
* When specified with 'POST', 'PUT', or 'PATCH' methods that support a body,
* you can also provide a `body` parameter with the request payload.
*
* **Platform Notes:**
* - iOS: Full support for all HTTP methods with headers
* - Android: Custom headers may not be sent with POST/PUT/PATCH requests due to WebView limitations
*
* @since 8.2.0
* @default "GET"
* @example
* method: "POST",
* body: JSON.stringify({ token: "auth-token", data: "value" }),
* headers: { "Content-Type": "application/json" }
*/
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | string;
/**
* HTTP body to send with the request when using POST, PUT, or other methods that support a body.
* Should be a string (use JSON.stringify for JSON data).
*
* **Optional parameter - only used when `method` is specified and supports a request body.**
* Omitting this parameter (or using GET method) results in standard behavior without a request body.
*
* @since 8.2.0
* @example
* method: "POST",
* body: JSON.stringify({ username: "user", password: "pass" }),
* headers: { "Content-Type": "application/json" }
*/
body?: string;
/**
* materialPicker: if true, uses Material Design theme for date and time pickers on Android.
* This improves the appearance of HTML date inputs to use modern Material Design UI instead of the old style pickers.
* @since 7.4.1
* @default false
* @example
* materialPicker: true
* Test URL: https://show-picker.glitch.me/demo.html
*/
materialPicker?: boolean;
/**
* JavaScript Interface:
* The webview automatically injects a JavaScript interface providing:
* - `window.mobileApp.close()`: Closes the webview from JavaScript
* - `window.mobileApp.postMessage(obj)`: Sends a message to the app (listen via "messageFromWebview" event)
* - `window.mobileApp.hide()` / `window.mobileApp.show()` when allowWebViewJsVisibilityControl is true in CapacitorConfig
* - `window.mobileApp.takeScreenshot()` when `allowScreenshotsFromWebPage` is true
*
* @example
* // In your webpage loaded in the webview:
* document.getElementById("closeBtn").addEventListener("click", () => {
* window.mobileApp.close();
* });
*
* // Send data to the app
* window.mobileApp.postMessage({ action: "login", data: { user: "test" }});
*
* @since 6.10.0
*/
jsInterface?: never; // This property doesn't exist, it's just for documentation
/**
* Allows page JavaScript to call `window.mobileApp.takeScreenshot()`.
* Disabled by default so only the host app can trigger native screenshots through the plugin API.
*
* @default false
* @since 8.4.0
*/
allowScreenshotsFromWebPage?: boolean;
/**
* Emits `consoleMessage` events for JavaScript `console.*` output coming from the managed page.
* Useful when the webview stays hidden and you still need page-level diagnostics.
*
* @default false
* @since 8.6.0
*/
captureConsoleLogs?: boolean;
/**
* Automatically handles downloads triggered inside the webview without requiring a custom JavaScript bridge.
*
* When enabled:
* - Standard attachment responses are written to a temporary file.
* - `blob:` downloads are also captured when the platform supports them.
* - Previewable files reopen inside the in-app browser when possible.
* - Other files are handed off to the native preview or viewer flow.
* - `downloadCompleted` and `downloadFailed` events notify the host app about the saved file.
*
* @default false
* @since 8.6.0
*/
handleDownloads?: boolean;
/**
* Share options for the webview. When provided, shows a disclaimer dialog before sharing content.
* This is useful for:
* - Warning users about sharing sensitive information
* - Getting user consent before sharing
* - Explaining what will be shared
* - Complying with privacy regulations
*
* Note: shareSubject is required when using shareDisclaimer
* @since 0.1.0
* @example
* shareDisclaimer: {
* title: "Disclaimer",
* message: "This is a test disclaimer",
* confirmBtn: "Accept",
* cancelBtn: "Decline"
* }
* Test URL: https://capgo.app
*/
shareDisclaimer?: DisclaimerOptions;
/**
* Toolbar type determines the appearance and behavior of the browser's toolbar
* - "activity": Shows a simple toolbar with just a close button and share button
* - "navigation": Shows a full navigation toolbar with back/forward buttons
* - "blank": Shows no toolbar
* - "": Default toolbar with close button
* @since 0.1.0
* @default ToolBarType.DEFAULT
* @example
* toolbarType: ToolBarType.ACTIVITY,
* title: "Activity Toolbar Test"
* Test URL: https://capgo.app
*/
toolbarType?: ToolBarType;
/**
* Subject text for sharing. Required when using shareDisclaimer.
* This text will be used as the subject line when sharing content.
* @since 0.1.0
* @example "Share this page"
*/
shareSubject?: string;
/**
* Title of the browser
* @since 0.1.0
* @default "New Window"
* @example "Camera Test"
*/
title?: string;
/**
* Background color of the browser
* @since 0.1.0
* @default BackgroundColor.BLACK
*/
backgroundColor?: BackgroundColor;
/**
* If true, enables native navigation gestures within the webview.
* - Android: Native back button navigates within webview history
* - iOS: Enables swipe left/right gestures for back/forward navigation
* @default false (Android), true (iOS - enabled by default)
* @example
* activeNativeNavigationForWebview: true,
* disableGoBackOnNativeApplication: true
* Test URL: https://capgo.app
*/
activeNativeNavigationForWebview?: boolean;
/**
* Disable the possibility to go back on native application,
* useful to force user to stay on the webview, Android only
* @default false
* @example
* disableGoBackOnNativeApplication: true
* Test URL: https://capgo.app
*/
disableGoBackOnNativeApplication?: boolean;
/**
* Open url in a new window fullscreen
* isPresentAfterPageLoad: if true, the browser will be presented after the page is loaded, if false, the browser will be presented immediately.
* Promise timing: on Android, `openWebView()` resolves with the webview id when the webview is ready to be controlled
* (immediately for hidden/immediate presentation, after the first page load when `isPresentAfterPageLoad` is `true`).
* On iOS, the promise resolves with the id as soon as the native webview is created, even if presentation is deferred.
* @since 0.1.0
* @default false
* @example
* isPresentAfterPageLoad: true,
* preShowScript: "await import('https://unpkg.com/darkreader@4.9.89/darkreader.js');\nDarkReader.enable({ brightness: 100, contrast: 90, sepia: 10 });"
* Test URL: https://capgo.app
*/
isPresentAfterPageLoad?: boolean;
/**
* Whether the website in the webview is inspectable or not, ios only
* @default false
*/
isInspectable?: boolean;
/**
* Whether the webview opening is animated or not, ios only
* @default true
*/
isAnimated?: boolean;
/**
* Shows a reload button that reloads the web page
* @since 1.0.15
* @default false
* @example
* showReloadButton: true
* Test URL: https://capgo.app
*/
showReloadButton?: boolean;
/**
* CloseModal: if true a confirm will be displayed when user clicks on close button, if false the browser will be closed immediately.
* @since 1.1.0
* @default false
* @example
* closeModal: true,
* closeModalTitle: "Close Window",
* closeModalDescription: "Are you sure you want to close?",
* closeModalOk: "Yes, close",
* closeModalCancel: "No, stay"
* Test URL: https://capgo.app
*/
closeModal?: boolean;
/**
* CloseModalTitle: title of the confirm when user clicks on close button
* @since 1.1.0
* @default "Close"
*/
closeModalTitle?: string;
/**
* CloseModalDescription: description of the confirm when user clicks on close button
* @since 1.1.0
* @default "Are you sure you want to close this window?"
*/
closeModalDescription?: string;
/**
* CloseModalOk: text of the confirm button when user clicks on close button
* @since 1.1.0
* @default "Close"
*/
closeModalOk?: string;
/**
* CloseModalCancel: text of the cancel button when user clicks on close button
* @since 1.1.0
* @default "Cancel"
*/
closeModalCancel?: string;
/**
* closeModalURLPattern: a regex pattern to match against the current URL when the close button is pressed.
* When provided along with closeModal: true, the close confirmation modal is only shown if the current URL matches this pattern.
* If the current URL does not match, the browser closes immediately without showing the modal.
* Requires closeModal to be true.
* @since 7.2.0
* @example
* closeModal: true,
* closeModalURLPattern: ".*checkout.*"
*/
closeModalURLPattern?: string;
/**
* visibleTitle: if true the website title would be shown else shown empty
* @since 1.2.5
* @default true
*/
visibleTitle?: boolean;
/**
* toolbarColor: color of the toolbar in hex format
* @since 1.2.5
* @default "#ffffff"
* @example
* toolbarColor: "#FF5733"
* Test URL: https://capgo.app
*/
toolbarColor?: string;
/**
* toolbarTextColor: color of the buttons and title in the toolbar in hex format
* When set, it overrides the automatic light/dark mode detection for text color
* @since 6.10.0
* @default calculated based on toolbarColor brightness
* @example
* toolbarTextColor: "#FFFFFF"
* Test URL: https://capgo.app
*/
toolbarTextColor?: string;
/**
* showArrow: if true an arrow would be shown instead of cross for closing the window
* @since 1.2.5
* @default false
* @example
* showArrow: true
* Test URL: https://capgo.app
*/
showArrow?: boolean;
/**
* ignoreUntrustedSSLError: if true, the webview will ignore untrusted SSL errors allowing the user to view the website.
* @since 6.1.0
* @default false
*/
ignoreUntrustedSSLError?: boolean;
/**
* preShowScript: if isPresentAfterPageLoad is true and this variable is set the plugin will inject a script before showing the browser.
* This script will be run in an async context. The plugin will wait for the script to finish (max 10 seconds)
* @since 6.6.0
* @example
* preShowScript: "await import('https://unpkg.com/darkreader@4.9.89/darkreader.js');\nDarkReader.enable({ brightness: 100, contrast: 90, sepia: 10 });"
* Test URL: https://capgo.app
*/
preShowScript?: string;
/**
* preShowScriptInjectionTime: controls when the preShowScript is injected.
* - "documentStart": injects before any page JavaScript runs (good for polyfills like Firebase)
* - "pageLoad": injects after page load (default, original behavior)
* @since 7.26.0
* @default "pageLoad"
* @example
* preShowScriptInjectionTime: "documentStart"
*/
preShowScriptInjectionTime?: 'documentStart' | 'pageLoad';
/**
* Proxy interception mode.
*
* - `true`: legacy blanket mode, delegates all HTTP/HTTPS requests to JavaScript.
* - `string`: Android-only regex mode kept for backward compatibility.
*
* Prefer `outboundProxyRules` and `inboundProxyRules` for native-first matching.
*
* @since 6.9.0
*/
proxyRequests?: boolean | string;
/**
* Native-first outbound proxy rules.
*
* @since 8.6.0
*/
outboundProxyRules?: NativeProxyRule[];
/**
* Native-first inbound proxy rules.
*
* @since 8.6.0
*/
inboundProxyRules?: NativeProxyRule[];
/**
* buttonNearDone allows for a creation of a custom button near the done/close button.
* The button is only shown when toolbarType is not "activity", "navigation", or "blank".
*
* For Android:
* - iconType must be "asset"
* - icon path should be in the public folder (e.g. "monkey.svg")
* - width and height are optional, defaults to 48dp
* - button is positioned at the end of toolbar with 8dp margin
*
* For iOS:
* - iconType can be "sf-symbol" or "asset"
* - for sf-symbol, icon should be the symbol name
* - for asset, icon should be the asset name
* @since 6.7.0
* @example
* buttonNearDone: {
* ios: {
* iconType: "sf-symbol",
* icon: "star.fill"
* },
* android: {
* iconType: "asset",
* icon: "public/monkey.svg",
* width: 24,
* height: 24
* }
* }
* Test URL: https://capgo.app
*/
buttonNearDone?: {
ios: {
iconType: 'sf-symbol' | 'asset';
icon: string;
};
android: {
iconType: 'asset' | 'vector';
icon: string;
width?: number;
height?: number;
};
};
/**
* Shows a native screenshot button near the done/close button.
* The button is hidden by default and captures the current viewport when tapped.
* This option uses the same toolbar slot as `buttonNearDone` and is therefore incompatible with it.
* The button is only shown when toolbarType is not "activity", "navigation", or "blank".
*
* @default false
* @since 8.4.0
*/
showScreenshotButton?: boolean;
/**
* textZoom: sets the text zoom of the page in percent.
* Allows users to increase or decrease the text size for better readability.
* @since 7.6.0
* @default 100
* @example
* textZoom: 120
* Test URL: https://capgo.app
*/
textZoom?: number;
/**
* enableZoom: enables pinch-to-zoom gestures in the Android WebView.
* When true, built-in zoom controls are enabled and the zoom buttons are hidden.
* **Android only** â ignored on iOS where zoom is enabled by default.
* @since 8.5.0
* @default false
* @example
* enableZoom: true
*/
enableZoom?: boolean;
/**
* preventDeeplink: if true, the deeplink will not be opened, if false the deeplink will be opened when clicked on the link. on IOS each schema need to be added to info.plist file under LSApplicationQueriesSchemes when false to make it work.
* @since 0.1.0
* @default false
* @example
* preventDeeplink: true
* Test URL: https://aasa-tester.capgo.app/
*/
preventDeeplink?: boolean;
/**
* When true, HTTP and HTTPS links opened from `target="_blank"` anchors stay in the current webview instead of spawning a popup or opening in the system browser.
* By default, blank-target HTTP(S) links stay inside the plugin as managed popups that share cookies with the opener; enabling this option keeps everything in the same tab.
* Custom schemes such as `tel:` and `mailto:` and authorized app links still prefer their native handlers unless `preventDeeplink` is enabled.
*
* @since 8.5.6
* @default false
* @example
* openBlankTargetInWebView: true
*/
openBlankTargetInWebView?: boolean;
/**
* List of base URLs whose hosts are treated as authorized App Links (Android) and Universal Links (iOS).
*
* - On both platforms, only HTTPS links whose host matches any entry in this list
* will attempt to open via the corresponding native application.
* - If the app is not installed or the system cannot handle the link, the URL
* will continue loading inside the in-app browser.
* - Matching is host-based (case-insensitive), ignoring the "www." prefix.
* - When `preventDeeplink` is enabled, all external handling is blocked regardless of this list.
*
* @example
* ```ts
* ["https://example.com", "https://subdomain.app.io"]
* ```
*
* @since 7.12.0
* @default []
*/
authorizedAppLinks?: string[];
/**
* If true, the webView will not take the full height and will have a 20px margin at the bottom.
* This creates a safe margin area outside the browser view.
* @since 7.13.0
* @default false
* @example
* enabledSafeBottomMargin: true
*/
enabledSafeBottomMargin?: boolean;
/**
* If false, the webView will extend behind the status bar for true full-screen immersive content.
* When true (default), respects the safe area at the top of the screen.
* Works independently of toolbarType - use for full-screen video players, games, or immersive web apps.
* @since 8.2.0
* @default true
* @example
* enabledSafeTopMargin: false // Full screen, extends behind status bar
*/
enabledSafeTopMargin?: boolean;
/**
* When true, applies the system status bar inset as the WebView top margin on Android.
* Keeps the legacy 0px margin by default for apps that handle padding themselves.
* @default false
* @example
* useTopInset: true
*/
useTopInset?: boolean;
/**
* enableGooglePaySupport: if true, enables support for Google Pay popups and Payment Request API.
* This fixes OR_BIBED_15 errors by allowing popup windows and configuring Cross-Origin-Opener-Policy.
* Only enable this if you need Google Pay functionality as it allows popup windows.
*
* When enabled:
* - Allows popup windows for Google Pay authentication
* - Sets proper CORS headers for Payment Request API
* - Enables multiple window support in WebView
* - Configures secure context for payment processing
*
* @since 7.13.0
* @default false
* @example
* enableGooglePaySupport: true
* Test URL: https://developers.google.com/pay/api/web/guides/tutorial
*/
enableGooglePaySupport?: boolean;
/**
* Opens popup windows created by the page in hidden mode.
* Hidden popup windows can still be controlled with `executeScript`, `postMessage`, `show`, and `close`.
* Listen to `popupWindowOpened` to capture the popup id, then call `show({ id })` only if you want to reveal it.
*
* @default false
* @since 8.6.0
* @example
* hiddenPopupWindow: true
*/
hiddenPopupWindow?: boolean;
/**
* blockedHosts: List of host patterns that should be blocked from loading in the InAppBrowser's internal navigations.
* Any request inside WebView to a URL with a host matching any of these patterns will be blocked.
* Supports wildcard patterns like:
* - "*.example.com" to block all subdomains
* - "www.example.*" to block wildcard domain extensions
*
* @since 7.17.0
* @default []
* @example
* blockedHosts: ["*.tracking.com", "ads.example.com"]
*/
blockedHosts?: string[];
/**
* Width of the webview in pixels.
* If not set, webview will be fullscreen width.
* @default undefined (fullscreen)
* @example
* width: 400
*/
width?: number;
/**
* Height of the webview in pixels.
* If not set, webview will be fullscreen height.
* @default undefined (fullscreen)
* @example
* height: 600
*/
height?: number;
/**
* X position of the webview in pixels from the left edge.
* Only effective when width is set.
* @default 0
* @example
* x: 50
*/
x?: number;
/**
* Y position of the webview in pixels from the top edge.
* Only effective when height is set.
* @default 0
* @example
* y: 100
*/
y?: number;
/**
* Disables the bounce (overscroll) effect on iOS WebView.
* When enabled, prevents the rubber band scrolling effect when users scroll beyond content boundaries.
* This is useful for:
* - Creating a more native, app-like experience
* - Preventing accidental overscroll states
* - Avoiding issues when keyboard opens/closes
*
* Note: This option only affects iOS. Android does not have this bounce effect by default.
*
* @since 8.0.2
* @default false
* @example
* disableOverscroll: true
*/
disableOverscroll?: boolean;
/**
* Opens the webview in hidden mode (not visible to user but fully functional).
* When hidden, the webview loads and executes JavaScript but is not displayed.
* All control methods (executeScript, postMessage, setUrl, etc.) work while hidden.
* Use close() to clean up the hidden webview when done.
*
* @since 8.0.7
* @default false
* @example
* hidden: true
*/
hidden?: boolean;
/**
* Controls how a hidden webview reports its visibility and size.
* - AWARE: webview is aware it's hidden (dimensions may be zero).
* - FAKE_VISIBLE: webview is hidden but reports fullscreen dimensions (uses alpha=0 to remain invisible).
*
* @default InvisibilityMode.AWARE
* @example
* invisibilityMode: InvisibilityMode.FAKE_VISIBLE
*/
invisibilityMode?: InvisibilityMode;
}
````
### `ScreenshotResult`
[Section titled âScreenshotResultâ](#screenshotresult)
```typescript
export interface ScreenshotResult {
/**
* Image format used for the screenshot.
*/
format: '.png';
/**
* MIME type of the generated screenshot.
*/
mimeType: 'image/.png';
/**
* Base64-encoded screenshot payload without the data URL prefix.
*/
base64: string;
/**
* Data URL for direct use in HTML img tags or uploads.
*/
dataUrl: string;
/**
* Screenshot width in pixels.
*/
width: number;
/**
* Screenshot height in pixels.
*/
height: number;
}
```
### `UrlChangeListener`
[Section titled âUrlChangeListenerâ](#urlchangelistener)
```typescript
export type UrlChangeListener = (state: UrlEvent) => void;
```
### `ButtonNearListener`
[Section titled âButtonNearListenerâ](#buttonnearlistener)
```typescript
export type ButtonNearListener = (state: object) => void;
```
### `ConfirmBtnListener`
[Section titled âConfirmBtnListenerâ](#confirmbtnlistener)
```typescript
export type ConfirmBtnListener = (state: BtnEvent) => void;
```
### `DownloadCompletedEvent`
[Section titled âDownloadCompletedEventâ](#downloadcompletedevent)
Event emitted after a managed download is saved locally.
```typescript
export interface DownloadCompletedEvent {
/**
* Source webview instance id.
*/
id?: string;
/**
* Original URL that triggered the download when available.
*/
sourceUrl?: string;
/**
* Saved filename.
*/
fileName: string;
/**
* Resolved MIME type when available.
*/
mimeType?: string;
/**
* Absolute native filesystem path to the saved file.
*/
path: string;
/**
* `file://` URL pointing at the saved file.
*/
localUrl: string;
/**
* How native handled the downloaded file after saving it.
*/
handledBy: DownloadHandledBy;
}
```
### `DownloadFailedEvent`
[Section titled âDownloadFailedEventâ](#downloadfailedevent)
Event emitted when managed download handling fails.
```typescript
export interface DownloadFailedEvent {
/**
* Source webview instance id.
*/
id?: string;
/**
* Original URL that triggered the download when available.
*/
sourceUrl?: string;
/**
* Intended filename when known.
*/
fileName?: string;
/**
* Resolved MIME type when available.
*/
mimeType?: string;
/**
* Native error message.
*/
error: string;
}
```
### `PopupWindowEvent`
[Section titled âPopupWindowEventâ](#popupwindowevent)
Event emitted when a web page opens a popup/new window.
```typescript
export interface PopupWindowEvent {
/**
* Popup webview instance id.
*/
id: string;
/**
* Parent webview instance id.
*/
parentId?: string;
/**
* Requested popup URL when available.
*/
url?: string;
/**
* Whether the popup was presented immediately.
*/
visible: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-incoming-call-kit
> Capacitor API for presenting a native incoming-call surface.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor API for presenting a native incoming-call surface.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `showIncomingCall` - Displays the native incoming call UI.
* `endCall` - Ends a specific tracked call.
* `endAllCalls` - Ends every tracked call.
* `getActiveCalls` - Returns the currently tracked calls.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------------------- | ------------------------------------------------------------------------------- |
| `showIncomingCall` | Displays the native incoming call UI. |
| `endCall` | Ends a specific tracked call. |
| `endAllCalls` | Ends every tracked call. |
| `getActiveCalls` | Returns the currently tracked calls. |
| `checkPermissions` | Returns the current permission state for notifications and full-screen intents. |
| `requestPermissions` | Requests the notification permission when the platform supports it. |
| `requestFullScreenIntentPermission` | Opens the Android 14+ full-screen intent settings page when available. |
| `getPluginVersion` | Returns the native implementation version marker. |
| `addListener` | Fired after the call has been handed to the native platform UI. |
| `addListener` | Fired when the user accepts the call from native UI. |
| `addListener` | Fired when the user declines the call from native UI. |
| `addListener` | Fired when a call ends through the API or a platform action. |
| `addListener` | Fired when an unanswered call reaches its configured timeout. |
| `removeAllListeners` | Removes every native listener registered by the plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-incoming-call-kit](https://github.com/Cap-go/capacitor-incoming-call-kit/).
# Android
> Configure notifications, full-screen intents, and Android-specific incoming-call behavior.
## How Android behavior works
[Section titled âHow Android behavior worksâ](#how-android-behavior-works)
On Android, the plugin posts a high-priority incoming-call notification and can raise a full-screen activity when the platform and user settings allow it.
The plugin manifest already includes:
```xml
```
After installation, `cap sync` is enough to merge that configuration into your host app.
## Runtime permissions
[Section titled âRuntime permissionsâ](#runtime-permissions)
Call these methods during onboarding or before you rely on incoming-call presentation:
```ts
import { IncomingCallKit } from '@capgo/capacitor-incoming-call-kit';
await IncomingCallKit.requestPermissions();
await IncomingCallKit.requestFullScreenIntentPermission();
```
* `requestPermissions()` requests notification permission on Android 13 and later.
* `requestFullScreenIntentPermission()` opens the Android 14 and later settings page for full-screen intents when needed.
## Basic example
[Section titled âBasic exampleâ](#basic-example)
```ts
import { IncomingCallKit } from '@capgo/capacitor-incoming-call-kit';
await IncomingCallKit.showIncomingCall({
callId: 'call-42',
callerName: 'Ada Lovelace',
appName: 'Capgo Phone',
timeoutMs: 45_000,
android: {
channelId: 'calls',
channelName: 'Incoming Calls',
showFullScreen: true,
isHighPriority: true,
accentColor: '#0F766E',
},
});
```
## Android-specific options
[Section titled âAndroid-specific optionsâ](#android-specific-options)
* `channelId`: identifier for the notification channel
* `channelName`: user-visible channel name
* `showFullScreen`: request the full-screen activity
* `isHighPriority`: keep the notification disruptive enough for ringing flows
* `accentColor`: tint compatible notification surfaces
* `ringtoneUri`: point at a custom Android ringtone resource or URI
## Behavior notes
[Section titled âBehavior notesâ](#behavior-notes)
* Full-screen presentation is best-effort. If the device or user settings block it, Android still shows the incoming-call notification.
* Timeout handling is best-effort. The plugin tracks `timeoutMs` and emits `callTimedOut`, but your backend should still reconcile missed calls on its side.
* Accept, decline, and end actions are emitted back through Capacitor listeners so your app can join or clean up the real call session.
## Recommended production model
[Section titled âRecommended production modelâ](#recommended-production-model)
Use Android push or your calling SDK for transport, then let this plugin handle the last mile of native ringing UI. Keep these responsibilities outside the plugin:
* FCM registration and token management
* Media session lifecycle
* Backend call state
* Retry and missed-call business logic
# Getting Started
> Install and wire incoming call presentation in Capacitor with a transport-agnostic API.
1. **Install the package**
```sh
bun add @capgo/capacitor-incoming-call-kit
```
2. **Sync native projects**
```sh
bunx cap sync
```
3. **Choose your ring source** Decide whether the incoming-call event comes from your backend, an SDK such as Twilio or Stream, or a native push path such as FCM or PushKit.
## How the integration fits together
[Section titled âHow the integration fits togetherâ](#how-the-integration-fits-together)
This plugin only owns native incoming-call presentation. Your app still owns transport, authentication, and the actual media session.
The common production pattern is:
1. Your backend or calling SDK emits a ring event.
2. Your app calls `showIncomingCall()`.
3. The plugin presents native incoming-call UI.
4. `callAccepted` tells your app to join the actual room or VoIP session.
5. `callDeclined`, `callEnded`, or `callTimedOut` tells your app to clean up remote state.
## Minimal integration
[Section titled âMinimal integrationâ](#minimal-integration)
```ts
import { IncomingCallKit } from '@capgo/capacitor-incoming-call-kit';
await IncomingCallKit.requestPermissions();
await IncomingCallKit.requestFullScreenIntentPermission();
await IncomingCallKit.addListener('callAccepted', async ({ call }) => {
console.log('Accepted', call.callId, call.extra);
// Start or join your real call session here.
});
await IncomingCallKit.addListener('callDeclined', ({ call }) => {
console.log('Declined', call.callId);
// Tell your backend or SDK that the user declined.
});
await IncomingCallKit.addListener('callTimedOut', ({ call }) => {
console.log('Timed out', call.callId);
// Clear ringing state in your backend or SDK.
});
await IncomingCallKit.showIncomingCall({
callId: 'call-42',
callerName: 'Ada Lovelace',
handle: '+39 555 010 020',
appName: 'Capgo Phone',
hasVideo: true,
timeoutMs: 45_000,
extra: {
roomId: 'room-42',
callerUserId: 'user_ada',
},
android: {
channelId: 'calls',
channelName: 'Incoming Calls',
showFullScreen: true,
},
ios: {
handleType: 'phoneNumber',
},
});
```
## Important options
[Section titled âImportant optionsâ](#important-options)
* `callId`: stable identifier reused later with `endCall()`
* `timeoutMs`: best-effort unanswered timeout
* `extra`: arbitrary JSON echoed back in listener payloads
* `android.channelId` and `android.channelName`: Android notification channel tuning
* `android.showFullScreen`: requests the Android full-screen incoming-call activity
* `ios.handleType`: choose `generic`, `phoneNumber`, or `emailAddress` for CallKit
## Managing active calls
[Section titled âManaging active callsâ](#managing-active-calls)
```ts
const { calls } = await IncomingCallKit.getActiveCalls();
await IncomingCallKit.endCall({
callId: 'call-42',
reason: 'remote-ended',
});
await IncomingCallKit.endAllCalls({
reason: 'session-reset',
});
```
## Event model
[Section titled âEvent modelâ](#event-model)
* `incomingCallDisplayed`: native UI was shown successfully
* `callAccepted`: user accepted from the native UI
* `callDeclined`: user declined before joining
* `callEnded`: your app or the platform ended the tracked call
* `callTimedOut`: the call stayed unanswered until `timeoutMs`
Each event carries the normalized `call` payload and your original `extra` object.
## Platform notes
[Section titled âPlatform notesâ](#platform-notes)
* Read the [iOS guide](/docs/plugins/incoming-call-kit/ios/) before wiring CallKit into a PushKit or APNs flow.
* Read the [Android guide](/docs/plugins/incoming-call-kit/android/) before relying on full-screen intents on Android 14 and later.
* Web is not supported.
# iOS
> Configure CallKit behavior and understand production limits on iOS.
## How iOS behavior works
[Section titled âHow iOS behavior worksâ](#how-ios-behavior-works)
On iOS, the plugin reports the incoming call to CallKit. That gives you the system incoming-call sheet and standardized call actions without building your own native incoming-call UI.
`requestPermissions()` resolves immediately on iOS because CallKit itself does not require a runtime permission dialog.
## Basic example
[Section titled âBasic exampleâ](#basic-example)
```ts
import { IncomingCallKit } from '@capgo/capacitor-incoming-call-kit';
await IncomingCallKit.showIncomingCall({
callId: 'call-42',
callerName: 'Ada Lovelace',
handle: '+1 555 010 020',
ios: {
handleType: 'phoneNumber',
supportsHolding: true,
supportsDTMF: false,
},
});
```
## Handle types
[Section titled âHandle typesâ](#handle-types)
Use `ios.handleType` to control how CallKit formats the handle:
* `generic` for app-specific identifiers
* `phoneNumber` for real phone numbers
* `emailAddress` for email-based identities
## Background incoming calls
[Section titled âBackground incoming callsâ](#background-incoming-calls)
This plugin does not register PushKit or APNs for you.
For true background or terminated-state ringing on iOS, your host app still needs the native Apple push setup that matches your transport strategy:
1. Enable Push Notifications when your transport uses Apple push delivery.
2. Enable the Voice over IP background mode when your app uses a VoIP push flow.
3. Deliver the incoming-call event to your app and invoke this plugin as soon as the Capacitor bridge is available.
If your ring event exists only in JavaScript, you will get the best experience while the app is already running in the foreground.
## Microphone and camera permissions
[Section titled âMicrophone and camera permissionsâ](#microphone-and-camera-permissions)
CallKit does not replace your media SDK. If the real call session uses microphone or camera access, those usage descriptions still belong in your app:
```xml
NSMicrophoneUsageDescriptionThis app uses the microphone for calls.NSCameraUsageDescriptionThis app uses the camera for video calls.
```
Add only the keys your real calling flow needs.
## Keep these responsibilities in your app layer
[Section titled âKeep these responsibilities in your app layerâ](#keep-these-responsibilities-in-your-app-layer)
* PushKit and APNs registration
* Authentication and token refresh
* Joining the real room or VoIP session after `callAccepted`
* Ending or reconciling remote call state when the plugin emits `callDeclined`, `callEnded`, or `callTimedOut`
# @capgo/capacitor-install-referrer
> Read Android Play install referrer data and iOS Apple AdServices attribution tokens from Capacitor.
## Overview
[Section titled âOverviewâ](#overview)
`@capgo/capacitor-install-referrer` exposes install attribution signals through one Capacitor API.
On Android, it reads Google Play Install Referrer details: the raw referrer string, click timestamp, install timestamp, and instant app flag. On iOS, it returns an Apple AdServices attribution token and can optionally call Appleâs AdServices attribution endpoint for Apple Search Ads attribution data.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `getReferrer` - Return native install attribution details for the current platform.
* `GetReferrer` - Deprecated compatibility alias for apps migrating from `cap-play-install-referrer`.
* `getPluginVersion` - Return the native plugin implementation version marker.
* Optional iOS Apple attribution lookup with retry support for delayed AdServices responses.
## Platform Support
[Section titled âPlatform Supportâ](#platform-support)
| Platform | Support |
| -------- | ------------------------------------------------------------------------- |
| Android | Google Play Install Referrer API |
| iOS | Apple AdServices attribution token and optional Apple attribution payload |
| Web | Unsupported stub |
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------- | ------------------------------------------------------ |
| `getReferrer(options?)` | Return install attribution details for Android or iOS. |
| `GetReferrer(options?)` | Deprecated compatibility alias for `getReferrer`. |
| `getPluginVersion()` | Return the native plugin version marker. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-install-referrer](https://github.com/Cap-go/capacitor-install-referrer/).
# Android Referrer
> Android behavior for @capgo/capacitor-install-referrer.
## Google Play Install Referrer
[Section titled âGoogle Play Install Referrerâ](#google-play-install-referrer)
On Android, `getReferrer()` connects to the Google Play Install Referrer service and returns data from the Play Store install record.
```typescript
const result = await InstallReferrer.getReferrer();
console.log(result.referrer);
console.log(result.clickTimestampSeconds);
console.log(result.installBeginTimestampSeconds);
console.log(result.googlePlayInstantParam);
```
## Returned Fields
[Section titled âReturned Fieldsâ](#returned-fields)
| Field | Description |
| ------------------------------ | ------------------------------------------------------- |
| `platform` | Always `android`. |
| `referrer` | Raw Play install referrer string. |
| `clickTimestampSeconds` | Client-side referrer click timestamp in seconds. |
| `installBeginTimestampSeconds` | Client-side install begin timestamp in seconds. |
| `googlePlayInstantParam` | Whether the user launched the appâs instant experience. |
## Requirements
[Section titled âRequirementsâ](#requirements)
* The app must be installed from Google Play for real install referrer data.
* The device must have a Play Store version that supports the Install Referrer service.
* No Android runtime permission is required.
## Error Cases
[Section titled âError Casesâ](#error-cases)
The plugin rejects when the Play Store service is unavailable, unsupported, disconnected before returning a result, or returns an unexpected response.
# Getting Started
> Install @capgo/capacitor-install-referrer and read install attribution data in a Capacitor app.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-install-referrer
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { InstallReferrer } from '@capgo/capacitor-install-referrer';
```
## Read Attribution Details
[Section titled âRead Attribution Detailsâ](#read-attribution-details)
```typescript
const result = await InstallReferrer.getReferrer();
if (result.platform === 'android') {
console.log('Install referrer:', result.referrer);
console.log('Click timestamp:', result.clickTimestampSeconds);
console.log('Install timestamp:', result.installBeginTimestampSeconds);
}
if (result.platform === 'ios') {
console.log('AdServices token:', result.attributionToken);
}
```
## Fetch Apple Attribution On iOS
[Section titled âFetch Apple Attribution On iOSâ](#fetch-apple-attribution-on-ios)
If you want native code to call Appleâs attribution endpoint, pass `fetchAppleAttribution`.
```typescript
const result = await InstallReferrer.getReferrer({
fetchAppleAttribution: true,
appleAttributionRetryCount: 3,
appleAttributionRetryDelayMs: 5000,
});
// result.appleAttribution is the parsed Apple attribution response.
// See the iOS attribution page for the Apple-provided payload fields.
console.log(result.appleAttribution);
```
Apple can return `404` while attribution data is still being prepared for a valid token. The retry options control how often the native plugin retries before rejecting. See [iOS attribution](/docs/plugins/install-referrer/ios/) for platform details.
## Compatibility Alias
[Section titled âCompatibility Aliasâ](#compatibility-alias)
`GetReferrer()` is available for apps migrating from `cap-play-install-referrer`.
```typescript
const result = await InstallReferrer.GetReferrer();
```
New code should use `getReferrer()`.
# iOS Attribution
> iOS behavior for @capgo/capacitor-install-referrer with Apple AdServices.
## Apple AdServices
[Section titled âApple AdServicesâ](#apple-adservices)
Apple does not provide a generic App Store install referrer equivalent to Google Play Install Referrer. On iOS, this plugin uses Apple AdServices attribution.
By default, `getReferrer()` returns an AdServices attribution token that you can send to your backend or mobile measurement partner.
```typescript
const result = await InstallReferrer.getReferrer();
console.log(result.attributionToken);
```
## Native Apple Attribution Lookup
[Section titled âNative Apple Attribution Lookupâ](#native-apple-attribution-lookup)
The plugin can also send the token to Appleâs AdServices endpoint from native code.
```typescript
const result = await InstallReferrer.getReferrer({
fetchAppleAttribution: true,
});
console.log(result.appleAttribution);
```
Use this mode when the app itself should receive Appleâs attribution payload. Keep `fetchAppleAttribution` false when your backend or attribution provider should exchange the token.
## Returned Fields
[Section titled âReturned Fieldsâ](#returned-fields)
| Field | Description |
| ------------------ | ------------------------------------------------------------------------ |
| `platform` | Always `ios`. |
| `attributionToken` | Apple AdServices attribution token. |
| `appleAttribution` | Optional Apple attribution payload when `fetchAppleAttribution` is true. |
## Requirements
[Section titled âRequirementsâ](#requirements)
* Apple AdServices attribution tokens are available on iOS 14.3 and later.
* The attribution payload covers Apple Search Ads attribution, not arbitrary App Store referrer URLs.
* No App Tracking Transparency prompt is required just to request the AdServices attribution token.
# @capgo/capacitor-intent-launcher
> Capacitor Intent Launcher Plugin for launching Android intents and opening system settings on both Android and iOS.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Intent Launcher Plugin for launching Android intents and opening system settings on both Android and iOS.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `startActivityAsync` - Starts an Android activity for the given action.
* `openIOSSettings` - Opens iOS settings screen.
* `openApplication` - Opens an application by its package name.
* `getApplicationIconAsync` - Gets the application icon as a base64-encoded PNG string.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------- | --------------------------------------------------------- |
| `startActivityAsync` | Starts an Android activity for the given action. |
| `openIOSSettings` | Opens iOS settings screen. |
| `openApplication` | Opens an application by its package name. |
| `getApplicationIconAsync` | Gets the application icon as a base64-encoded PNG string. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-intent-launcher](https://github.com/Cap-go/capacitor-intent-launcher/).
# Getting Started
> Install @capgo/capacitor-intent-launcher and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-intent-launcher
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { IntentLauncher } from '@capgo/capacitor-intent-launcher';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `startActivityAsync`
[Section titled âstartActivityAsyncâ](#startactivityasync)
Starts an Android activity for the given action.
```typescript
import { IntentLauncher } from '@capgo/capacitor-intent-launcher';
// Open location settings
const result = await IntentLauncher.startActivityAsync({
action: ActivityAction.LOCATION_SOURCE_SETTINGS
});
// Open a specific app settings
const result = await IntentLauncher.startActivityAsync({
action: ActivityAction.APPLICATION_DETAILS_SETTINGS,
data: 'package:com.example.app'
});
```
### `openIOSSettings`
[Section titled âopenIOSSettingsâ](#openiossettings)
Opens iOS settings screen.
Note: The only officially supported option by Apple is `App` which opens your appâs settings page. Other options may work but are not guaranteed and could break in future iOS versions or cause App Store rejection.
Also note that the iOS Simulator will sometimes only open the Settings app, instead of the specified option.
```typescript
import { IntentLauncher } from '@capgo/capacitor-intent-launcher';
// Open app settings (recommended - officially supported by Apple)
await IntentLauncher.openIOSSettings({ option: IOSSettings.App });
// Open WiFi settings (may not work in all iOS versions)
await IntentLauncher.openIOSSettings({ option: IOSSettings.WiFi });
```
### `openApplication`
[Section titled âopenApplicationâ](#openapplication)
Opens an application by its package name.
```typescript
import { IntentLauncher } from '@capgo/capacitor-intent-launcher';
// Open Gmail app
await IntentLauncher.openApplication({ packageName: 'com.google.android.gm' });
```
### `getApplicationIconAsync`
[Section titled âgetApplicationIconAsyncâ](#getapplicationiconasync)
Gets the application icon as a base64-encoded PNG string.
```typescript
import { IntentLauncher } from '@capgo/capacitor-intent-launcher';
const { icon } = await IntentLauncher.getApplicationIconAsync({
packageName: 'com.google.android.gm'
});
if (icon) {
const img = document.createElement('img');
img.src = icon;
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `IntentLauncherParams`
[Section titled âIntentLauncherParamsâ](#intentlauncherparams)
Options for starting an activity.
```typescript
export interface IntentLauncherParams {
/**
* The action to perform. Use values from `ActivityAction` enum.
*
* @since 1.0.0
*/
action: string;
/**
* Optional category to add to the intent.
*
* @since 1.0.0
*/
category?: string;
/**
* Optional class name for the component to launch.
*
* @since 1.0.0
*/
className?: string;
/**
* Optional URI data for the intent. Must be a valid URI.
*
* @since 1.0.0
*/
data?: string;
/**
* Optional extra data to pass to the intent as key-value pairs.
*
* @since 1.0.0
*/
extra?: Record;
/**
* Optional intent flags as a bitmask.
*
* @since 1.0.0
*/
flags?: number;
/**
* Optional package name for the component.
*
* @since 1.0.0
*/
packageName?: string;
/**
* Optional MIME type for the intent data.
*
* @since 1.0.0
*/
type?: string;
}
```
### `IntentLauncherResult`
[Section titled âIntentLauncherResultâ](#intentlauncherresult)
Result from starting an activity.
```typescript
export interface IntentLauncherResult {
/**
* The result code returned by the activity.
*
* @since 1.0.0
*/
resultCode: ResultCode;
/**
* Optional data URI returned by the activity.
*
* @since 1.0.0
*/
data?: string;
/**
* Optional extra data returned by the activity.
*
* @since 1.0.0
*/
extra?: Record;
}
```
### `IOSSettingsParams`
[Section titled âIOSSettingsParamsâ](#iossettingsparams)
Options for opening iOS settings.
```typescript
export interface IOSSettingsParams {
/**
* The iOS settings screen to open. Use values from `IOSSettings` enum.
*
* @since 8.2.0
*/
option: string;
}
```
### `IOSSettingsResult`
[Section titled âIOSSettingsResultâ](#iossettingsresult)
Result from opening iOS settings.
```typescript
export interface IOSSettingsResult {
/**
* Whether the settings screen was successfully opened.
*
* @since 8.2.0
*/
success: boolean;
}
```
### `OpenApplicationOptions`
[Section titled âOpenApplicationOptionsâ](#openapplicationoptions)
Options for opening an application.
```typescript
export interface OpenApplicationOptions {
/**
* The package name of the application to open.
*
* @since 1.0.0
*/
packageName: string;
}
```
### `GetApplicationIconOptions`
[Section titled âGetApplicationIconOptionsâ](#getapplicationiconoptions)
Options for getting an application icon.
```typescript
export interface GetApplicationIconOptions {
/**
* The package name of the application.
*
* @since 1.0.0
*/
packageName: string;
}
```
### `GetApplicationIconResult`
[Section titled âGetApplicationIconResultâ](#getapplicationiconresult)
Result from getting an application icon.
```typescript
export interface GetApplicationIconResult {
/**
* The application icon as a base64-encoded PNG string prefixed with 'data:image/.png;base64,'.
* Empty string if the icon is not available.
*
* @since 1.0.0
*/
icon: string;
}
```
### `ResultCode`
[Section titled âResultCodeâ](#resultcode)
Result codes returned by activities.
```typescript
export enum ResultCode {
/**
* The activity completed successfully.
*/
Success = -1,
/**
* The activity was canceled by the user.
*/
Canceled = 0,
/**
* First custom user-defined result code.
*/
FirstUser = 1,
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-intercom
> Intercom Capacitor plugin.
## Overview
[Section titled âOverviewâ](#overview)
Intercom Capacitor plugin.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `loadWithKeys` - Initialize Intercom with API keys at runtime. Use this if you prefer not to configure keys in capacitor.config.
* `registerIdentifiedUser` - Register a known user with Intercom. At least one of userId or email must be provided.
* `registerUnidentifiedUser` - Register an anonymous user with Intercom.
* `updateUser` - Update user attributes in Intercom.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `loadWithKeys` | Initialize Intercom with API keys at runtime. Use this if you prefer not to configure keys in capacitor.config. |
| `registerIdentifiedUser` | Register a known user with Intercom. At least one of userId or email must be provided. |
| `registerUnidentifiedUser` | Register an anonymous user with Intercom. |
| `updateUser` | Update user attributes in Intercom. |
| `logout` | Log the user out of Intercom. |
| `logEvent` | Log a custom event in Intercom. |
| `displayMessenger` | Open the Intercom messenger. |
| `displayMessageComposer` | Open the message composer with a pre-filled message. |
| `displayHelpCenter` | Open the Intercom help center. |
| `hideMessenger` | Hide the Intercom messenger. |
| `displayLauncher` | Show the Intercom launcher button. |
| `hideLauncher` | Hide the Intercom launcher button. |
| `displayInAppMessages` | Enable in-app messages from Intercom. |
| `hideInAppMessages` | Disable in-app messages from Intercom. |
| `displayCarousel` | Display a specific Intercom carousel. |
| `displayArticle` | Display a specific Intercom article. |
| `displaySurvey` | Display a specific Intercom survey. |
| `setUserHash` | Set the HMAC for identity verification. |
| `setUserJwt` | Set JWT for secure messenger authentication. |
| `setBottomPadding` | Set the bottom padding for the Intercom messenger UI. |
| `sendPushTokenToIntercom` | Send a push notification token to Intercom. |
| `receivePush` | Handle a received Intercom push notification. |
| `getUnreadConversationCount` | Get the number of unread conversations for the current user. |
| `addListener` | Listen for when the Intercom window is shown. |
| `addListener` | Listen for when the Intercom window is hidden. |
| `addListener` | Listen for changes in the unread conversation count. |
| `removeAllListeners` | Remove all event listeners. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-intercom](https://github.com/Cap-go/capacitor-intercom/).
# Getting Started
> Install @capgo/capacitor-intercom and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-intercom
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `loadWithKeys`
[Section titled âloadWithKeysâ](#loadwithkeys)
Initialize Intercom with API keys at runtime. Use this if you prefer not to configure keys in capacitor.config.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.loadWithKeys({} as IntercomLoadOptions);
```
### `registerIdentifiedUser`
[Section titled âregisterIdentifiedUserâ](#registeridentifieduser)
Register a known user with Intercom. At least one of userId or email must be provided.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.registerIdentifiedUser({} as IntercomIdentifiedUserOptions);
```
### `registerUnidentifiedUser`
[Section titled âregisterUnidentifiedUserâ](#registerunidentifieduser)
Register an anonymous user with Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.registerUnidentifiedUser();
```
### `updateUser`
[Section titled âupdateUserâ](#updateuser)
Update user attributes in Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.updateUser({} as IntercomUserUpdateOptions);
```
### `logout`
[Section titled âlogoutâ](#logout)
Log the user out of Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.logout();
```
### `logEvent`
[Section titled âlogEventâ](#logevent)
Log a custom event in Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.logEvent({} as IntercomLogEventOptions);
```
### `displayMessenger`
[Section titled âdisplayMessengerâ](#displaymessenger)
Open the Intercom messenger.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayMessenger();
```
### `displayMessageComposer`
[Section titled âdisplayMessageComposerâ](#displaymessagecomposer)
Open the message composer with a pre-filled message.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayMessageComposer({} as IntercomMessageComposerOptions);
```
### `displayHelpCenter`
[Section titled âdisplayHelpCenterâ](#displayhelpcenter)
Open the Intercom help center.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayHelpCenter();
```
### `hideMessenger`
[Section titled âhideMessengerâ](#hidemessenger)
Hide the Intercom messenger.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.hideMessenger();
```
### `displayLauncher`
[Section titled âdisplayLauncherâ](#displaylauncher)
Show the Intercom launcher button.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayLauncher();
```
### `hideLauncher`
[Section titled âhideLauncherâ](#hidelauncher)
Hide the Intercom launcher button.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.hideLauncher();
```
### `displayInAppMessages`
[Section titled âdisplayInAppMessagesâ](#displayinappmessages)
Enable in-app messages from Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayInAppMessages();
```
### `hideInAppMessages`
[Section titled âhideInAppMessagesâ](#hideinappmessages)
Disable in-app messages from Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.hideInAppMessages();
```
### `displayCarousel`
[Section titled âdisplayCarouselâ](#displaycarousel)
Display a specific Intercom carousel.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayCarousel({} as IntercomCarouselOptions);
```
### `displayArticle`
[Section titled âdisplayArticleâ](#displayarticle)
Display a specific Intercom article.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displayArticle({} as IntercomArticleOptions);
```
### `displaySurvey`
[Section titled âdisplaySurveyâ](#displaysurvey)
Display a specific Intercom survey.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.displaySurvey({} as IntercomSurveyOptions);
```
### `setUserHash`
[Section titled âsetUserHashâ](#setuserhash)
Set the HMAC for identity verification.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.setUserHash({} as IntercomUserHashOptions);
```
### `setUserJwt`
[Section titled âsetUserJwtâ](#setuserjwt)
Set JWT for secure messenger authentication.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.setUserJwt({} as IntercomUserJwtOptions);
```
### `setBottomPadding`
[Section titled âsetBottomPaddingâ](#setbottompadding)
Set the bottom padding for the Intercom messenger UI.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.setBottomPadding({} as IntercomBottomPaddingOptions);
```
### `sendPushTokenToIntercom`
[Section titled âsendPushTokenToIntercomâ](#sendpushtokentointercom)
Send a push notification token to Intercom.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.sendPushTokenToIntercom({} as IntercomPushTokenOptions);
```
### `receivePush`
[Section titled âreceivePushâ](#receivepush)
Handle a received Intercom push notification.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.receivePush({} as IntercomPushNotificationData);
```
### `getUnreadConversationCount`
[Section titled âgetUnreadConversationCountâ](#getunreadconversationcount)
Get the number of unread conversations for the current user.
```typescript
import { CapgoIntercom } from '@capgo/capacitor-intercom';
await CapgoIntercom.getUnreadConversationCount();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `IntercomLoadOptions`
[Section titled âIntercomLoadOptionsâ](#intercomloadoptions)
```typescript
export interface IntercomLoadOptions {
appId?: string;
apiKeyIOS?: string;
apiKeyAndroid?: string;
}
```
### `IntercomIdentifiedUserOptions`
[Section titled âIntercomIdentifiedUserOptionsâ](#intercomidentifieduseroptions)
```typescript
export interface IntercomIdentifiedUserOptions {
userId?: string;
email?: string;
}
```
### `IntercomUserUpdateOptions`
[Section titled âIntercomUserUpdateOptionsâ](#intercomuserupdateoptions)
```typescript
export interface IntercomUserUpdateOptions {
userId?: string;
email?: string;
name?: string;
phone?: string;
languageOverride?: string;
customAttributes?: { [key: string]: any };
companies?: IntercomCompany[];
}
```
### `IntercomLogEventOptions`
[Section titled âIntercomLogEventOptionsâ](#intercomlogeventoptions)
```typescript
export interface IntercomLogEventOptions {
name: string;
data?: { [key: string]: any };
}
```
### `IntercomMessageComposerOptions`
[Section titled âIntercomMessageComposerOptionsâ](#intercommessagecomposeroptions)
```typescript
export interface IntercomMessageComposerOptions {
message: string;
}
```
### `IntercomCarouselOptions`
[Section titled âIntercomCarouselOptionsâ](#intercomcarouseloptions)
```typescript
export interface IntercomCarouselOptions {
carouselId: string;
}
```
### `IntercomArticleOptions`
[Section titled âIntercomArticleOptionsâ](#intercomarticleoptions)
```typescript
export interface IntercomArticleOptions {
articleId: string;
}
```
### `IntercomSurveyOptions`
[Section titled âIntercomSurveyOptionsâ](#intercomsurveyoptions)
```typescript
export interface IntercomSurveyOptions {
surveyId: string;
}
```
### `IntercomUserHashOptions`
[Section titled âIntercomUserHashOptionsâ](#intercomuserhashoptions)
```typescript
export interface IntercomUserHashOptions {
hmac: string;
}
```
### `IntercomUserJwtOptions`
[Section titled âIntercomUserJwtOptionsâ](#intercomuserjwtoptions)
```typescript
export interface IntercomUserJwtOptions {
jwt: string;
}
```
### `IntercomBottomPaddingOptions`
[Section titled âIntercomBottomPaddingOptionsâ](#intercombottompaddingoptions)
```typescript
export interface IntercomBottomPaddingOptions {
value: number;
}
```
### `IntercomPushTokenOptions`
[Section titled âIntercomPushTokenOptionsâ](#intercompushtokenoptions)
```typescript
export interface IntercomPushTokenOptions {
value: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-intune
> Capacitor plugin for Microsoft Intune MAM enrollment, app protection policies, app config, and MSAL authentication.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for Microsoft Intune MAM enrollment, app protection policies, app config, and MSAL authentication.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `acquireToken` - Present the Microsoft sign-in flow and return an access token plus the account metadata.
* `acquireTokenSilent` - Acquire a token from the MSAL cache for a previously signed-in user.
* `registerAndEnrollAccount` - Register a previously authenticated account with Intune and start enrollment.
* `loginAndEnrollAccount` - Ask Intune to authenticate and enroll a user without first requesting an app token.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------ | ---------------------------------------------------------------------------------------- |
| `acquireToken` | Present the Microsoft sign-in flow and return an access token plus the account metadata. |
| `acquireTokenSilent` | Acquire a token from the MSAL cache for a previously signed-in user. |
| `registerAndEnrollAccount` | Register a previously authenticated account with Intune and start enrollment. |
| `loginAndEnrollAccount` | Ask Intune to authenticate and enroll a user without first requesting an app token. |
| `enrolledAccount` | Return the currently enrolled Intune account, if one is available. |
| `deRegisterAndUnenrollAccount` | Deregister the account from Intune and trigger selective wipe when applicable. |
| `logoutOfAccount` | Sign the user out of MSAL without unenrolling the Intune account. |
| `appConfig` | Fetch the remote Intune app configuration for a managed account. |
| `getPolicy` | Fetch the currently effective Intune app protection policy for a managed account. |
| `groupName` | Convenience helper that resolves the `GroupName` app configuration value when present. |
| `sdkVersion` | Return the native Intune and MSAL SDK versions bundled by this plugin. |
| `displayDiagnosticConsole` | Show the native Intune diagnostics UI. |
| `addListener` | Listen for remote app configuration refreshes. |
| `addListener` | Listen for remote app protection policy refreshes. |
| `removeAllListeners` | Remove all registered listeners for this plugin instance. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-intune](https://github.com/Cap-go/capacitor-intune/).
# Android Setup
> Configure Microsoft Intune MAM and MSAL on Android for @capgo/capacitor-intune.
## 1. Add the Intune Gradle plugin
[Section titled â1. Add the Intune Gradle pluginâ](#1-add-the-intune-gradle-plugin)
In your app projectâs top-level `android/build.gradle`, add the Intune Gradle plugin JAR to the `buildscript` classpath. The plugin package includes:
* `android/ms-intune-app-sdk-android/GradlePlugin/com.microsoft.intune.mam.build.jar`
Also include the Duo Maven feed that Ionic documents for current Intune Android SDK releases:
```kotlin
maven {
url 'https://pkgs.dev.azure.com/MicrosoftDeviceSDK/DuoSDK-Public/_packaging/Duo-SDK-Feed/maven/v1'
name 'Duo-SDK-Feed'
}
```
## 2. Update the app module
[Section titled â2. Update the app moduleâ](#2-update-the-app-module)
In `android/app/build.gradle`:
```kotlin
apply plugin: 'com.microsoft.intune.mam'
```
And keep resource optimization disabled:
```properties
android.enableResourceOptimizations=false
```
## 3. Provide `auth_config.json`
[Section titled â3. Provide auth\_config.jsonâ](#3-provide-auth_configjson)
Create `android/app/src/main/res/raw/auth_config.json`:
```json
{
"client_id": "YOUR_CLIENT_ID",
"authorization_user_agent": "BROWSER",
"redirect_uri": "msauth://YOUR_PACKAGE/YOUR_SIGNATURE_HASH",
"broker_redirect_uri_registered": true,
"account_mode": "MULTIPLE",
"authorities": [
{
"type": "AAD",
"audience": {
"type": "AzureADMyOrg"
}
}
]
}
```
The plugin expects that file at runtime for both MSAL and the Intune auth callback.
## 4. Configure the `` tag
[Section titled â4. Configure the \ tagâ](#4-configure-the-application-tag)
If your app does not already define a custom `Application`, set:
```xml
```
If you already have a custom `Application`, extend `MAMApplication` and register `IntuneMamServiceAuthenticationCallback` in `onMAMCreate()`.
## 5. Add broker auth queries and redirect handling
[Section titled â5. Add broker auth queries and redirect handlingâ](#5-add-broker-auth-queries-and-redirect-handling)
Add the package visibility queries Ionic documents for:
* `com.azure.authenticator`
* `com.microsoft.windowsintune.companyportal`
* browser detection intents
Also add `BrowserTabActivity` with your `msauth://` redirect URI host/path so MSAL can complete the sign-in round trip.
## 6. Use the plugin
[Section titled â6. Use the pluginâ](#6-use-the-plugin)
Once the app-level native setup is complete, the Capacitor API is the same as on iOS:
```ts
import { IntuneMAM } from '@capgo/capacitor-intune';
const auth = await IntuneMAM.acquireToken({
scopes: ['https://graph.microsoft.com/.default'],
});
await IntuneMAM.registerAndEnrollAccount({
accountId: auth.accountId,
});
```
# Getting Started
> Install and use Microsoft Intune MAM, policy, app config, and MSAL support in your Capacitor app.
1. **Install the package**
```sh
bun add @capgo/capacitor-intune
```
2. **Sync native projects**
```sh
bunx cap sync
```
3. **Complete native Intune setup** Follow the dedicated [iOS setup](/docs/plugins/intune/ios/) and [Android setup](/docs/plugins/intune/android/) pages. Intune still requires host-app native configuration for brokered auth, redirect URIs, manifests, entitlements, and MSAL config.
## Requirements
[Section titled âRequirementsâ](#requirements)
* Capacitor 8+
* Android with Intune Android SDK `12.0.3`
* iOS with Intune iOS SDK `21.5.1`
* iOS deployment target `17.0+`
Ionicâs Intune docs currently call out a January 19, 2026 cutoff for apps built with Xcode 26, requiring Intune iOS SDK `21.1.0+`. This plugin already uses `21.5.1`.
## Basic Usage
[Section titled âBasic Usageâ](#basic-usage)
```ts
import { IntuneMAM } from '@capgo/capacitor-intune';
await IntuneMAM.addListener('appConfigChange', (result) => {
console.log('App config changed', result.accountId);
});
await IntuneMAM.addListener('policyChange', (result) => {
console.log('Policy changed', result.accountId);
});
const auth = await IntuneMAM.acquireToken({
scopes: ['https://graph.microsoft.com/.default'],
loginHint: 'alex@example.com',
});
await IntuneMAM.registerAndEnrollAccount({
accountId: auth.accountId,
});
const appConfig = await IntuneMAM.appConfig({
accountId: auth.accountId,
});
const policy = await IntuneMAM.getPolicy({
accountId: auth.accountId,
});
console.log({ auth, appConfig, policy });
```
## Common Flows
[Section titled âCommon Flowsâ](#common-flows)
### Interactive sign-in and enrollment
[Section titled âInteractive sign-in and enrollmentâ](#interactive-sign-in-and-enrollment)
```ts
const auth = await IntuneMAM.acquireToken({
scopes: ['https://graph.microsoft.com/.default'],
});
await IntuneMAM.registerAndEnrollAccount({
accountId: auth.accountId,
});
```
### Silent token refresh
[Section titled âSilent token refreshâ](#silent-token-refresh)
```ts
const token = await IntuneMAM.acquireTokenSilent({
accountId: 'AAD_OBJECT_ID',
scopes: ['https://graph.microsoft.com/.default'],
forceRefresh: true,
});
```
### Read the currently enrolled account
[Section titled âRead the currently enrolled accountâ](#read-the-currently-enrolled-account)
```ts
const user = await IntuneMAM.enrolledAccount();
```
### Sign out or selectively wipe
[Section titled âSign out or selectively wipeâ](#sign-out-or-selectively-wipe)
```ts
await IntuneMAM.logoutOfAccount({ accountId: 'AAD_OBJECT_ID' });
await IntuneMAM.deRegisterAndUnenrollAccount({ accountId: 'AAD_OBJECT_ID' });
```
## API Summary
[Section titled âAPI Summaryâ](#api-summary)
* `acquireToken(options)`: Start Microsoft sign-in and return token plus account metadata.
* `acquireTokenSilent(options)`: Read a cached token for an existing account.
* `registerAndEnrollAccount(options)`: Register the MSAL account with Intune and trigger enrollment.
* `loginAndEnrollAccount()`: Let Intune drive the login and enrollment flow.
* `appConfig(user)`: Read Intune app configuration values for the account.
* `getPolicy(user)`: Read the current Intune app protection policy for the account.
* `groupName(user)`: Read the common `GroupName` config helper value when present.
* `sdkVersion()`: Inspect bundled Intune and MSAL versions.
## Platform Notes
[Section titled âPlatform Notesâ](#platform-notes)
* Web is not supported.
* iOS and Android both require native project configuration beyond `cap sync`.
* Your Azure registration, Intune policy assignment, redirect URIs, and entitlements remain app-specific.
# iOS Setup
> Configure Microsoft Intune MAM and MSAL on iOS for @capgo/capacitor-intune.
## iOS Support Matrix
[Section titled âiOS Support Matrixâ](#ios-support-matrix)
* Intune iOS SDK bundled by this plugin: `21.5.1`
* Minimum iOS version: `17.0`
* Recommended Xcode line: `26.x`
Ionicâs Intune docs currently note that apps built with Xcode 26 must use Intune iOS SDK `21.1.0+` starting on January 19, 2026. This plugin is already on that newer SDK line.
## 1. Add Intune and MSAL settings to `Info.plist`
[Section titled â1. Add Intune and MSAL settings to Info.plistâ](#1-add-intune-and-msal-settings-to-infoplist)
Add an `IntuneMAMSettings` dictionary:
```xml
IntuneMAMSettingsADALClientIdYOUR_CLIENT_IDADALRedirectUrimsauth.com.example.app://authADALAuthorityhttps://login.microsoftonline.com/common
```
The plugin reads:
* `ADALClientId`
* `ADALRedirectUri`
* `ADALRedirectScheme` as a fallback if you prefer storing only the scheme
* `ADALAuthority` as an optional authority override
## 2. Forward the MSAL callback in `AppDelegate`
[Section titled â2. Forward the MSAL callback in AppDelegateâ](#2-forward-the-msal-callback-in-appdelegate)
```swift
import MSAL
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
return MSALPublicClientApplication.handleMSALResponse(
url,
sourceApplication: options[.sourceApplication] as? String
)
}
```
## 3. Configure URL schemes and entitlements
[Section titled â3. Configure URL schemes and entitlementsâ](#3-configure-url-schemes-and-entitlements)
Follow Microsoftâs and Ionicâs Intune guidance for:
* the `msauth...` redirect URI scheme
* keychain sharing / keychain access groups
* `LSApplicationQueriesSchemes`
* `NSFaceIDUsageDescription` if your flow needs biometrics
These are app-specific and cannot be inferred by the plugin.
## 4. Run `IntuneMAMConfigurator`
[Section titled â4. Run IntuneMAMConfiguratorâ](#4-run-intunemamconfigurator)
Microsoft requires running `IntuneMAMConfigurator` against your final app `Info.plist` and entitlements. Use the latest configurator from the official Intune iOS SDK and rerun it whenever those files materially change.
## 5. Keep the deployment target aligned
[Section titled â5. Keep the deployment target alignedâ](#5-keep-the-deployment-target-aligned)
Because the bundled Intune iOS SDK is on the current `21.x` line, your app target should remain at iOS `17.0` or later.
# @capgo/capacitor-is-root
> Capacitor Is Root Plugin for detecting rooted (Android) or jailbroken (iOS) devices.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Is Root Plugin for detecting rooted (Android) or jailbroken (iOS) devices.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isRooted` - Performs the default root/jailbreak detection checks.
* `isRootedWithBusyBox` - Extends the default detection with BusyBox specific checks (Android only).
* `detectRootManagementApps` - Detects if known root management applications are present (Android only).
* `detectPotentiallyDangerousApps` - Detects potentially dangerous applications commonly found on rooted devices (Android only).
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| --------------------------------- | ------------------------------------------------------------------------------------------- |
| `isRooted` | Performs the default root/jailbreak detection checks. |
| `isRootedWithBusyBox` | Extends the default detection with BusyBox specific checks (Android only). |
| `detectRootManagementApps` | Detects if known root management applications are present (Android only). |
| `detectPotentiallyDangerousApps` | Detects potentially dangerous applications commonly found on rooted devices (Android only). |
| `detectTestKeys` | Detects debug/test build tags (Android only). |
| `checkForBusyBoxBinary` | Checks whether a BusyBox binary exists on the device (Android only). |
| `checkForSuBinary` | Checks whether a `su` binary is present (Android only). |
| `checkSuExists` | Detects if the `su` binary can be executed (Android only). |
| `checkForRWPaths` | Detects world writable system paths (Android only). |
| `checkForDangerousProps` | Detects dangerous system properties (Android only). |
| `checkForRootNative` | Executes RootBeer native checks (Android only). |
| `detectRootCloakingApps` | Detects applications that can hide root (Android only). |
| `isSelinuxFlagInEnabled` | Checks the SELinux enforcement state (Android only). |
| `isExistBuildTags` | Detects test build tags on the OS image (Android only). |
| `doesSuperuserApkExist` | Detects if superuser APKs are installed (Android only). |
| `isExistSUPath` | Checks for known `su` binary locations (Android only). |
| `checkDirPermissions` | Detects writable directories that should be protected (Android only). |
| `checkExecutingCommands` | Executes `which su` style commands to detect root (Android only). |
| `checkInstalledPackages` | Detects suspicious installed packages (Android only). |
| `checkforOverTheAirCertificates` | Detects tampered OTA certificates (Android only). |
| `isRunningOnEmulator` | Detects common emulator fingerprints (Android only). |
| `simpleCheckEmulator` | Performs a lightweight emulator check (Android only). |
| `simpleCheckSDKBF86` | Detects x86 emulator fingerprints (Android only). |
| `simpleCheckQRREFPH` | Detects QC reference phone builds (Android only). |
| `simpleCheckBuild` | Detects build host anomalies (Android only). |
| `checkGenymotion` | Detects Genymotion emulator fingerprints (Android only). |
| `checkGeneric` | Detects generic emulator fingerprints (Android only). |
| `checkGoogleSDK` | Detects Google SDK emulator fingerprints (Android only). |
| `togetDeviceInfo` | Returns device information collected during detection. |
| `isRootedWithEmulator` | Extends the default detection with emulator heuristics (Android only). |
| `isRootedWithBusyBoxWithEmulator` | Extends the BusyBox detection with emulator heuristics (Android only). |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-is-root](https://github.com/Cap-go/capacitor-is-root/).
# Getting Started
> Install @capgo/capacitor-is-root and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-is-root
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isRooted`
[Section titled âisRootedâ](#isrooted)
Performs the default root/jailbreak detection checks.
This is the recommended method for basic root/jailbreak detection. It runs a combination of the most reliable detection heuristics for the platform. Works on both Android and iOS.
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
const { result } = await IsRoot.isRooted();
if (result) {
console.log('Device is rooted/jailbroken');
} else {
console.log('Device is not rooted/jailbroken');
}
```
### `isRootedWithBusyBox`
[Section titled âisRootedWithBusyBoxâ](#isrootedwithbusybox)
Extends the default detection with BusyBox specific checks (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isRootedWithBusyBox();
```
### `detectRootManagementApps`
[Section titled âdetectRootManagementAppsâ](#detectrootmanagementapps)
Detects if known root management applications are present (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.detectRootManagementApps();
```
### `detectPotentiallyDangerousApps`
[Section titled âdetectPotentiallyDangerousAppsâ](#detectpotentiallydangerousapps)
Detects potentially dangerous applications commonly found on rooted devices (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.detectPotentiallyDangerousApps();
```
### `detectTestKeys`
[Section titled âdetectTestKeysâ](#detecttestkeys)
Detects debug/test build tags (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.detectTestKeys();
```
### `checkForBusyBoxBinary`
[Section titled âcheckForBusyBoxBinaryâ](#checkforbusyboxbinary)
Checks whether a BusyBox binary exists on the device (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkForBusyBoxBinary();
```
### `checkForSuBinary`
[Section titled âcheckForSuBinaryâ](#checkforsubinary)
Checks whether a `su` binary is present (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkForSuBinary();
```
### `checkSuExists`
[Section titled âcheckSuExistsâ](#checksuexists)
Detects if the `su` binary can be executed (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkSuExists();
```
### `checkForRWPaths`
[Section titled âcheckForRWPathsâ](#checkforrwpaths)
Detects world writable system paths (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkForRWPaths();
```
### `checkForDangerousProps`
[Section titled âcheckForDangerousPropsâ](#checkfordangerousprops)
Detects dangerous system properties (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkForDangerousProps();
```
### `checkForRootNative`
[Section titled âcheckForRootNativeâ](#checkforrootnative)
Executes RootBeer native checks (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkForRootNative();
```
### `detectRootCloakingApps`
[Section titled âdetectRootCloakingAppsâ](#detectrootcloakingapps)
Detects applications that can hide root (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.detectRootCloakingApps();
```
### `isSelinuxFlagInEnabled`
[Section titled âisSelinuxFlagInEnabledâ](#isselinuxflaginenabled)
Checks the SELinux enforcement state (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isSelinuxFlagInEnabled();
```
### `isExistBuildTags`
[Section titled âisExistBuildTagsâ](#isexistbuildtags)
Detects test build tags on the OS image (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isExistBuildTags();
```
### `doesSuperuserApkExist`
[Section titled âdoesSuperuserApkExistâ](#doessuperuserapkexist)
Detects if superuser APKs are installed (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.doesSuperuserApkExist();
```
### `isExistSUPath`
[Section titled âisExistSUPathâ](#isexistsupath)
Checks for known `su` binary locations (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isExistSUPath();
```
### `checkDirPermissions`
[Section titled âcheckDirPermissionsâ](#checkdirpermissions)
Detects writable directories that should be protected (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkDirPermissions();
```
### `checkExecutingCommands`
[Section titled âcheckExecutingCommandsâ](#checkexecutingcommands)
Executes `which su` style commands to detect root (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkExecutingCommands();
```
### `checkInstalledPackages`
[Section titled âcheckInstalledPackagesâ](#checkinstalledpackages)
Detects suspicious installed packages (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkInstalledPackages();
```
### `checkforOverTheAirCertificates`
[Section titled âcheckforOverTheAirCertificatesâ](#checkforovertheaircertificates)
Detects tampered OTA certificates (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkforOverTheAirCertificates();
```
### `isRunningOnEmulator`
[Section titled âisRunningOnEmulatorâ](#isrunningonemulator)
Detects common emulator fingerprints (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isRunningOnEmulator();
```
### `simpleCheckEmulator`
[Section titled âsimpleCheckEmulatorâ](#simplecheckemulator)
Performs a lightweight emulator check (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.simpleCheckEmulator();
```
### `simpleCheckSDKBF86`
[Section titled âsimpleCheckSDKBF86â](#simplechecksdkbf86)
Detects x86 emulator fingerprints (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.simpleCheckSDKBF86();
```
### `simpleCheckQRREFPH`
[Section titled âsimpleCheckQRREFPHâ](#simplecheckqrrefph)
Detects QC reference phone builds (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.simpleCheckQRREFPH();
```
### `simpleCheckBuild`
[Section titled âsimpleCheckBuildâ](#simplecheckbuild)
Detects build host anomalies (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.simpleCheckBuild();
```
### `checkGenymotion`
[Section titled âcheckGenymotionâ](#checkgenymotion)
Detects Genymotion emulator fingerprints (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkGenymotion();
```
### `checkGeneric`
[Section titled âcheckGenericâ](#checkgeneric)
Detects generic emulator fingerprints (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkGeneric();
```
### `checkGoogleSDK`
[Section titled âcheckGoogleSDKâ](#checkgooglesdk)
Detects Google SDK emulator fingerprints (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.checkGoogleSDK();
```
### `togetDeviceInfo`
[Section titled âtogetDeviceInfoâ](#togetdeviceinfo)
Returns device information collected during detection.
Provides additional context and metadata about the device that was gathered during the root detection process. Useful for debugging and logging purposes.
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
const deviceInfo = await IsRoot.togetDeviceInfo();
console.log('Device info:', deviceInfo);
```
### `isRootedWithEmulator`
[Section titled âisRootedWithEmulatorâ](#isrootedwithemulator)
Extends the default detection with emulator heuristics (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isRootedWithEmulator();
```
### `isRootedWithBusyBoxWithEmulator`
[Section titled âisRootedWithBusyBoxWithEmulatorâ](#isrootedwithbusyboxwithemulator)
Extends the BusyBox detection with emulator heuristics (Android only).
```typescript
import { IsRoot } from '@capgo/capacitor-is-root';
await IsRoot.isRootedWithBusyBoxWithEmulator();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `DetectionResult`
[Section titled âDetectionResultâ](#detectionresult)
Result returned by root/jailbreak detection methods.
```typescript
export interface DetectionResult {
/**
* `true` when the associated heuristic detects root/jailbreak artifacts.
* `false` when no root/jailbreak indicators are found.
*
* @since 1.0.0
*/
result: boolean;
}
```
### `DeviceInfo`
[Section titled âDeviceInfoâ](#deviceinfo)
Device information collected during detection.
```typescript
export interface DeviceInfo {
/**
* Arbitrary key/value device metadata populated by the native implementation.
* Contents vary by platform and detection methods used.
*
* @since 1.0.0
*/
[key: string]: any;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-ivs-player
> Ivs player for capacitor app.
## Overview
[Section titled âOverviewâ](#overview)
Ivs player for capacitor app.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `create`
* `start`
* `cast`
* `getCastStatus`
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ------------------------------------------------------------------------------ |
| `create` | See the source definitions for current behavior. |
| `start` | See the source definitions for current behavior. |
| `cast` | See the source definitions for current behavior. |
| `getCastStatus` | See the source definitions for current behavior. |
| `pause` | See the source definitions for current behavior. |
| `delete` | See the source definitions for current behavior. |
| `getUrl` | See the source definitions for current behavior. |
| `getState` | See the source definitions for current behavior. |
| `setPlayerPosition` | See the source definitions for current behavior. |
| `getPlayerPosition` | See the source definitions for current behavior. |
| `setAutoQuality` | See the source definitions for current behavior. |
| `getAutoQuality` | See the source definitions for current behavior. |
| `setPip` | See the source definitions for current behavior. |
| `getPip` | See the source definitions for current behavior. |
| `setFrame` | Set the frame of the player view, all number have to be positive and integers. |
| `getFrame` | See the source definitions for current behavior. |
| `setBackgroundState` | See the source definitions for current behavior. |
| `getBackgroundState` | See the source definitions for current behavior. |
| `setMute` | See the source definitions for current behavior. |
| `getMute` | See the source definitions for current behavior. |
| `setQuality` | See the source definitions for current behavior. |
| `getQuality` | See the source definitions for current behavior. |
| `getQualities` | See the source definitions for current behavior. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `addListener` | Listen for start pip. |
| `addListener` | Listen for stop pip. |
| `addListener` | Listen for expend pip. |
| `addListener` | Listen for close pip. |
| `addListener` | Listen for state changes. |
| `addListener` | Listen for cue changes. |
| `addListener` | Listen for duration changes. |
| `addListener` | Listen for errors. |
| `addListener` | Listen for rebuffering. |
| `addListener` | Listen for position changes. |
| `addListener` | Listen for video size changes. |
| `addListener` | Listen for quality changes. |
| `addListener` | Listen for cast status changes. |
| `removeAllListeners` | Remove all listeners for this plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-ivs-player](https://github.com/Cap-go/capacitor-ivs-player/).
# Getting Started
> Install @capgo/capacitor-ivs-player and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-ivs-player
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `create`
[Section titled âcreateâ](#create)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.create({} as {
url: string;
pip?: boolean;
title?: string;
subtitle?: string;
cover?: string;
autoPlay?: boolean;
toBack?: boolean;
x?: number;
y?: number;
width?: number;
height?: number;
});
```
### `start`
[Section titled âstartâ](#start)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.start();
```
### `cast`
[Section titled âcastâ](#cast)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.cast();
```
### `getCastStatus`
[Section titled âgetCastStatusâ](#getcaststatus)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getCastStatus();
```
### `pause`
[Section titled âpauseâ](#pause)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.pause();
```
### `delete`
[Section titled âdeleteâ](#delete)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.delete();
```
### `getUrl`
[Section titled âgetUrlâ](#geturl)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getUrl();
```
### `getState`
[Section titled âgetStateâ](#getstate)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getState();
```
### `setPlayerPosition`
[Section titled âsetPlayerPositionâ](#setplayerposition)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setPlayerPosition();
```
### `getPlayerPosition`
[Section titled âgetPlayerPositionâ](#getplayerposition)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getPlayerPosition();
```
### `setAutoQuality`
[Section titled âsetAutoQualityâ](#setautoquality)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setAutoQuality();
```
### `getAutoQuality`
[Section titled âgetAutoQualityâ](#getautoquality)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getAutoQuality();
```
### `setPip`
[Section titled âsetPipâ](#setpip)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setPip();
```
### `getPip`
[Section titled âgetPipâ](#getpip)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getPip();
```
### `setFrame`
[Section titled âsetFrameâ](#setframe)
Set the frame of the player view, all number have to be positive and integers
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setFrame();
```
### `getFrame`
[Section titled âgetFrameâ](#getframe)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getFrame();
```
### `setBackgroundState`
[Section titled âsetBackgroundStateâ](#setbackgroundstate)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setBackgroundState({} as { backgroundState: CapacitorIvsPlayerBackgroundState });
```
### `getBackgroundState`
[Section titled âgetBackgroundStateâ](#getbackgroundstate)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getBackgroundState();
```
### `setMute`
[Section titled âsetMuteâ](#setmute)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setMute();
```
### `getMute`
[Section titled âgetMuteâ](#getmute)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getMute();
```
### `setQuality`
[Section titled âsetQualityâ](#setquality)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.setQuality();
```
### `getQuality`
[Section titled âgetQualityâ](#getquality)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getQuality();
```
### `getQualities`
[Section titled âgetQualitiesâ](#getqualities)
See the source definitions for the current contract.
```typescript
import { CapacitorIvsPlayer } from '@capgo/capacitor-ivs-player';
await CapacitorIvsPlayer.getQualities();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `CapacitorIvsPlayerState`
[Section titled âCapacitorIvsPlayerStateâ](#capacitorivsplayerstate)
```typescript
export type CapacitorIvsPlayerState = 'IDLE' | 'BUFFERING' | 'READY' | 'PLAYING' | 'ENDED' | 'UNKNOWN';
```
### `CapacitorIvsPlayerBackgroundState`
[Section titled âCapacitorIvsPlayerBackgroundStateâ](#capacitorivsplayerbackgroundstate)
```typescript
export type CapacitorIvsPlayerBackgroundState = 'PAUSED' | 'PLAYING';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-jw-player
> Playes videos from jwplayer.com.
## Overview
[Section titled âOverviewâ](#overview)
Playes videos from jwplayer.com.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `initialize` - Initialize the JW Player.
* `play` - Play a video.
* `pause` - Pause the currently playing media.
* `resume` - Resume the currently paused media.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ----------------------- | ----------------------------------------------------------- |
| `initialize` | Initialize the JW Player. |
| `play` | Play a video. |
| `pause` | Pause the currently playing media. |
| `resume` | Resume the currently paused media. |
| `stop` | Stop the currently playing media. |
| `seekTo` | Seek to a specific position in the currently playing media. |
| `setVolume` | Set the volume level. |
| `getPosition` | Get the current position in the media. |
| `getState` | Get the current player state. |
| `setSpeed` | Set the playback speed. |
| `setPlaylistIndex` | Set the current item in the playlist by index. |
| `loadPlaylist` | Load a playlist. |
| `loadPlaylistWithItems` | Load a playlist with items. |
| `getAudioTracks` | Get available audio tracks. |
| `getCurrentAudioTrack` | Get the current audio track. |
| `setCurrentAudioTrack` | Set the current audio track. |
| `getCaptions` | Get the available captions/subtitles. |
| `getCurrentCaptions` | Get the current captions/subtitles track. |
| `setCurrentCaptions` | Set the current captions/subtitles track. |
| `currentPlaylist` | Get the current playlist. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-jw-player](https://github.com/Cap-go/capacitor-jw-player/).
# Getting Started
> Install @capgo/capacitor-jw-player and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-jw-player
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `initialize`
[Section titled âinitializeâ](#initialize)
Initialize the JW Player
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.initialize({} as { licenseKey: string; playerUrl?: string });
```
### `play`
[Section titled âplayâ](#play)
Play a video
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.play({} as { mediaUrl: string; mediaType: 'video' | 'playlist'; autostart?: boolean });
```
### `pause`
[Section titled âpauseâ](#pause)
Pause the currently playing media
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.pause();
```
### `resume`
[Section titled âresumeâ](#resume)
Resume the currently paused media
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.resume();
```
### `stop`
[Section titled âstopâ](#stop)
Stop the currently playing media
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.stop();
```
### `seekTo`
[Section titled âseekToâ](#seekto)
Seek to a specific position in the currently playing media
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.seekTo({} as { time: number });
```
### `setVolume`
[Section titled âsetVolumeâ](#setvolume)
Set the volume level
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.setVolume({} as { volume: number });
```
### `getPosition`
[Section titled âgetPositionâ](#getposition)
Get the current position in the media
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getPosition();
```
### `getState`
[Section titled âgetStateâ](#getstate)
Get the current player state
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getState();
```
### `setSpeed`
[Section titled âsetSpeedâ](#setspeed)
Set the playback speed
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.setSpeed({} as { speed: number });
```
### `setPlaylistIndex`
[Section titled âsetPlaylistIndexâ](#setplaylistindex)
Set the current item in the playlist by index
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.setPlaylistIndex({} as { index: number });
```
### `loadPlaylist`
[Section titled âloadPlaylistâ](#loadplaylist)
Load a playlist
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.loadPlaylist({} as { playlistUrl: string });
```
### `loadPlaylistWithItems`
[Section titled âloadPlaylistWithItemsâ](#loadplaylistwithitems)
Load a playlist with items
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.loadPlaylistWithItems({} as { playlist: any[] });
```
### `getAudioTracks`
[Section titled âgetAudioTracksâ](#getaudiotracks)
Get available audio tracks
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getAudioTracks();
```
### `getCurrentAudioTrack`
[Section titled âgetCurrentAudioTrackâ](#getcurrentaudiotrack)
Get the current audio track
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getCurrentAudioTrack();
```
### `setCurrentAudioTrack`
[Section titled âsetCurrentAudioTrackâ](#setcurrentaudiotrack)
Set the current audio track
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.setCurrentAudioTrack({} as { index: number });
```
### `getCaptions`
[Section titled âgetCaptionsâ](#getcaptions)
Get the available captions/subtitles
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getCaptions();
```
### `getCurrentCaptions`
[Section titled âgetCurrentCaptionsâ](#getcurrentcaptions)
Get the current captions/subtitles track
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.getCurrentCaptions();
```
### `setCurrentCaptions`
[Section titled âsetCurrentCaptionsâ](#setcurrentcaptions)
Set the current captions/subtitles track
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.setCurrentCaptions({} as { index: number });
```
### `currentPlaylist`
[Section titled âcurrentPlaylistâ](#currentplaylist)
Get the current playlist
```typescript
import { JwPlayer } from '@capgo/capacitor-jw-player';
await JwPlayer.currentPlaylist();
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-keep-awake
> Capacitor Keep Awake Plugin for preventing the device screen from dimming/sleeping.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Keep Awake Plugin for preventing the device screen from dimming/sleeping.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `keepAwake` - Prevent the device from dimming the screen.
* `allowSleep` - Allow the device to dim the screen (disable keep awake).
* `isSupported` - Check if the keep awake feature is supported on the current platform.
* `isKeptAwake` - Check if the device is currently being kept awake.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------- |
| `keepAwake` | Prevent the device from dimming the screen. |
| `allowSleep` | Allow the device to dim the screen (disable keep awake). |
| `isSupported` | Check if the keep awake feature is supported on the current platform. |
| `isKeptAwake` | Check if the device is currently being kept awake. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-keep-awake](https://github.com/Cap-go/capacitor-keep-awake/).
# Getting Started
> Install @capgo/capacitor-keep-awake and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-keep-awake
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { KeepAwake } from '@capgo/capacitor-keep-awake';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `keepAwake`
[Section titled âkeepAwakeâ](#keepawake)
Prevent the device from dimming the screen.
```typescript
import { KeepAwake } from '@capgo/capacitor-keep-awake';
await KeepAwake.keepAwake();
console.log('Screen will stay awake');
```
### `allowSleep`
[Section titled âallowSleepâ](#allowsleep)
Allow the device to dim the screen (disable keep awake).
```typescript
import { KeepAwake } from '@capgo/capacitor-keep-awake';
await KeepAwake.allowSleep();
console.log('Screen can now dim');
```
### `isSupported`
[Section titled âisSupportedâ](#issupported)
Check if the keep awake feature is supported on the current platform.
```typescript
import { KeepAwake } from '@capgo/capacitor-keep-awake';
const { isSupported } = await KeepAwake.isSupported();
if (isSupported) {
console.log('Keep awake is supported');
}
```
### `isKeptAwake`
[Section titled âisKeptAwakeâ](#iskeptawake)
Check if the device is currently being kept awake.
```typescript
import { KeepAwake } from '@capgo/capacitor-keep-awake';
const { isKeptAwake } = await KeepAwake.isKeptAwake();
console.log('Is kept awake:', isKeptAwake);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `IsSupportedResult`
[Section titled âIsSupportedResultâ](#issupportedresult)
Result of the isSupported() method.
```typescript
export interface IsSupportedResult {
/**
* Whether keep awake is supported on the current platform.
*
* @since 1.0.0
*/
isSupported: boolean;
}
```
### `IsKeptAwakeResult`
[Section titled âIsKeptAwakeResultâ](#iskeptawakeresult)
Result of the isKeptAwake() method.
```typescript
export interface IsKeptAwakeResult {
/**
* Whether the device is currently being kept awake.
*
* @since 1.0.0
*/
isKeptAwake: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-launch-navigator
> Main plugin interface.
## Overview
[Section titled âOverviewâ](#overview)
Main plugin interface.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `navigate` - Navigate to a location using latitude and longitude.
* `isAppAvailable` - Check if a specific navigation app is available.
* `getAvailableApps` - Get list of available navigation apps on the device.
* `getSupportedApps` - Get list of supported apps for the current platform.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ---------------------------------------------------- |
| `navigate` | Navigate to a location using latitude and longitude. |
| `isAppAvailable` | Check if a specific navigation app is available. |
| `getAvailableApps` | Get list of available navigation apps on the device. |
| `getSupportedApps` | Get list of supported apps for the current platform. |
| `getDefaultApp` | Get the name of the default app for navigation. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-launch-navigator](https://github.com/Cap-go/capacitor-launch-navigator/).
# Getting Started
> Install @capgo/capacitor-launch-navigator and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-launch-navigator
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `navigate`
[Section titled ânavigateâ](#navigate)
Navigate to a location using latitude and longitude
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
await LaunchNavigator.navigate({} as {
/**
* Destination coordinates [latitude, longitude]
*/
destination: [number, number];
/**
* Optional navigation options
*/
options?: NavigateOptions;
});
```
### `isAppAvailable`
[Section titled âisAppAvailableâ](#isappavailable)
Check if a specific navigation app is available
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
await LaunchNavigator.isAppAvailable({} as {
/**
* App identifier to check
*/
app: IOSNavigationApp | AndroidNavigationApp | string;
});
```
### `getAvailableApps`
[Section titled âgetAvailableAppsâ](#getavailableapps)
Get list of available navigation apps on the device
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
await LaunchNavigator.getAvailableApps();
```
### `getSupportedApps`
[Section titled âgetSupportedAppsâ](#getsupportedapps)
Get list of supported apps for the current platform
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
await LaunchNavigator.getSupportedApps();
```
### `getDefaultApp`
[Section titled âgetDefaultAppâ](#getdefaultapp)
Get the name of the default app for navigation
```typescript
import { LaunchNavigator } from '@capgo/capacitor-launch-navigator';
await LaunchNavigator.getDefaultApp();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `NavigateOptions`
[Section titled âNavigateOptionsâ](#navigateoptions)
Options for navigation.
```typescript
export interface NavigateOptions {
/**
* Starting location coordinates [latitude, longitude]
*/
start?: [number, number];
/**
* Starting location name
*/
startName?: string;
/**
* Destination name (will be ignored since we only support coordinates)
*/
destinationName?: string;
/**
* Transport mode
*/
transportMode?: TransportMode;
/**
* Specific app to launch (if not specified, will use default or prompt)
*/
app?: IOSNavigationApp | AndroidNavigationApp | string;
/**
* Launch mode
*/
launchMode?: LaunchMode;
/**
* Additional parameters specific to certain apps
*/
extras?: Record;
/**
* Enable debug logging
*/
enableDebug?: boolean;
}
```
### `IOSNavigationApp`
[Section titled âIOSNavigationAppâ](#iosnavigationapp)
Available navigation apps for iOS.
```typescript
export enum IOSNavigationApp {
APPLE_MAPS = 'apple_maps',
GOOGLE_MAPS = 'google_maps',
WAZE = 'waze',
CITYMAPPER = 'citymapper',
GARMIN_NAVIGON = 'garmin_navigon',
TRANSIT_APP = 'transit_app',
YANDEX_NAVIGATOR = 'yandex',
UBER = 'uber',
TOMTOM = 'tomtom',
SYGIC = 'sygic',
HERE_MAPS = 'here',
MOOVIT = 'moovit',
LYFT = 'lyft',
MAPS_ME = 'mapsme',
CABIFY = 'cabify',
BAIDU = 'baidu',
GAODE = 'gaode',
TAXI_99 = '99taxi',
}
```
### `AndroidNavigationApp`
[Section titled âAndroidNavigationAppâ](#androidnavigationapp)
Available navigation apps for Android.
```typescript
export enum AndroidNavigationApp {
GOOGLE_MAPS = 'google_maps',
WAZE = 'waze',
CITYMAPPER = 'citymapper',
UBER = 'uber',
YANDEX = 'yandex',
SYGIC = 'sygic',
HERE_MAPS = 'here',
MOOVIT = 'moovit',
LYFT = 'lyft',
MAPS_ME = 'mapsme',
CABIFY = 'cabify',
BAIDU = 'baidu',
GAODE = 'gaode',
}
```
### `AvailableApp`
[Section titled âAvailableAppâ](#availableapp)
Result of checking app availability.
```typescript
export interface AvailableApp {
/**
* App identifier
*/
app: string;
/**
* Display name of the app
*/
name: string;
/**
* Whether the app is available on the device
*/
available: boolean;
}
```
### `TransportMode`
[Section titled âTransportModeâ](#transportmode)
Transport modes.
```typescript
export enum TransportMode {
DRIVING = 'driving',
WALKING = 'walking',
BICYCLING = 'bicycling',
TRANSIT = 'transit',
}
```
### `LaunchMode`
[Section titled âLaunchModeâ](#launchmode)
Launch modes.
```typescript
export enum LaunchMode {
MAPS = 'maps',
TURN_BY_TURN = 'turn_by_turn',
GEO = 'geo',
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-light-sensor
> Capacitor plugin for accessing the device's ambient light sensor.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for accessing the deviceâs ambient light sensor.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isAvailable` - Check if the light sensor is available on the current device. You should always check sensor availability before attempting to use it.
* `start` - Start listening to light sensor updates. This will begin sensor measurements at the specified interval. Use `addListener` to receive the sensor data.
* `stop` - Stop listening to light sensor updates. This will stop the sensor and conserve battery.
* `checkPermissions` - Check the current permission status for high sampling rate sensors. On Android 12+, the HIGH\_SAMPLING\_RATE\_SENSORS permission is required for sensor update intervals below 200ms.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isAvailable` | Check if the light sensor is available on the current device. You should always check sensor availability before attempting to use it. |
| `start` | Start listening to light sensor updates. This will begin sensor measurements at the specified interval. Use `addListener` to receive the sensor data. |
| `stop` | Stop listening to light sensor updates. This will stop the sensor and conserve battery. |
| `addListener` | Add a listener for light sensor change events. The listener will be called whenever new sensor data is available. |
| `removeAllListeners` | Remove all listeners for light sensor events. |
| `checkPermissions` | Check the current permission status for high sampling rate sensors. On Android 12+, the HIGH\_SAMPLING\_RATE\_SENSORS permission is required for sensor update intervals below 200ms. |
| `requestPermissions` | Request permission for high sampling rate sensors. On Android 12+, this requests the HIGH\_SAMPLING\_RATE\_SENSORS permission. |
| `getPluginVersion` | Get the current version of the plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-light-sensor](https://github.com/Cap-go/capacitor-light-sensor/).
# Getting Started
> Install @capgo/capacitor-light-sensor and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-light-sensor
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Check if the light sensor is available on the current device. You should always check sensor availability before attempting to use it.
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
const { available } = await LightSensor.isAvailable();
```
### `start`
[Section titled âstartâ](#start)
Start listening to light sensor updates. This will begin sensor measurements at the specified interval. Use `addListener` to receive the sensor data.
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
await LightSensor.start({ updateInterval: 500 });
```
### `stop`
[Section titled âstopâ](#stop)
Stop listening to light sensor updates. This will stop the sensor and conserve battery.
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
await LightSensor.stop();
```
### `checkPermissions`
[Section titled âcheckPermissionsâ](#checkpermissions)
Check the current permission status for high sampling rate sensors. On Android 12+, the HIGH\_SAMPLING\_RATE\_SENSORS permission is required for sensor update intervals below 200ms.
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
const status = await LightSensor.checkPermissions();
```
### `requestPermissions`
[Section titled ârequestPermissionsâ](#requestpermissions)
Request permission for high sampling rate sensors. On Android 12+, this requests the HIGH\_SAMPLING\_RATE\_SENSORS permission.
```typescript
import { LightSensor } from '@capgo/capacitor-light-sensor';
const status = await LightSensor.requestPermissions();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `IsAvailableResult`
[Section titled âIsAvailableResultâ](#isavailableresult)
Result indicating whether the sensor is available.
```typescript
export interface IsAvailableResult {
/**
* Whether the light sensor is available on this device.
* Always false on iOS as the light sensor API is not available.
*
* @since 0.0.1
*/
available: boolean;
}
```
### `StartOptions`
[Section titled âStartOptionsâ](#startoptions)
Options for starting the light sensor listener.
```typescript
export interface StartOptions {
/**
* The desired interval between sensor updates in milliseconds.
* On Android 12+, there's a minimum interval of 200ms unless the app
* has the HIGH_SAMPLING_RATE_SENSORS permission.
*
* @default 200
* @since 0.0.1
*/
updateInterval?: number;
}
```
### `LightSensorCallback`
[Section titled âLightSensorCallbackâ](#lightsensorcallback)
Callback function for light sensor updates.
```typescript
export type LightSensorCallback = (measurement: LightSensorMeasurement) => void;
```
### `PermissionStatus`
[Section titled âPermissionStatusâ](#permissionstatus)
Result of a permission request or check.
```typescript
export interface PermissionStatus {
/**
* Whether the high sampling rate sensor permission is granted.
* On Android 12+, this permission is required for update intervals below 200ms.
*
* @since 0.0.1
*/
highSamplingRate: 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
}
```
### `VersionResult`
[Section titled âVersionResultâ](#versionresult)
Plugin version information.
```typescript
export interface VersionResult {
/**
* The current version of the plugin.
*
* @since 0.0.1
*/
version: string;
}
```
### `LightSensorMeasurement`
[Section titled âLightSensorMeasurementâ](#lightsensormeasurement)
A single light sensor measurement.
```typescript
export interface LightSensorMeasurement {
/**
* Ambient light level in lux (lx).
*
* @since 0.0.1
*/
illuminance: number;
/**
* Timestamp of the measurement in seconds since epoch.
*
* @since 0.0.1
*/
timestamp: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-live-activities
> Capacitor Live Activities Plugin interface for managing iOS Live Activities.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Live Activities Plugin interface for managing iOS Live Activities.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `areActivitiesSupported` - Check if Live Activities are supported on this device. Requires iOS 16.1+ and device support.
* `startActivity` - Start a new Live Activity with the specified layout and data.
* `updateActivity` - Update an existing Live Activity with new data.
* `endActivity` - End a Live Activity.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `areActivitiesSupported` | Check if Live Activities are supported on this device. Requires iOS 16.1+ and device support. |
| `startActivity` | Start a new Live Activity with the specified layout and data. |
| `updateActivity` | Update an existing Live Activity with new data. |
| `endActivity` | End a Live Activity. |
| `getAllActivities` | Get all currently active Live Activities. |
| `saveImage` | Save an image to the shared App Group container for use in Live Activities. Images must be saved to the shared container to be accessible from the widget extension. |
| `removeImage` | Remove a saved image from the shared container. |
| `listImages` | List all saved images in the shared container. |
| `cleanupImages` | Remove all saved images from the shared container. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `startTimerSequence` | Start a timer sequence for workouts/sports. On iOS: Shows in Live Activity and Dynamic Island On Android: Shows as a foreground notification with timer. |
| `pauseTimerSequence` | Pause the timer sequence. |
| `resumeTimerSequence` | Resume a paused timer sequence. |
| `stopTimerSequence` | Stop and dismiss the timer sequence. |
| `skipTimerStep` | Skip to the next step in the sequence. |
| `previousTimerStep` | Go back to the previous step in the sequence. |
| `getTimerState` | Get the current state of a timer sequence. |
| `addListener` | Add a listener for timer sequence events. Events include: stepChange, complete, tick, paused, resumed, stopped, loopComplete. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-live-activities](https://github.com/Cap-go/capacitor-live-activities/).
# Getting Started
> Install @capgo/capacitor-live-activities and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-live-activities
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `areActivitiesSupported`
[Section titled âareActivitiesSupportedâ](#areactivitiessupported)
Check if Live Activities are supported on this device. Requires iOS 16.1+ and device support.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { supported, reason } = await CapgoLiveActivities.areActivitiesSupported();
if (supported) {
console.log('Live Activities are supported!');
} else {
console.log('Not supported:', reason);
}
```
### `startActivity`
[Section titled âstartActivityâ](#startactivity)
Start a new Live Activity with the specified layout and data.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { activityId } = await CapgoLiveActivities.startActivity({
layout: {
type: 'container',
direction: 'horizontal',
children: [
{ type: 'text', content: 'Order #{{orderNumber}}', fontSize: 16, fontWeight: 'bold' },
{ type: 'text', content: '{{status}}', fontSize: 14, color: '#666666' }
]
},
dynamicIslandLayout: {
expanded: {
leading: { type: 'image', source: 'sfSymbol', value: 'box.truck' },
trailing: { type: 'text', content: '{{eta}}' },
center: { type: 'text', content: '{{status}}' },
bottom: { type: 'progress', value: 'progress' }
},
compactLeading: { type: 'image', source: 'sfSymbol', value: 'box.truck' },
compactTrailing: { type: 'text', content: '{{eta}}' },
minimal: { type: 'image', source: 'sfSymbol', value: 'box.truck' }
},
data: {
orderNumber: '12345',
status: 'On the way',
eta: '10 min',
progress: 0.6
}
});
console.log('Started activity:', activityId);
```
### `updateActivity`
[Section titled âupdateActivityâ](#updateactivity)
Update an existing Live Activity with new data.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.updateActivity({
activityId: 'abc123',
data: {
status: 'Arrived!',
eta: 'Now',
progress: 1.0
},
alertConfiguration: {
title: 'Delivery Update',
body: 'Your order has arrived!'
}
});
```
### `endActivity`
[Section titled âendActivityâ](#endactivity)
End a Live Activity.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.endActivity({
activityId: 'abc123',
data: { status: 'Delivered' },
dismissalPolicy: 'after',
dismissAfter: Date.now() + 3600000 // 1 hour from now
});
```
### `getAllActivities`
[Section titled âgetAllActivitiesâ](#getallactivities)
Get all currently active Live Activities.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { activities } = await CapgoLiveActivities.getAllActivities();
activities.forEach(activity => {
console.log(`Activity ${activity.activityId}: ${activity.state}`);
});
```
### `saveImage`
[Section titled âsaveImageâ](#saveimage)
Save an image to the shared App Group container for use in Live Activities. Images must be saved to the shared container to be accessible from the widget extension.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { success, imageName } = await CapgoLiveActivities.saveImage({
imageData: 'base64EncodedImageData...',
name: 'product-image',
compressionQuality: 0.8
});
// Use in layout with: { type: 'image', source: 'saved', value: imageName }
```
### `removeImage`
[Section titled âremoveImageâ](#removeimage)
Remove a saved image from the shared container.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { success } = await CapgoLiveActivities.removeImage({ name: 'product-image' });
```
### `listImages`
[Section titled âlistImagesâ](#listimages)
List all saved images in the shared container.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { images } = await CapgoLiveActivities.listImages();
console.log('Saved images:', images);
```
### `cleanupImages`
[Section titled âcleanupImagesâ](#cleanupimages)
Remove all saved images from the shared container.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.cleanupImages();
```
### `startTimerSequence`
[Section titled âstartTimerSequenceâ](#starttimersequence)
Start a timer sequence for workouts/sports. On iOS: Shows in Live Activity and Dynamic Island On Android: Shows as a foreground notification with timer
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const { sequenceId } = await CapgoLiveActivities.startTimerSequence({
title: 'HIIT Workout',
steps: [
{ duration: 30, title: 'Jumping Jacks', subtitle: 'Warm up', color: '#FF6B00', icon: 'figure.jumprope' },
{ duration: 10, title: 'Rest', color: '#00C853', icon: 'pause.circle' },
{ duration: 45, title: 'Burpees', subtitle: 'High intensity', color: '#FF0000', icon: 'flame.fill' },
{ duration: 15, title: 'Rest', color: '#00C853', icon: 'pause.circle' },
{ duration: 45, title: 'Mountain Climbers', color: '#FF0000', icon: 'figure.run' },
{ duration: 15, title: 'Rest', color: '#00C853', icon: 'pause.circle' },
],
loop: true,
loopCount: 3,
soundEnabled: true,
vibrateEnabled: true,
countdownBeeps: true,
tapUrl: 'myapp://workout/hiit'
});
```
### `pauseTimerSequence`
[Section titled âpauseTimerSequenceâ](#pausetimersequence)
Pause the timer sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.pauseTimerSequence({ sequenceId: 'abc123' });
```
### `resumeTimerSequence`
[Section titled âresumeTimerSequenceâ](#resumetimersequence)
Resume a paused timer sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.resumeTimerSequence({ sequenceId: 'abc123' });
```
### `stopTimerSequence`
[Section titled âstopTimerSequenceâ](#stoptimersequence)
Stop and dismiss the timer sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.stopTimerSequence({ sequenceId: 'abc123' });
```
### `skipTimerStep`
[Section titled âskipTimerStepâ](#skiptimerstep)
Skip to the next step in the sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.skipTimerStep({ sequenceId: 'abc123' });
```
### `previousTimerStep`
[Section titled âpreviousTimerStepâ](#previoustimerstep)
Go back to the previous step in the sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
await CapgoLiveActivities.previousTimerStep({ sequenceId: 'abc123' });
```
### `getTimerState`
[Section titled âgetTimerStateâ](#gettimerstate)
Get the current state of a timer sequence.
```typescript
import { CapgoLiveActivities } from '@capgo/capacitor-live-activities';
const state = await CapgoLiveActivities.getTimerState({ sequenceId: 'abc123' });
console.log(`Step ${state.currentStepIndex + 1}/${state.totalSteps}: ${state.currentStep.title}`);
console.log(`Time remaining: ${state.remainingSeconds}s`);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `AreActivitiesSupportedResult`
[Section titled âAreActivitiesSupportedResultâ](#areactivitiessupportedresult)
Result of checking if activities are supported.
```typescript
export interface AreActivitiesSupportedResult {
/** Whether Live Activities are supported on this device */
supported: boolean;
/** Reason if not supported */
reason?: string;
}
```
### `StartActivityOptions`
[Section titled âStartActivityOptionsâ](#startactivityoptions)
Options for starting a Live Activity.
```typescript
export interface StartActivityOptions {
/** Main activity layout (lock screen widget) */
layout: ActivityLayout;
/** Dynamic Island layout configuration */
dynamicIslandLayout: DynamicIslandLayout;
/** Activity behavior settings */
behavior?: LiveActivitiesBehavior;
/** Dynamic data for the activity */
data: Record;
/** Stale date timestamp (activity becomes stale after this) */
staleDate?: number;
/** Relevance score for activity ordering (0-100) */
relevanceScore?: number;
}
```
### `StartActivityResult`
[Section titled âStartActivityResultâ](#startactivityresult)
Result of starting an activity.
```typescript
export interface StartActivityResult {
/** Unique activity identifier */
activityId: string;
}
```
### `UpdateActivityOptions`
[Section titled âUpdateActivityOptionsâ](#updateactivityoptions)
Options for updating a Live Activity.
```typescript
export interface UpdateActivityOptions {
/** Activity ID to update */
activityId: string;
/** Updated data */
data: Record;
/** Optional alert to show with update */
alertConfiguration?: ActivityAlertConfiguration;
/** Updated stale date */
staleDate?: number;
/** Updated relevance score */
relevanceScore?: number;
}
```
### `EndActivityOptions`
[Section titled âEndActivityOptionsâ](#endactivityoptions)
Options for ending a Live Activity.
```typescript
export interface EndActivityOptions {
/** Activity ID to end */
activityId: string;
/** Final data to display */
data?: Record;
/** Dismissal policy */
dismissalPolicy?: 'immediate' | 'default' | 'after';
/** Dismiss after timestamp (when dismissalPolicy is 'after') */
dismissAfter?: number;
}
```
### `GetAllActivitiesResult`
[Section titled âGetAllActivitiesResultâ](#getallactivitiesresult)
Result of getAllActivities.
```typescript
export interface GetAllActivitiesResult {
/** List of activities */
activities: ActivityInfo[];
}
```
### `SaveImageOptions`
[Section titled âSaveImageOptionsâ](#saveimageoptions)
Options for saving an image.
```typescript
export interface SaveImageOptions {
/** Base64 encoded image data */
imageData: string;
/** Name to save the image as */
name: string;
/** JPEG compression quality (0-1, default 0.8) */
compressionQuality?: number;
}
```
### `SaveImageResult`
[Section titled âSaveImageResultâ](#saveimageresult)
Result of saving an image.
```typescript
export interface SaveImageResult {
/** Whether the save was successful */
success: boolean;
/** Saved image name */
imageName: string;
}
```
### `RemoveImageOptions`
[Section titled âRemoveImageOptionsâ](#removeimageoptions)
Options for removing an image.
```typescript
export interface RemoveImageOptions {
/** Name of the image to remove */
name: string;
}
```
### `RemoveImageResult`
[Section titled âRemoveImageResultâ](#removeimageresult)
Result of removing an image.
```typescript
export interface RemoveImageResult {
/** Whether the removal was successful */
success: boolean;
}
```
### `ListImagesResult`
[Section titled âListImagesResultâ](#listimagesresult)
Result of listing images.
```typescript
export interface ListImagesResult {
/** List of saved image names */
images: string[];
}
```
### `TimerSequenceOptions`
[Section titled âTimerSequenceOptionsâ](#timersequenceoptions)
Options for starting a timer sequence.
```typescript
export interface TimerSequenceOptions {
/** Array of steps in the sequence */
steps: TimerStep[];
/** Overall title for the sequence (e.g., "HIIT Workout", "Tabata") */
title?: string;
/** Whether to loop the sequence when complete */
loop?: boolean;
/** Number of times to loop (if loop is true, 0 means infinite) */
loopCount?: number;
/** Play sound on step change (default: true) */
soundEnabled?: boolean;
/** Vibrate on step change (default: true) */
vibrateEnabled?: boolean;
/** Play countdown beeps in last 3 seconds (default: true) */
countdownBeeps?: boolean;
/** Deep link URL when tapping the notification/activity */
tapUrl?: string;
/** Keep screen on during timer (Android only, default: false) */
keepScreenOn?: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-live-reload
> Capacitor plugin to live reload Capacitor apps from a remote Vite dev server.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin to live reload Capacitor apps from a remote Vite dev server.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `configureServer` - Store remote dev server settings used for subsequent connections.
* `connect` - Establish a WebSocket connection if one is not already active.
* `disconnect` - Close the current WebSocket connection and disable auto reconnect.
* `getStatus` - Returns the current connection status.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | ----------------------------------------------------------------------------------- |
| `configureServer` | Store remote dev server settings used for subsequent connections. |
| `connect` | Establish a WebSocket connection if one is not already active. |
| `disconnect` | Close the current WebSocket connection and disable auto reconnect. |
| `getStatus` | Returns the current connection status. |
| `reload` | Trigger a full reload of the Capacitor WebView. |
| `reloadFile` | Reload a single file/module if the runtime supports it (falls back to full reload). |
| `addListener` | Listen to incoming reload events emitted by the server. |
| `addListener` | Listen to socket status changes (connected/disconnected). |
| `removeAllListeners` | Remove all registered listeners. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-live-reload](https://github.com/Cap-go/capacitor-live-reload/).
# Getting Started
> Install @capgo/capacitor-live-reload and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-live-reload
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `configureServer`
[Section titled âconfigureServerâ](#configureserver)
Store remote dev server settings used for subsequent connections.
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.configureServer({} as ConfigureServerOptions);
```
### `connect`
[Section titled âconnectâ](#connect)
Establish a WebSocket connection if one is not already active.
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.connect();
```
### `disconnect`
[Section titled âdisconnectâ](#disconnect)
Close the current WebSocket connection and disable auto reconnect.
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.disconnect();
```
### `getStatus`
[Section titled âgetStatusâ](#getstatus)
Returns the current connection status.
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.getStatus();
```
### `reload`
[Section titled âreloadâ](#reload)
Trigger a full reload of the Capacitor WebView.
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.reload();
```
### `reloadFile`
[Section titled âreloadFileâ](#reloadfile)
Reload a single file/module if the runtime supports it (falls back to full reload).
```typescript
import { LiveReload } from '@capgo/capacitor-live-reload';
await LiveReload.reloadFile({} as FileUpdatePayload);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ConfigureServerOptions`
[Section titled âConfigureServerOptionsâ](#configureserveroptions)
```typescript
export interface ConfigureServerOptions {
/**
* Base URL for the dev server (e.g. https://dev.local:5173).
* When a connection is established the Capacitor WebView navigates to this URL.
*/
url: string;
/** Optional WebSocket path override when different from /ws. */
websocketPath?: string;
/** Extra headers sent when creating the WebSocket connection. */
headers?: Record;
/** Automatically reconnect when the socket closes unexpectedly. Default: true. */
autoReconnect?: boolean;
/** Delay (ms) between reconnection attempts. Default: 2000. */
reconnectInterval?: number;
}
```
### `LiveReloadStatus`
[Section titled âLiveReloadStatusâ](#livereloadstatus)
```typescript
export interface LiveReloadStatus {
connected: boolean;
url?: string;
}
```
### `FileUpdatePayload`
[Section titled âFileUpdatePayloadâ](#fileupdatepayload)
```typescript
export interface FileUpdatePayload {
path: string;
hash?: string;
}
```
### `LiveReloadEventCallback`
[Section titled âLiveReloadEventCallbackâ](#livereloadeventcallback)
```typescript
export type LiveReloadEventCallback = (event: LiveReloadEventPayload) => void;
```
### `LiveReloadStatusCallback`
[Section titled âLiveReloadStatusCallbackâ](#livereloadstatuscallback)
```typescript
export type LiveReloadStatusCallback = (status: LiveReloadStatus) => void;
```
### `LiveReloadEventPayload`
[Section titled âLiveReloadEventPayloadâ](#livereloadeventpayload)
```typescript
export interface LiveReloadEventPayload {
type: LiveReloadMessageType;
/** Populated when type === 'file-update'. */
file?: FileUpdatePayload;
/** Optional human-readable message for errors or status changes. */
message?: string;
}
```
### `LiveReloadMessageType`
[Section titled âLiveReloadMessageTypeâ](#livereloadmessagetype)
```typescript
export type LiveReloadMessageType = 'full-reload' | 'file-update' | 'error' | 'connected' | 'disconnected';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-llm
> LLM Plugin interface for interacting with on-device language models.
## Overview
[Section titled âOverviewâ](#overview)
LLM Plugin interface for interacting with on-device language models.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `createChat` - Creates a new chat session.
* `sendMessage` - Sends a message to the AI in a specific chat session.
* `getReadiness` - Gets the readiness status of the LLM.
* `setModel` - Sets the model configuration - iOS: Use âApple Intelligenceâ as path for system model, or provide path to MediaPipe model - Android: Path to a MediaPipe model file (in assets or files directory).
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createChat` | Creates a new chat session. |
| `sendMessage` | Sends a message to the AI in a specific chat session. |
| `getReadiness` | Gets the readiness status of the LLM. |
| `setModel` | Sets the model configuration - iOS: Use âApple Intelligenceâ as path for system model, or provide path to MediaPipe model - Android: Path to a MediaPipe model file (in assets or files directory). |
| `downloadModel` | Downloads a model from a URL and saves it to the appropriate location - iOS: Downloads to the appâs documents directory - Android: Downloads to the appâs files directory. |
| `addListener` | Adds a listener for text received from AI. |
| `addListener` | Adds a listener for AI completion events. |
| `addListener` | Adds a listener for model download progress events. |
| `addListener` | Adds a listener for readiness status changes. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-llm](https://github.com/Cap-go/capacitor-llm/).
# Getting Started
> Install @capgo/capacitor-llm and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-llm
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `createChat`
[Section titled âcreateChatâ](#createchat)
Creates a new chat session
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
await CapgoLLM.createChat();
```
### `sendMessage`
[Section titled âsendMessageâ](#sendmessage)
Sends a message to the AI in a specific chat session
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
await CapgoLLM.sendMessage({} as { chatId: string; message: string });
```
### `getReadiness`
[Section titled âgetReadinessâ](#getreadiness)
Gets the readiness status of the LLM
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
await CapgoLLM.getReadiness();
```
### `setModel`
[Section titled âsetModelâ](#setmodel)
Sets the model configuration
* iOS: Use âApple Intelligenceâ as path for system model, or provide path to MediaPipe model
* Android: Path to a MediaPipe model file (in assets or files directory)
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
await CapgoLLM.setModel({} as ModelOptions);
```
### `downloadModel`
[Section titled âdownloadModelâ](#downloadmodel)
Downloads a model from a URL and saves it to the appropriate location
* iOS: Downloads to the appâs documents directory
* Android: Downloads to the appâs files directory
```typescript
import { CapgoLLM } from '@capgo/capacitor-llm';
await CapgoLLM.downloadModel({} as DownloadModelOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ModelOptions`
[Section titled âModelOptionsâ](#modeloptions)
Model configuration options.
```typescript
export interface ModelOptions {
/** Model path or "Apple Intelligence" for iOS system model */
path: string;
/** Model file type/extension (e.g., "task", "bin", "litertlm"). If not provided, will be extracted from path. */
modelType?: string;
/** Maximum number of tokens the model handles */
maxTokens?: number;
/** Number of tokens the model considers at each step */
topk?: number;
/** Amount of randomness in generation (0.0-1.0) */
temperature?: number;
/** Random seed for generation */
randomSeed?: number;
}
```
### `DownloadModelOptions`
[Section titled âDownloadModelOptionsâ](#downloadmodeloptions)
Options for downloading a model.
```typescript
export interface DownloadModelOptions {
/** URL of the model file to download */
url: string;
/** Optional: URL of companion file (e.g., .litertlm for Android) */
companionUrl?: string;
/** Optional: Custom filename (defaults to filename from URL) */
filename?: string;
}
```
### `DownloadModelResult`
[Section titled âDownloadModelResultâ](#downloadmodelresult)
Result of model download.
```typescript
export interface DownloadModelResult {
/** Path where the model was saved */
path: string;
/** Path where the companion file was saved (if applicable) */
companionPath?: string;
}
```
### `TextFromAiEvent`
[Section titled âTextFromAiEventâ](#textfromaievent)
Event data for text received from AI.
```typescript
export interface TextFromAiEvent {
/** The text content from AI - this is an incremental chunk, not the full text */
text: string;
/** The chat session ID */
chatId: string;
/** Whether this is a complete chunk (true) or partial streaming data (false) */
isChunk?: boolean;
}
```
### `AiFinishedEvent`
[Section titled âAiFinishedEventâ](#aifinishedevent)
Event data for AI completion.
```typescript
export interface AiFinishedEvent {
/** The chat session ID that finished */
chatId: string;
}
```
### `DownloadProgressEvent`
[Section titled âDownloadProgressEventâ](#downloadprogressevent)
Event data for download progress.
```typescript
export interface DownloadProgressEvent {
/** Percentage of download completed (0-100) */
progress: number;
/** Total bytes to download */
totalBytes?: number;
/** Bytes downloaded so far */
downloadedBytes?: number;
}
```
### `ReadinessChangeEvent`
[Section titled âReadinessChangeEventâ](#readinesschangeevent)
Event data for readiness status changes.
```typescript
export interface ReadinessChangeEvent {
/** The readiness status */
readiness: string;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-media-session
> Capacitor plugin to expose media session controls of the device.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin to expose media session controls of the device.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `setMetadata` - Sets metadata of the currently playing media.
* `setPlaybackState` - Updates the playback state of the media session.
* `setActionHandler` - Registers a handler for a media session action.
* `setPositionState` - Updates position state for the active media session.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ---------------------------------------------------- |
| `setMetadata` | Sets metadata of the currently playing media. |
| `setPlaybackState` | Updates the playback state of the media session. |
| `setActionHandler` | Registers a handler for a media session action. |
| `setPositionState` | Updates position state for the active media session. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-media-session](https://github.com/Cap-go/capacitor-media-session/).
# Getting Started
> Install @capgo/capacitor-media-session and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-media-session
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { MediaSession } from '@capgo/capacitor-media-session';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `setMetadata`
[Section titled âsetMetadataâ](#setmetadata)
Sets metadata of the currently playing media.
```typescript
import { MediaSession } from '@capgo/capacitor-media-session';
await MediaSession.setMetadata({} as MetadataOptions);
```
### `setPlaybackState`
[Section titled âsetPlaybackStateâ](#setplaybackstate)
Updates the playback state of the media session.
```typescript
import { MediaSession } from '@capgo/capacitor-media-session';
await MediaSession.setPlaybackState({} as PlaybackStateOptions);
```
### `setActionHandler`
[Section titled âsetActionHandlerâ](#setactionhandler)
Registers a handler for a media session action.
```typescript
import { MediaSession } from '@capgo/capacitor-media-session';
await MediaSession.setActionHandler({} as ActionHandlerOptions, {} as ActionHandler | null);
```
### `setPositionState`
[Section titled âsetPositionStateâ](#setpositionstate)
Updates position state for the active media session.
```typescript
import { MediaSession } from '@capgo/capacitor-media-session';
await MediaSession.setPositionState({} as PositionStateOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `MetadataOptions`
[Section titled âMetadataOptionsâ](#metadataoptions)
```typescript
export interface MetadataOptions {
album?: string;
artist?: string;
artwork?: MediaImage[];
title?: string;
}
```
### `PlaybackStateOptions`
[Section titled âPlaybackStateOptionsâ](#playbackstateoptions)
```typescript
export interface PlaybackStateOptions {
playbackState: MediaSessionPlaybackState;
}
```
### `ActionHandlerOptions`
[Section titled âActionHandlerOptionsâ](#actionhandleroptions)
```typescript
export interface ActionHandlerOptions {
action: MediaSessionAction;
}
```
### `ActionHandler`
[Section titled âActionHandlerâ](#actionhandler)
```typescript
export type ActionHandler = (details: ActionDetails) => void;
```
### `PositionStateOptions`
[Section titled âPositionStateOptionsâ](#positionstateoptions)
```typescript
export interface PositionStateOptions {
duration?: number;
playbackRate?: number;
position?: number;
}
```
### `MediaImage`
[Section titled âMediaImageâ](#mediaimage)
```typescript
export interface MediaImage {
src: string;
sizes?: string;
type?: string;
}
```
### `MediaSessionPlaybackState`
[Section titled âMediaSessionPlaybackStateâ](#mediasessionplaybackstate)
```typescript
export type MediaSessionPlaybackState = 'none' | 'paused' | 'playing';
```
### `MediaSessionAction`
[Section titled âMediaSessionActionâ](#mediasessionaction)
```typescript
export type MediaSessionAction =
| 'play'
| 'pause'
| 'seekbackward'
| 'seekforward'
| 'previoustrack'
| 'nexttrack'
| 'seekto'
| 'stop';
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-mqtt
> Capacitor plugin for MQTT connectivity on Android and iOS.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor plugin for MQTT connectivity on Android and iOS.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `connect`
* `disconnect`
* `subscribe`
* `publish`
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------- | ------------------------------------------------ |
| `connect` | See the source definitions for current behavior. |
| `disconnect` | See the source definitions for current behavior. |
| `subscribe` | See the source definitions for current behavior. |
| `publish` | See the source definitions for current behavior. |
| `addListener` | See the source definitions for current behavior. |
| `addListener` | See the source definitions for current behavior. |
| `addListener` | See the source definitions for current behavior. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-mqtt](https://github.com/Cap-go/capacitor-mqtt/).
# Getting Started
> Install @capgo/capacitor-mqtt and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-mqtt
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { MqttBridge } from '@capgo/capacitor-mqtt';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `connect`
[Section titled âconnectâ](#connect)
See the source definitions for the current contract.
```typescript
import { MqttBridge } from '@capgo/capacitor-mqtt';
await MqttBridge.connect({} as {
serverURI: string;
port: number;
clientId: string;
username: string;
password: string;
setCleanSession: boolean;
connectionTimeout: number;
keepAliveInterval: number;
setAutomaticReconnect: boolean;
setLastWill?: {
willTopic: string;
willPayload: string;
willQoS: number;
setRetained: boolean;
};
});
```
### `disconnect`
[Section titled âdisconnectâ](#disconnect)
See the source definitions for the current contract.
```typescript
import { MqttBridge } from '@capgo/capacitor-mqtt';
await MqttBridge.disconnect();
```
### `subscribe`
[Section titled âsubscribeâ](#subscribe)
See the source definitions for the current contract.
```typescript
import { MqttBridge } from '@capgo/capacitor-mqtt';
await MqttBridge.subscribe({} as { topic: string; qos: number });
```
### `publish`
[Section titled âpublishâ](#publish)
See the source definitions for the current contract.
```typescript
import { MqttBridge } from '@capgo/capacitor-mqtt';
await MqttBridge.publish({} as { topic: string; payload: string; qos: number; retained: boolean });
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `onConnectionLostListener`
[Section titled âonConnectionLostListenerâ](#onconnectionlostlistener)
```typescript
export type onConnectionLostListener = (x: { connectionStatus: string; reasonCode: number; message: string }) => void;
```
### `onConnectCompleteListener`
[Section titled âonConnectCompleteListenerâ](#onconnectcompletelistener)
```typescript
export type onConnectCompleteListener = (x: { reconnected: boolean; serverURI: string }) => void;
```
### `onMessageArrivedListener`
[Section titled âonMessageArrivedListenerâ](#onmessagearrivedlistener)
```typescript
export type onMessageArrivedListener = (x: { topic: string; message: string }) => void;
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-mute
> Capacitor Mute Plugin for detecting device mute status.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Mute Plugin for detecting device mute status.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isMuted` - Check if the device mute switch is enabled.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ------------------------------------------- |
| `isMuted` | Check if the device mute switch is enabled. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-mute](https://github.com/Cap-go/capacitor-mute/).
# Getting Started
> Install @capgo/capacitor-mute and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-mute
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { Mute } from '@capgo/capacitor-mute';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isMuted`
[Section titled âisMutedâ](#ismuted)
Check if the device mute switch is enabled.
```typescript
import { Mute } from '@capgo/capacitor-mute';
const { value } = await Mute.isMuted();
if (value) {
console.log('Device is muted');
} else {
console.log('Device is not muted');
}
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `MuteResponse`
[Section titled âMuteResponseâ](#muteresponse)
Response from mute status check.
```typescript
export interface MuteResponse {
/** True if device is muted, false otherwise */
value: boolean;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-mux-player
> Native Mux Player SDK to play video on IOS and Android.
## Overview
[Section titled âOverviewâ](#overview)
Native Mux Player SDK to play video on IOS and Android.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `play` - Launch the native Mux Player in fullscreen and begin playback.
* `dismiss` - Dismiss the player if it is visible.
* `isActive` - Returns whether the player is currently being displayed.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| -------------------- | -------------------------------------------------------------------- |
| `play` | Launch the native Mux Player in fullscreen and begin playback. |
| `dismiss` | Dismiss the player if it is visible. |
| `isActive` | Returns whether the player is currently being displayed. |
| `removeAllListeners` | Remove all event listeners registered on the plugin instance. |
| `addListener` | Listen to player lifecycle or playback events emitted by the plugin. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-mux-player](https://github.com/Cap-go/capacitor-mux-player/).
# Getting Started
> Install @capgo/capacitor-mux-player and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-mux-player
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { MuxPlayer } from '@capgo/capacitor-mux-player';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `play`
[Section titled âplayâ](#play)
Launch the native Mux Player in fullscreen and begin playback.
```typescript
import { MuxPlayer } from '@capgo/capacitor-mux-player';
await MuxPlayer.play({} as MuxPlayOptions);
```
### `dismiss`
[Section titled âdismissâ](#dismiss)
Dismiss the player if it is visible.
```typescript
import { MuxPlayer } from '@capgo/capacitor-mux-player';
await MuxPlayer.dismiss();
```
### `isActive`
[Section titled âisActiveâ](#isactive)
Returns whether the player is currently being displayed.
```typescript
import { MuxPlayer } from '@capgo/capacitor-mux-player';
await MuxPlayer.isActive();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `MuxPlayOptions`
[Section titled âMuxPlayOptionsâ](#muxplayoptions)
```typescript
export interface MuxPlayOptions {
/**
* The playback ID of the asset you want to stream.
*/
playbackId: string;
/**
* Provide a JSON web token generated for signed playback policies.
*/
playbackToken?: string;
/**
* Provide a JSON web token generated for DRM playback policies.
*/
drmToken?: string;
/**
* Override the default Mux playback domain (e.g. `stream.example.com`).
*/
customDomain?: string;
/**
* Auto-play when the player becomes visible. Defaults to true.
*/
autoPlay?: boolean;
/**
* Start playback from the provided time (in seconds).
*/
startTime?: number;
/**
* Provide a poster image URL to display before playback begins.
*/
poster?: string;
/**
* Provide a custom title to surface in native player chrome when available.
*/
title?: string;
/**
* Provide a subtitle or description to surface in native player chrome when available.
*/
subtitle?: string;
/**
* Set to true to keep the video muted when playback starts.
*/
muted?: boolean;
/**
* Mux Data environment key used for analytics. If omitted, the SDK default is used.
*/
environmentKey?: string;
/**
* Provide an explicit player name for analytics. Defaults to a generated name.
*/
playerName?: string;
/**
* Enable smart caching when the underlying SDK supports it.
*/
enableSmartCache?: boolean;
/**
* Enable verbose logging in native SDKs where available.
*/
debug?: boolean;
}
```
### `MuxPlayerEvents`
[Section titled âMuxPlayerEventsâ](#muxplayerevents)
```typescript
export interface MuxPlayerEvents {
/**
* Fired when the underlying player is ready to begin playback.
*/
ready: { playerName?: string };
/**
* Fired when playback starts or resumes.
*/
play: void;
/**
* Fired when playback pauses.
*/
pause: void;
/**
* Fired when playback ends.
*/
ended: void;
/**
* Fired when an unrecoverable error occurs.
*/
error: { message: string };
/**
* Fired when the fullscreen player is closed.
*/
playerDismissed: void;
/**
* Get the native Capacitor plugin version
*
* @returns {Promise<{ id: string }>} an Promise with version for this device
* @throws An error if the something went wrong
*/
getPluginVersion(): Promise<{ version: string }>;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/native-audio
> A native plugin for native audio engine.
## Overview
[Section titled âOverviewâ](#overview)
A native plugin for native audio engine.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `configure` - Configure the audio player.
* `preload` - Load an audio file.
* `playOnce` - Play an audio file once with automatic cleanup.
* `isPreloaded` - Check if an audio file is preloaded.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `configure` | Configure the audio player. |
| `preload` | Load an audio file. |
| `playOnce` | Play an audio file once with automatic cleanup. |
| `isPreloaded` | Check if an audio file is preloaded. |
| `play` | Play an audio file. |
| `pause` | Pause an audio file. |
| `resume` | Resume an audio file. |
| `loop` | Stop an audio file. |
| `stop` | Stop an audio file. |
| `unload` | Unload an audio file. |
| `setVolume` | Set the volume of an audio file. |
| `setRate` | Set the rate of an audio file. |
| `setCurrentTime` | Set the current time of an audio file. |
| `getCurrentTime` | Get the current time of an audio file. |
| `getDuration` | Get the duration of an audio file in seconds. |
| `isPlaying` | Check if an audio file is playing. |
| `addListener` | Listen for complete event. |
| `addListener` | Listen for current time updates Emits every 100ms while audio is playing. |
| `addListener` | Listen for playback state changes, including notification and lock-screen transport controls. Emitted by Android and iOS. The current Web implementation does not emit this event. |
| `clearCache` | Clear the audio cache for remote audio files. |
| `setDebugMode` | Set debug mode logging. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `deinitPlugin` | Deinitialize the plugin and restore original audio session settings This method stops all playing audio and reverts any audio session changes made by the plugin Use this when you need to ensure compatibility with other audio plugins. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-native-audio](https://github.com/Cap-go/capacitor-native-audio/).
# Getting Started
> Install @capgo/native-audio and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/native-audio
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { NativeAudio } from '@capgo/native-audio';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `configure`
[Section titled âconfigureâ](#configure)
Configure the audio player
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.configure({} as ConfigureOptions);
```
### `preload`
[Section titled âpreloadâ](#preload)
Load an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.preload({} as PreloadOptions);
```
### `playOnce`
[Section titled âplayOnceâ](#playonce)
Play an audio file once with automatic cleanup
Method designed for simple, single-shot audio playback, such as notification sounds, UI feedback, or other short audio clips that donât require manual state management.
**Key Features:**
* **Fire-and-forget**: No need to manually preload, play, stop, or unload
* **Auto-cleanup**: Asset is automatically unloaded after playback completes
* **Optional file deletion**: Can delete local files after playback (useful for temp files)
* **Returns assetId**: Can still control playback if needed (pause, stop, etc.)
**Use Cases:**
* Notification sounds
* UI sound effects (button clicks, alerts)
* Short audio clips that play once
* Temporary audio files that should be cleaned up
**Comparison with regular play():**
* `play()`: Requires manual preload, play, and unload steps
* `playOnce()`: Handles everything automatically with a single call
```typescript
import { NativeAudio } from '@capgo/native-audio';
// Simple one-shot playback
await NativeAudio.playOnce({ assetPath: 'audio/notification.mp3' });
// Play and delete the file after completion
await NativeAudio.playOnce({
assetPath: 'file:///path/to/temp/audio.mp3',
isUrl: true,
deleteAfterPlay: true
});
// Get the assetId to control playback
const { assetId } = await NativeAudio.playOnce({
assetPath: 'audio/long-track.mp3',
autoPlay: true
});
// Later, you can stop it manually if needed
await NativeAudio.stop({ assetId });
```
### `isPreloaded`
[Section titled âisPreloadedâ](#ispreloaded)
Check if an audio file is preloaded
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.isPreloaded({} as PreloadOptions);
```
### `play`
[Section titled âplayâ](#play)
Play an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.play({} as AssetPlayOptions);
```
### `pause`
[Section titled âpauseâ](#pause)
Pause an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.pause({} as AssetPauseOptions);
```
### `resume`
[Section titled âresumeâ](#resume)
Resume an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.resume({} as AssetResumeOptions);
```
### `loop`
[Section titled âloopâ](#loop)
Stop an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.loop({} as Assets);
```
### `stop`
[Section titled âstopâ](#stop)
Stop an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.stop({} as AssetStopOptions);
```
### `unload`
[Section titled âunloadâ](#unload)
Unload an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.unload({} as Assets);
```
### `setVolume`
[Section titled âsetVolumeâ](#setvolume)
Set the volume of an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.setVolume({} as AssetVolume);
```
### `setRate`
[Section titled âsetRateâ](#setrate)
Set the rate of an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.setRate({} as AssetRate);
```
### `setCurrentTime`
[Section titled âsetCurrentTimeâ](#setcurrenttime)
Set the current time of an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.setCurrentTime({} as AssetSetTime);
```
### `getCurrentTime`
[Section titled âgetCurrentTimeâ](#getcurrenttime)
Get the current time of an audio file
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.getCurrentTime({} as Assets);
```
### `getDuration`
[Section titled âgetDurationâ](#getduration)
Get the duration of an audio file in seconds
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.getDuration({} as Assets);
```
### `isPlaying`
[Section titled âisPlayingâ](#isplaying)
Check if an audio file is playing
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.isPlaying({} as Assets);
```
### `clearCache`
[Section titled âclearCacheâ](#clearcache)
Clear the audio cache for remote audio files
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.clearCache();
```
### `setDebugMode`
[Section titled âsetDebugModeâ](#setdebugmode)
Set debug mode logging
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.setDebugMode({} as { enabled: boolean });
```
### `deinitPlugin`
[Section titled âdeinitPluginâ](#deinitplugin)
Deinitialize the plugin and restore original audio session settings This method stops all playing audio and reverts any audio session changes made by the plugin Use this when you need to ensure compatibility with other audio plugins
```typescript
import { NativeAudio } from '@capgo/native-audio';
await NativeAudio.deinitPlugin();
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `ConfigureOptions`
[Section titled âConfigureOptionsâ](#configureoptions)
````typescript
export interface ConfigureOptions {
/**
* focus the audio with Audio Focus
*/
focus?: boolean;
/**
* Play the audio in the background
*/
background?: boolean;
/**
* Ignore silent mode, works only on iOS setting this will nuke other audio apps
*/
ignoreSilent?: boolean;
/**
* Show audio playback in the notification center (iOS and Android)
* When enabled, displays audio metadata (title, artist, album, artwork) in the system notification
* and Control Center (iOS) or lock screen.
*
* **Important iOS Behavior:**
* Enabling this option changes the audio session category to `.playback` with `.default` mode,
* which means your app's audio will **interrupt** other apps' audio (like background music from
* Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing
* info to appear in Control Center and on the lock screen.
*
* **Trade-offs:**
* - `showNotification: true` â Shows Now Playing controls, but interrupts other audio
* - `showNotification: false` â Audio mixes with other apps, but no Now Playing controls
*
* Use this when your app is the primary audio source (music players, podcast apps, etc.).
* Disable this for secondary audio like sound effects or notification sounds where mixing
* with background music is preferred.
*
* @see https://github.com/Cap-go/capacitor-native-audio/issues/202
*/
showNotification?: boolean;
/**
* Enable background audio playback (Android only)
*
* When enabled, audio will continue playing when the app is backgrounded or the screen is locked.
* The plugin will skip the automatic pause/resume logic that normally occurs when the app
* enters the background or returns to the foreground.
*
* **Important Android Requirements:**
* To use background playback on Android, your app must:
* 1. Declare the required permissions in `AndroidManifest.xml`:
* - ``
* - ``
* - ``
* 2. Start a Foreground Service with a media-style notification before backgrounding
* (the plugin does not automatically create or manage the foreground service)
* 3. Use `showNotification: true` to display playback controls in the notification
*
* **Usage Example:**
* ```typescript
* await NativeAudio.configure({
* backgroundPlayback: true,
* showNotification: true
* });
* // Start your foreground service here
* // Then preload and play audio as normal
* ```
*
* @default false
* @platform Android
* @since 8.2.0
*/
backgroundPlayback?: boolean;
}
````
### `PreloadOptions`
[Section titled âPreloadOptionsâ](#preloadoptions)
```typescript
export interface PreloadOptions {
/**
* Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)
* Supported formats:
* - MP3, WAV (all platforms)
* - M3U8/HLS streams (iOS and Android)
*/
assetPath: string;
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Volume of the audio, between 0.1 and 1.0
*/
volume?: number;
/**
* Audio channel number, default is 1
*/
audioChannelNum?: number;
/**
* Is the audio file a URL, pass true if assetPath is a `file://` url
* or a streaming URL (m3u8)
*/
isUrl?: boolean;
/**
* Metadata to display in the notification center when audio is playing.
* Only used when `showNotification: true` is set in `configure()`.
*
* See {@link ConfigureOptions.showNotification} for important details about
* how this affects audio mixing behavior on iOS.
*
* @see NotificationMetadata
*/
notificationMetadata?: NotificationMetadata;
/**
* Custom HTTP headers to include when fetching remote audio files.
* Only used when isUrl is true and assetPath is a remote URL (http/https).
* Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }
*
* @since 7.10.0
*/
headers?: Record;
}
```
### `PlayOnceOptions`
[Section titled âPlayOnceOptionsâ](#playonceoptions)
```typescript
export interface PlayOnceOptions {
/**
* Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)
* Supported formats:
* - MP3, WAV (all platforms)
* - M3U8/HLS streams (iOS and Android)
*/
assetPath: string;
/**
* Volume of the audio, between 0.1 and 1.0
* @default 1.0
*/
volume?: number;
/**
* Is the audio file a URL, pass true if assetPath is a `file://` url
* or a streaming URL (m3u8)
* @default false
*/
isUrl?: boolean;
/**
* Automatically start playback after loading
* @default true
*/
autoPlay?: boolean;
/**
* Delete the audio file from disk after playback completes
* Only works for local files (file:// URLs), ignored for remote URLs
* @default false
* @since 7.11.0
*/
deleteAfterPlay?: boolean;
/**
* Metadata to display in the notification center when audio is playing.
* Only used when `showNotification: true` is set in `configure()`.
*
* See {@link ConfigureOptions.showNotification} for important details about
* how this affects audio mixing behavior on iOS.
*
* @see NotificationMetadata
* @since 7.10.0
*/
notificationMetadata?: NotificationMetadata;
/**
* Custom HTTP headers to include when fetching remote audio files.
* Only used when isUrl is true and assetPath is a remote URL (http/https).
* Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }
*
* @since 7.10.0
*/
headers?: Record;
}
```
### `PlayOnceResult`
[Section titled âPlayOnceResultâ](#playonceresult)
```typescript
export interface PlayOnceResult {
/**
* The internally generated asset ID for this playback
* Can be used to control playback (pause, stop, etc.) before completion
*/
assetId: string;
}
```
### `AssetPlayOptions`
[Section titled âAssetPlayOptionsâ](#assetplayoptions)
```typescript
export interface AssetPlayOptions {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Time to start playing the audio, in seconds
*/
time?: number;
/**
* Delay to start playing the audio, in seconds
*/
delay?: number;
/**
* Volume of the audio, between 0.1 and 1.0
*/
volume?: number;
/**
* Whether to fade in the audio
*/
fadeIn?: boolean;
/**
* Whether to fade out the audio
*/
fadeOut?: boolean;
/**
* Fade in duration in seconds.
* Only used if fadeIn is true.
* Default is 1s.
*/
fadeInDuration?: number;
/**
* Fade out duration in seconds.
* Only used if fadeOut is true.
* Default is 1s.
*/
fadeOutDuration?: number;
/**
* Time in seconds from the start of the audio to start fading out.
* Only used if fadeOut is true.
* Default is fadeOutDuration before end of audio.
*/
fadeOutStartTime?: number;
}
```
### `AssetPauseOptions`
[Section titled âAssetPauseOptionsâ](#assetpauseoptions)
```typescript
export interface AssetPauseOptions {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Whether to fade out the audio before pausing
*/
fadeOut?: boolean;
/**
* Fade out duration in seconds.
* Default is 1s.
*/
fadeOutDuration?: number;
}
```
### `AssetResumeOptions`
[Section titled âAssetResumeOptionsâ](#assetresumeoptions)
```typescript
export interface AssetResumeOptions {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Whether to fade in the audio during resume
*/
fadeIn?: boolean;
/**
* Fade in duration in seconds.
* Default is 1s.
*/
fadeInDuration?: number;
}
```
### `Assets`
[Section titled âAssetsâ](#assets)
```typescript
export interface Assets {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
}
```
### `AssetStopOptions`
[Section titled âAssetStopOptionsâ](#assetstopoptions)
```typescript
export interface AssetStopOptions {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Whether to fade out the audio before stopping
*/
fadeOut?: boolean;
/**
* Fade out duration in seconds.
* Default is 1s.
*/
fadeOutDuration?: number;
}
```
### `AssetVolume`
[Section titled âAssetVolumeâ](#assetvolume)
```typescript
export interface AssetVolume {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Volume of the audio, between 0.1 and 1.0
*/
volume: number;
/**
* Time over which to fade to the target volume, in seconds. Default is 0s (immediate).
*/
duration?: number;
}
```
### `AssetRate`
[Section titled âAssetRateâ](#assetrate)
```typescript
export interface AssetRate {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Rate of the audio, between 0.1 and 1.0
*/
rate: number;
}
```
### `AssetSetTime`
[Section titled âAssetSetTimeâ](#assetsettime)
```typescript
export interface AssetSetTime {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
/**
* Time to set the audio, in seconds
*/
time: number;
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/capacitor-native-biometric
> This plugin gives access to the native biometric apis for android and iOS.
## Overview
[Section titled âOverviewâ](#overview)
This plugin gives access to the native biometric apis for android and iOS.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `isAvailable` - Checks if biometric authentication hardware is available.
* `verifyIdentity` - Prompts the user to authenticate with biometrics.
* `getCredentials` - Gets the stored credentials for a given server.
* `setCredentials` - Stores the given credentials for a given server.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isAvailable` | Checks if biometric authentication hardware is available. |
| `addListener` | Adds a listener that is called when the app resumes from background. This is useful to detect if biometry availability has changed while the app was in the background (e.g., user enrolled/unenrolled biometrics). |
| `verifyIdentity` | Prompts the user to authenticate with biometrics. |
| `getCredentials` | Gets the stored credentials for a given server. |
| `setCredentials` | Stores the given credentials for a given server. |
| `deleteCredentials` | Deletes the stored credentials for a given server. |
| `getSecureCredentials` | Gets the stored credentials for a given server, requiring biometric authentication. Credentials must have been stored with accessControl set to BIOMETRY\_CURRENT\_SET or BIOMETRY\_ANY. |
| `isCredentialsSaved` | Checks if credentials are already saved for a given server. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-native-biometric](https://github.com/Cap-go/capacitor-native-biometric/).
# Getting Started
> Install @capgo/capacitor-native-biometric and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/capacitor-native-biometric
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `isAvailable`
[Section titled âisAvailableâ](#isavailable)
Checks if biometric authentication hardware is available.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.isAvailable();
```
### `verifyIdentity`
[Section titled âverifyIdentityâ](#verifyidentity)
Prompts the user to authenticate with biometrics.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.verifyIdentity();
```
### `getCredentials`
[Section titled âgetCredentialsâ](#getcredentials)
Gets the stored credentials for a given server.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.getCredentials({} as GetCredentialOptions);
```
### `setCredentials`
[Section titled âsetCredentialsâ](#setcredentials)
Stores the given credentials for a given server.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.setCredentials({} as SetCredentialOptions);
```
### `deleteCredentials`
[Section titled âdeleteCredentialsâ](#deletecredentials)
Deletes the stored credentials for a given server.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.deleteCredentials({} as DeleteCredentialOptions);
```
### `getSecureCredentials`
[Section titled âgetSecureCredentialsâ](#getsecurecredentials)
Gets the stored credentials for a given server, requiring biometric authentication. Credentials must have been stored with accessControl set to BIOMETRY\_CURRENT\_SET or BIOMETRY\_ANY.
On iOS, the system automatically shows the biometric prompt when accessing the protected Keychain item. On Android, BiometricPrompt is shown with a CryptoObject bound to the credential decryption key.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.getSecureCredentials({} as GetSecureCredentialsOptions);
```
### `isCredentialsSaved`
[Section titled âisCredentialsSavedâ](#iscredentialssaved)
Checks if credentials are already saved for a given server.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.isCredentialsSaved({} as IsCredentialsSavedOptions);
```
## Type Reference
[Section titled âType Referenceâ](#type-reference)
### `IsAvailableOptions`
[Section titled âIsAvailableOptionsâ](#isavailableoptions)
```typescript
export interface IsAvailableOptions {
/**
* Only for iOS.
* Specifies if should fallback to passcode authentication if biometric authentication is not available.
* On Android, this parameter is ignored due to BiometricPrompt API constraints:
* DEVICE_CREDENTIAL authenticator and negative button (cancel) are mutually exclusive.
*/
useFallback: boolean;
}
```
### `AvailableResult`
[Section titled âAvailableResultâ](#availableresult)
Result from isAvailable() method indicating biometric authentication availability.
```typescript
export interface AvailableResult {
/**
* Whether authentication is available (biometric or fallback if useFallback is true)
*/
isAvailable: boolean;
/**
* The strength of available authentication method (STRONG, WEAK, or NONE)
*/
authenticationStrength: AuthenticationStrength;
/**
* The primary biometry type available on the device.
* On Android devices with multiple biometry types, this returns MULTIPLE.
* Use this for display purposes only - always use isAvailable for logic decisions.
*/
biometryType: BiometryType;
/**
* Whether the device has a secure lock screen (PIN, pattern, or password).
* This is independent of biometric enrollment.
*/
deviceIsSecure: boolean;
/**
* Whether strong biometry (Face ID, Touch ID, or fingerprint on devices that consider it strong)
* is specifically available, separate from weak biometry or device credentials.
*/
strongBiometryIsAvailable: boolean;
/**
* Error code from BiometricAuthError enum. Only present when isAvailable is false.
* Indicates why biometric authentication is not available.
* @see BiometricAuthError
*/
errorCode?: BiometricAuthError;
}
```
### `BiometryChangeListener`
[Section titled âBiometryChangeListenerâ](#biometrychangelistener)
Callback type for biometry change listener.
```typescript
export type BiometryChangeListener = (result: AvailableResult) => void;
```
### `BiometricOptions`
[Section titled âBiometricOptionsâ](#biometricoptions)
```typescript
export interface BiometricOptions {
reason?: string;
title?: string;
subtitle?: string;
description?: string;
negativeButtonText?: string;
/**
* Only for iOS.
* Specifies if should fallback to passcode authentication if biometric authentication fails.
* On Android, this parameter is ignored due to BiometricPrompt API constraints:
* DEVICE_CREDENTIAL authenticator and negative button (cancel) are mutually exclusive.
*/
useFallback?: boolean;
/**
* Only for iOS.
* Set the text for the fallback button in the authentication dialog.
* If this property is not specified, the default text is set by the system.
*/
fallbackTitle?: string;
/**
* Only for Android.
* Set a maximum number of attempts for biometric authentication. The maximum allowed by android is 5.
* @default 1
*/
maxAttempts?: number;
/**
* Only for Android.
* Specify which biometry types are allowed for authentication.
* If not specified, all available types will be allowed.
* @example [BiometryType.FINGERPRINT, BiometryType.FACE_AUTHENTICATION]
*/
allowedBiometryTypes?: BiometryType[];
}
```
### `GetCredentialOptions`
[Section titled âGetCredentialOptionsâ](#getcredentialoptions)
```typescript
export interface GetCredentialOptions {
server: string;
}
```
### `Credentials`
[Section titled âCredentialsâ](#credentials)
```typescript
export interface Credentials {
username: string;
password: string;
}
```
### `SetCredentialOptions`
[Section titled âSetCredentialOptionsâ](#setcredentialoptions)
```typescript
export interface SetCredentialOptions {
username: string;
password: string;
server: string;
/**
* Access control level for the stored credentials.
* When set to BIOMETRY_CURRENT_SET or BIOMETRY_ANY, the credentials are
* hardware-protected and require biometric authentication to access.
*
* On iOS, this adds SecAccessControl to the Keychain item.
* On Android, this creates a biometric-protected Keystore key and requires
* BiometricPrompt authentication for both storing and retrieving credentials.
*
* @default AccessControl.NONE
* @since 8.4.0
*/
accessControl?: AccessControl;
}
```
### `DeleteCredentialOptions`
[Section titled âDeleteCredentialOptionsâ](#deletecredentialoptions)
```typescript
export interface DeleteCredentialOptions {
server: string;
}
```
### `GetSecureCredentialsOptions`
[Section titled âGetSecureCredentialsOptionsâ](#getsecurecredentialsoptions)
```typescript
export interface GetSecureCredentialsOptions {
server: string;
/**
* Reason for requesting biometric authentication.
* Displayed in the biometric prompt on both iOS and Android.
*/
reason?: string;
/**
* Title for the biometric prompt.
* Only for Android.
*/
title?: string;
/**
* Subtitle for the biometric prompt.
* Only for Android.
*/
subtitle?: string;
/**
* Description for the biometric prompt.
* Only for Android.
*/
description?: string;
/**
* Text for the negative/cancel button.
* Only for Android.
*/
negativeButtonText?: string;
}
```
### `IsCredentialsSavedOptions`
[Section titled âIsCredentialsSavedOptionsâ](#iscredentialssavedoptions)
```typescript
export interface IsCredentialsSavedOptions {
server: string;
}
```
### `IsCredentialsSavedResult`
[Section titled âIsCredentialsSavedResultâ](#iscredentialssavedresult)
```typescript
export interface IsCredentialsSavedResult {
isSaved: boolean;
}
```
### `AuthenticationStrength`
[Section titled âAuthenticationStrengthâ](#authenticationstrength)
```typescript
export enum AuthenticationStrength {
/**
* No authentication available, even if PIN is available but useFallback = false
*/
NONE = 0,
/**
* Strong authentication: Face ID on iOS, fingerprints on devices that consider fingerprints strong (Android).
* Note: PIN/pattern/password is NEVER considered STRONG, even when useFallback = true.
*/
STRONG = 1,
/**
* Weak authentication: Face authentication on Android devices that consider face weak,
* or PIN/pattern/password if useFallback = true (PIN is always WEAK, never STRONG).
*/
WEAK = 2,
}
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/native-market
> Capacitor Native Market Plugin for opening app store listings and pages.
## Overview
[Section titled âOverviewâ](#overview)
Capacitor Native Market Plugin for opening app store listings and pages.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `openStoreListing` - Launch app listing page in Play Store (Android) or App Store (iOS).
* `openDevPage` - Deep-link directly to a developerâs page in the Play Store. Android only.
* `openCollection` - Link users to a collection or top charts in the Play Store. Android only.
* `openEditorChoicePage` - Link users to Editorâs choice page in the Play Store. Android only.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ---------------------- | ------------------------------------------------------------------------- |
| `openStoreListing` | Launch app listing page in Play Store (Android) or App Store (iOS). |
| `openDevPage` | Deep-link directly to a developerâs page in the Play Store. Android only. |
| `openCollection` | Link users to a collection or top charts in the Play Store. Android only. |
| `openEditorChoicePage` | Link users to Editorâs choice page in the Play Store. Android only. |
| `search` | Search the Play Store with custom search terms. Android only. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-native-market](https://github.com/Cap-go/capacitor-native-market/).
# Getting Started
> Install @capgo/native-market and start using its current Capacitor API.
## Install
[Section titled âInstallâ](#install)
```bash
bun add @capgo/native-market
bunx cap sync
```
## Import
[Section titled âImportâ](#import)
```typescript
import { NativeMarket } from '@capgo/native-market';
```
## API Overview
[Section titled âAPI Overviewâ](#api-overview)
### `openStoreListing`
[Section titled âopenStoreListingâ](#openstorelisting)
Launch app listing page in Play Store (Android) or App Store (iOS).
```typescript
import { NativeMarket } from '@capgo/native-market';
// Open app in store
await NativeMarket.openStoreListing({
appId: 'com.example.app'
});
// Open app in specific country store (iOS only)
await NativeMarket.openStoreListing({
appId: 'com.example.app',
country: 'IT'
});
```
### `openDevPage`
[Section titled âopenDevPageâ](#opendevpage)
Deep-link directly to a developerâs page in the Play Store. Android only.
```typescript
import { NativeMarket } from '@capgo/native-market';
await NativeMarket.openDevPage({
devId: 'Google+LLC'
});
```
### `openCollection`
[Section titled âopenCollectionâ](#opencollection)
Link users to a collection or top charts in the Play Store. Android only.
```typescript
import { NativeMarket } from '@capgo/native-market';
await NativeMarket.openCollection({
name: 'featured'
});
```
### `openEditorChoicePage`
[Section titled âopenEditorChoicePageâ](#openeditorchoicepage)
Link users to Editorâs choice page in the Play Store. Android only.
```typescript
import { NativeMarket } from '@capgo/native-market';
await NativeMarket.openEditorChoicePage({
editorChoice: 'editorial_fitness_apps_us'
});
```
### `search`
[Section titled âsearchâ](#search)
Search the Play Store with custom search terms. Android only.
```typescript
import { NativeMarket } from '@capgo/native-market';
await NativeMarket.search({
terms: 'fitness apps'
});
```
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This page is generated from the pluginâs `src/definitions.ts`. Re-run the sync when the public API changes upstream.
# @capgo/native-navigation
> Render iOS and Android navigation chrome natively while JavaScript keeps owning routes, content, icons, labels, and bar state.
Native chrome
Draw the top navigation bar and bottom tab bar with platform UI instead of web components.
Web-owned routes
Native emits user intent events, then your existing router changes the WebView content.
Serialized icons
Configure tabs and buttons with SVG, SF Symbol, bundled image, or Android drawable descriptors.
Native transition shell
Capture the current WebView, update content in JavaScript, then finish with a native snapshot-to-WebView animation.
## Core API
[Section titled âCore APIâ](#core-api)
* `configure(options?)` enables the native chrome host and controls content insets.
* `setNavbar(options)` updates native title, subtitle, back button, buttons, colors, transparency, and visibility.
* `setTabbar(options)` updates tabs, selected tab, badges, labels, icons, colors, and visibility.
* `beginTransition(options?)` captures the outgoing WebView before the JavaScript route change.
* `finishTransition(options?)` animates from the captured snapshot to the live WebView after route content is ready.
* `getPluginVersion()` returns the native implementation version marker.
## Events
[Section titled âEventsâ](#events)
* `navbarBack` fires when the native back affordance is tapped.
* `navbarItemTap` fires when a native navbar action button is tapped.
* `tabSelect` fires when a native tab is selected.
* `safeAreaChanged` reports native bar and safe-area inset changes.
* `transitionStart` and `transitionEnd` report native transition boundaries.
## Platform Model
[Section titled âPlatform Modelâ](#platform-model)
iOS uses `UINavigationBar` and `UITabBar`. On iOS 26 and newer, the plugin lets the system render Liquid Glass behavior; older versions use native translucent/material fallbacks.
Android uses an AppCompat toolbar and Material bottom navigation with edge-to-edge placement.
The plugin does not create one native WebView per route. Version 1 keeps a single Capacitor WebView for bridge stability and lets native own only the frame, bar visuals, tab selection chrome, safe-area reporting, and transition shell.
# Getting Started
> Install @capgo/native-navigation and render native navigation chrome over a Capacitor WebView.
1. **Install the package**
```sh
bun add @capgo/native-navigation
```
2. **Sync native projects**
```sh
bunx cap sync
```
3. **Configure native chrome**
```ts
import { NativeNavigation } from '@capgo/native-navigation';
await NativeNavigation.configure({
contentInsetMode: 'css',
animationDuration: 360,
colors: {
tint: '#0f172a',
inactiveTint: '#64748b',
},
});
```
4. **Render the native navbar**
```ts
await NativeNavigation.setNavbar({
title: 'Home',
subtitle: 'Native chrome',
transparent: true,
backButton: { visible: false },
rightItems: [
{
id: 'compose',
title: 'Compose',
icon: {
svg: '',
},
},
],
});
```
5. **Render the native tabbar**
```ts
await NativeNavigation.setTabbar({
selectedId: 'home',
labels: true,
icons: true,
tabs: [
{
id: 'home',
title: 'Home',
icon: {
svg: '',
},
},
{
id: 'settings',
title: 'Settings',
badge: '2',
icon: {
svg: '',
},
},
],
});
```
6. **Handle native intent events**
```ts
await NativeNavigation.addListener('navbarBack', () => {
router.back();
});
await NativeNavigation.addListener('navbarItemTap', ({ id }) => {
if (id === 'compose') router.push('/compose');
});
await NativeNavigation.addListener('tabSelect', ({ id }) => {
router.push(`/${id}`);
});
```
## Transition flow
[Section titled âTransition flowâ](#transition-flow)
Native transitions are a transaction around your normal JavaScript route change:
```ts
const transition = await NativeNavigation.beginTransition({
direction: 'forward',
});
router.push('/detail');
await router.ready?.();
await NativeNavigation.setNavbar({
title: 'Detail',
backButton: { visible: true, title: 'Back' },
});
await NativeNavigation.finishTransition({
id: transition.id,
direction: 'forward',
});
```
## CSS insets
[Section titled âCSS insetsâ](#css-insets)
With `contentInsetMode: 'css'`, the plugin writes native bar dimensions to `document.documentElement`.
```css
.page {
padding-top: var(--cap-native-navigation-top);
padding-bottom: var(--cap-native-navigation-bottom);
}
```
Available variables:
* `--cap-native-navigation-top`
* `--cap-native-navigation-right`
* `--cap-native-navigation-bottom`
* `--cap-native-navigation-left`
* `--cap-native-navbar-height`
* `--cap-native-tabbar-height`
## Icon descriptors
[Section titled âIcon descriptorsâ](#icon-descriptors)
Icons must be serializable because native UI renders them. You can use cross-platform SVG, platform-specific SVG, SF Symbols, bundled iOS images, Android drawable resources, or bundled Android images.
```ts
const icon = {
svg: '',
width: 24,
height: 24,
template: true,
src: 'fallback_asset_name',
ios: {
svg: '',
sfSymbol: 'house.fill',
image: 'BundledAssetName',
},
android: {
svg: '',
resource: 'ic_menu_view',
image: 'bundled_drawable_name',
},
};
```
Inline SVG supports the icon-focused subset used by common icon sets such as Lucide and Feather: `path`, `line`, `polyline`, `polygon`, `circle`, and `rect`. SVG icons are rendered as template images by default, so native tint colors can recolor them.
## Optional web components
[Section titled âOptional web componentsâ](#optional-web-components)
The package can register custom elements for framework-agnostic declarative setup:
```ts
import { defineNativeNavigationElements } from '@capgo/native-navigation';
defineNativeNavigationElements();
```
```html
```
Note
The web components are optional. React, Vue, Angular, Svelte, Solid, and vanilla apps can all use the imperative API directly.
## Platform notes
[Section titled âPlatform notesâ](#platform-notes)
* iOS renders `UINavigationBar` and `UITabBar`; iOS 26+ uses the system Liquid Glass bar behavior.
* Android renders an AppCompat toolbar and Material bottom navigation.
* Web fallback does not draw native bars. It mirrors events and inset variables for browser development.
* The plugin keeps one full-screen Capacitor WebView. Native owns the frame, bars, safe-area reporting, and transition shell.
# @capgo/native-purchases
> In-app Subscriptions Made Easy.
## Overview
[Section titled âOverviewâ](#overview)
In-app Subscriptions Made Easy.
## Core Capabilities
[Section titled âCore Capabilitiesâ](#core-capabilities)
* `restorePurchases` - Restores a userâs previous and links their appUserIDs to any userâs also using those .
* `getAppTransaction` - Gets the App Transaction information, which provides details about when the user originally downloaded or purchased the app.
* `isEntitledToOldBusinessModel` - Compares the original app version from the App Transaction against a target version to determine if the user is entitled to features from an earlier business model.
* `purchaseProduct` - Started purchase process for the given product.
## Public API
[Section titled âPublic APIâ](#public-api)
| Method | Description |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `restorePurchases` | Restores a userâs previous and links their appUserIDs to any userâs also using those . |
| `getAppTransaction` | Gets the App Transaction information, which provides details about when the user originally downloaded or purchased the app. |
| `isEntitledToOldBusinessModel` | Compares the original app version from the App Transaction against a target version to determine if the user is entitled to features from an earlier business model. |
| `purchaseProduct` | Started purchase process for the given product. |
| `getProducts` | Gets the product info associated with a list of product identifiers. |
| `getProduct` | Gets the product info for a single product identifier. |
| `isBillingSupported` | Check if billing is supported for the current device. |
| `getPluginVersion` | Get the native Capacitor plugin version. |
| `getPurchases` | Gets all the userâs purchases (both in-app purchases and subscriptions). This method queries the platformâs purchase history for the current user. |
| `manageSubscriptions` | Opens the platformâs native subscription management page. This allows users to view, modify, or cancel their subscriptions. |
| `acknowledgePurchase` | Manually acknowledge/finish a purchase transaction. |
| `consumePurchase` | Consume an in-app purchase on Android. |
| `addListener` | Listen for StoreKit transaction updates delivered by Appleâs Transaction.updates. Fires on app launch if there are unfinished transactions, and for any updates afterward. iOS only. |
| `addListener` | Listen for StoreKit transaction verification failures delivered by Appleâs Transaction.updates. Fires when the verification result is unverified. iOS only. |
| `removeAllListeners` | Remove all registered listeners. |
## Source Of Truth
[Section titled âSource Of Truthâ](#source-of-truth)
This reference is synced from `src/definitions.ts` in [capacitor-native-purchases](https://github.com/Cap-go/capacitor-native-purchases/).
# Create Android Auto-Renewable Subscription
> Step-by-step guide to creating auto-renewable subscriptions in Google Play Console for the native-purchases plugin.
Auto-renewable subscriptions provide access to content, services, or premium features in your app on an ongoing basis. This guide will help you create and configure subscriptions in Google Play Console.
## Overview
[Section titled âOverviewâ](#overview)
Subscriptions automatically renew at the end of each billing period until the user cancels. Theyâre ideal for:
* Premium content access
* Ad-free experiences
* Cloud storage
* Ongoing services
## Creating a Subscription
[Section titled âCreating a Subscriptionâ](#creating-a-subscription)
1. **Navigate to Subscriptions**
In Google Play Console, select your app and choose **Monetize > Subscriptions** from the left menu.
Click the **Create subscription** button to begin.

2. **Enter Basic Information**
Provide a subscription name and product ID. The product ID is required for configuration in your app and cannot be changed later.

3. **Create Base Plan**
Google Play requires exactly one base plan per subscription. The native-purchases plugin supports only one base plan to maintain compatibility with iOS.
Click **Add base plan** to continue.

4. **Configure Base Plan Details**
Enter:
* **Base plan ID**: Unique identifier for this plan
* **Billing period**: How often users are charged (weekly, monthly, yearly, etc.)
* **Grace period**: Time window during which Google maintains the subscription while retrying payment before cancellation

5. **Set Up Pricing**
Access the pricing section and select all countries/regions where you want to offer the subscription.

6. **Configure Price**
Set your base price in your primary currency. Google Play automatically converts this to local currencies.

7. **Review Regional Pricing**
Review the automatically converted prices for each country. You can adjust individual prices if needed.

8. **Save Configuration**
Save your pricing configuration.

9. **Activate Subscription**
Click the **Activate** button to make your subscription product live and available for purchase.

## Important Considerations
[Section titled âImportant Considerationsâ](#important-considerations)
### Base Plan Limitation
[Section titled âBase Plan Limitationâ](#base-plan-limitation)
The native-purchases plugin requires exactly one base plan per subscription to ensure consistency with iOS subscription handling. Multiple base plans are not supported.
### Grace Period
[Section titled âGrace Periodâ](#grace-period)
The grace period allows Google Play to retry failed payments while maintaining the userâs subscription access. Common grace periods are:
* 3 days for monthly subscriptions
* 7 days for longer subscriptions
### Subscription Status
[Section titled âSubscription Statusâ](#subscription-status)
After creation, your subscription will be in âDraftâ status until activated. You can test draft subscriptions in sandbox mode.
## Using in Your App
[Section titled âUsing in Your Appâ](#using-in-your-app)
Once created, reference the subscription in your app using the product ID:
```typescript
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
// Load subscription info
const { products } = await NativePurchases.getProducts({
productIdentifiers: ['com.example.premium.monthly'],
productType: PURCHASE_TYPE.SUBS,
});
const product = products[0];
console.log(`${product.title} â ${product.priceString}`);
// Purchase (planIdentifier = Base Plan ID from Google Play Console)
const transaction = await NativePurchases.purchaseProduct({
productIdentifier: 'com.example.premium.monthly',
planIdentifier: 'monthly-plan', // REQUIRED on Android, ignored on iOS
productType: PURCHASE_TYPE.SUBS,
});
console.log('Transaction ID', transaction.transactionId);
// Later, check purchase state
const { purchases } = await NativePurchases.getPurchases({
productType: PURCHASE_TYPE.SUBS,
});
const subscription = purchases.find(
(purchase) => purchase.productIdentifier === 'com.example.premium.monthly',
);
if (subscription && subscription.purchaseState === 'PURCHASED' && subscription.isAcknowledged) {
console.log('Subscription active locally');
// For expiration/cancellation, validate purchaseToken through your backend
}
```
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* [Create an introductory offer](/docs/plugins/native-purchases/android-introductory-offer/) to attract new subscribers
* [Configure sandbox testing](/docs/plugins/native-purchases/android-sandbox-testing/) to test your subscriptions
* Set up backend receipt validation for security
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
**Subscription not appearing in app:**
* Verify the product ID matches exactly
* Ensure the subscription is activated
* Check that your app has the correct package name
* Wait 2-3 hours after activation for changes to propagate
**Base plan errors:**
* Ensure you have exactly one base plan
* Verify all required fields are filled
* Check that billing period is valid
**Pricing issues:**
* Confirm at least one country is selected
* Verify base price is greater than minimum allowed
* Check currency conversion rates are acceptable
# Create Android Subscription Introductory Offer
> Learn how to create introductory offers for auto-renewable subscriptions on Android to attract new subscribers.
Introductory offers allow you to provide eligible users with either a free trial or a discounted introductory price. After the introductory period concludes, subscriptions automatically renew at standard pricing unless cancelled.
## Overview
[Section titled âOverviewâ](#overview)
Introductory offers are a powerful tool to:
* Reduce barriers to entry for new subscribers
* Increase conversion rates
* Allow users to try your premium features risk-free
* Build long-term subscriber relationships
## Eligibility
[Section titled âEligibilityâ](#eligibility)
Users can receive an introductory offer if they havenât previously purchased or received an introductory offer for the subscription. Google Play handles eligibility automatically.
## Prerequisites
[Section titled âPrerequisitesâ](#prerequisites)
You must first [create an auto-renewable subscription](/docs/plugins/native-purchases/android-create-subscription/) before adding an introductory offer.
## Creating an Introductory Offer
[Section titled âCreating an Introductory Offerâ](#creating-an-introductory-offer)
1. **Access Offer Configuration**
Navigate to your subscription in Google Play Console and select the **Add offer** button.

2. **Select Base Plan**
A modal will appear requiring you to choose your base plan. Typically, youâll only have one base plan. Click **Add offer** to continue.

3. **Configure Offer Details**
Enter the following information:
**Offer ID**: A unique identifier for this offer
**Eligibility**: Choose who can receive this offer
* **New customers**: Only users who have never subscribed
* **Existing customers**: Users who previously subscribed
* **Developer determined**: Custom eligibility logic (not supported by native-purchases)
Caution
The native-purchases plugin does not support the âDeveloper determinedâ eligibility option. Use âNew customersâ or âExisting customersâ instead.

4. **Add Phases**
Click **Add phase** at the bottom of the page to define your offer structure.
You can add up to two phases, allowing combinations like:
* Free trial only
* Discounted price only
* Free trial followed by discounted recurring payment
5. **Select Phase Type**
Choose from three phase types:
**Free Trial**
* Complimentary access for a set duration
* Example: 7 days free, then $9.99/month
**Single Payment**
* One-time discounted price for a specific period
* Example: $1.99 for 2 months, then $9.99/month
**Discounted Recurring Payment**
* Reduced per-billing-cycle rate for multiple cycles
* Example: $4.99/month for 3 months, then $9.99/month
6. **Configure Phase Duration**
Set how long the introductory phase lasts:
* Days, weeks, or months
* Number of billing cycles
7. **Finalize and Activate**
Click **Apply**, then **Save** to activate the offer. The **Activate** button will become available once saved.
## Offer Phase Examples
[Section titled âOffer Phase Examplesâ](#offer-phase-examples)
### Example 1: Simple Free Trial
[Section titled âExample 1: Simple Free Trialâ](#example-1-simple-free-trial)
* Phase 1: 7 days free
* Then: $9.99/month standard pricing
### Example 2: Discounted Introduction
[Section titled âExample 2: Discounted Introductionâ](#example-2-discounted-introduction)
* Phase 1: $1.99 for the first month
* Then: $9.99/month standard pricing
### Example 3: Extended Trial + Discount
[Section titled âExample 3: Extended Trial + Discountâ](#example-3-extended-trial--discount)
* Phase 1: 14 days free
* Phase 2: $4.99/month for 2 months
* Then: $9.99/month standard pricing
## Using in Your App
[Section titled âUsing in Your Appâ](#using-in-your-app)
The native-purchases plugin automatically handles introductory offer eligibility and presentation:
```typescript
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
// Fetch products (includes intro offer metadata)
const { products } = await NativePurchases.getProducts({
productIdentifiers: ['com.example.premium.monthly'],
productType: PURCHASE_TYPE.SUBS,
});
const product = products[0];
if (product.introductoryPrice) {
console.log(`Intro price: ${product.introductoryPriceString}`);
console.log(`Regular price: ${product.priceString}`);
console.log(
`Offer duration: ${product.introductoryPrice.subscriptionPeriod?.numberOfUnits} ${product.introductoryPrice.subscriptionPeriod?.unit}`,
);
} else {
console.log('No intro offer configured for this product');
}
// Purchase (Google Play applies intro pricing automatically if the user is eligible)
const transaction = await NativePurchases.purchaseProduct({
productIdentifier: 'com.example.premium.monthly',
planIdentifier: 'monthly-plan', // Base Plan ID from Google Play Console
productType: PURCHASE_TYPE.SUBS,
});
console.log('Introductory purchase transaction', transaction.transactionId);
```
## Best Practices
[Section titled âBest Practicesâ](#best-practices)
### Offer Duration
[Section titled âOffer Durationâ](#offer-duration)
* **Free trials**: 3-14 days is optimal for most apps
* **Discounted periods**: 1-3 months works well for building habit
* **Price discount**: 50-70% off regular price drives conversions
### Marketing
[Section titled âMarketingâ](#marketing)
* Clearly display the intro offer and regular price
* Show what happens after the intro period
* Make cancellation easy and transparent
* Remind users before the intro period ends
### A/B Testing
[Section titled âA/B Testingâ](#ab-testing)
Test different offer structures:
* Free trial length
* Discount percentage
* Discount duration
* Single phase vs. multi-phase
## Important Notes
[Section titled âImportant Notesâ](#important-notes)
* Only one introductory offer can be active per subscription at a time
* Users can only claim an intro offer once per subscription
* Intro offers donât apply to subscription upgrades/downgrades
* Changes to intro offers donât affect existing subscribers
## Troubleshooting
[Section titled âTroubleshootingâ](#troubleshooting)
**Intro offer not showing:**
* Verify the offer is activated in Play Console
* Check user eligibility (may have used offer before)
* Ensure app is using latest product information
**Wrong users receiving offer:**
* Review eligibility settings (new vs. existing customers)
* Check if user previously subscribed on different device
* Verify Play Store account history
**Offer not applying at purchase:**
* Confirm product ID matches exactly
* Check that offer is still active and not expired
* Verify date range settings for the offer
## Next Steps
[Section titled âNext Stepsâ](#next-steps)
* [Configure sandbox testing](/docs/plugins/native-purchases/android-sandbox-testing/) to test your offers
* Monitor conversion rates in Play Console analytics
* Consider creating multiple subscription tiers with different offers
# Android Play Store Review Guidelines for IAP
> Complete guide to passing Google Play review with in-app purchases and subscriptions, including compliance requirements and best practices.
Getting your Android app approved on Google Play requires compliance with Googleâs policies, especially for apps with in-app purchases and subscriptions. This guide covers everything you need to pass review successfully.
## Release Path That Works
[Section titled âRelease Path That Worksâ](#release-path-that-works)
1. **Build a Signed Android App Bundle**
New Google Play apps should be uploaded as an Android App Bundle (`.aab`), not a sideloaded debug APK.
Keep your `versionCode` increasing on every upload and store your upload key safely if you use Play App Signing.

2. **Create the App Record in Play Console**
If you do not have a developer account yet, start with [Play Console signup](https://play.google.com/console/signup). Then, in **Home > Create app**, choose the language, app/game type, free/paid status, support email, and accept the required declarations.
Choose the free/paid setting carefully. Google lets you change a paid app to free later, but once an app has been offered for free, it cannot be switched to paid.

3. **Complete App Content and Store Listing**
Before production review, finish the required Play Console declarations:
* Privacy policy
* Ads
* App access
* Target audience and content
* Content rating
* Data Safety
* Sensitive permissions declarations, if applicable
4. **Run a Play-Installed Test Track**
Start with **internal testing** for fast QA. If your developer account is a personal account created after November 13, 2023, you must also complete a **closed test** with at least 12 opted-in testers for 14 consecutive days before production access.

5. **Verify Billing End-to-End**
Install the app from Google Play, not from a locally exported APK. Then confirm that:
* Products load from Play correctly
* The purchase sheet shows a **test purchase** banner for license testers
* Entitlements unlock after purchase
* Restore and subscription management flows work
## Google Play Billing Requirements
[Section titled âGoogle Play Billing Requirementsâ](#google-play-billing-requirements)
### Mandatory Billing System
[Section titled âMandatory Billing Systemâ](#mandatory-billing-system)
For digital goods and services, you **must** use Google Playâs billing system:
**Digital Goods (Must Use Play Billing):**
* Subscriptions to premium features
* In-app currency or credits
* Digital content (ebooks, music, videos)
* Game upgrades and power-ups
* App unlocks and premium tiers
**Physical Goods (Cannot Use Play Billing):**
* Physical merchandise
* Real-world services
* One-time donations to nonprofits
:::note Subscription Setup In Play Console, configure Android subscriptions using the current **subscription -> base plan -> offer** model. In `native-purchases`, pass the Base Plan ID with `planIdentifier`. :::
### Implementation with Native Purchases
[Section titled âImplementation with Native Purchasesâ](#implementation-with-native-purchases)
```typescript
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
// Ensure billing is available on the device
const { isBillingSupported } = await NativePurchases.isBillingSupported();
if (!isBillingSupported) throw new Error('Google Play Billing not available');
// Fetch subscription products (Store data is requiredânever hardcode pricing)
const { products } = await NativePurchases.getProducts({
productIdentifiers: ['premium_monthly', 'premium_yearly'],
productType: PURCHASE_TYPE.SUBS,
});
// Plan identifiers are the Base Plan IDs you create in Google Play Console
const transaction = await NativePurchases.purchaseProduct({
productIdentifier: 'premium_monthly',
planIdentifier: 'monthly-plan', // REQUIRED on Android, ignored on iOS
productType: PURCHASE_TYPE.SUBS,
});
console.log('Purchase token for server validation:', transaction.purchaseToken);
```
## Transparency and Disclosure Requirements
[Section titled âTransparency and Disclosure Requirementsâ](#transparency-and-disclosure-requirements)
### Upfront Pricing Disclosure
[Section titled âUpfront Pricing Disclosureâ](#upfront-pricing-disclosure)
Google Play mandates clear disclosure of all costs before purchase:
**Required Elements:**
* Exact price in userâs local currency
* Billing frequency (monthly, yearly, etc.)
* Whatâs included in the subscription
* Total cost for introductory offers
* When charges will occur

**Example of Compliant UI:**
```typescript
function SubscriptionCard({ product }) {
return (