К основному содержанию
скилл CX Codex

mobile-platform-native-capabilities-integrate — скилл для Claude Code

Помогает собрать Salesforce LWC с нативными функциями мобильного устройства: сканированием, геолокацией, NFC и платежами. Нужен при работе с lightning/mobileCapabilities.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add forcedotcom/sf-skills --skill mobile-platform-native-capabilities-integrate -a claude-code
Открыть на GitHub

Что делает mobile-platform-native-capabilities-integrate

Скилл направляет агента к подходящей функции lightning/mobileCapabilities и её типам. Он охватывает сканер штрихкодов и документов, биометрию, геолокацию, геозоны, календарь, контакты, NFC, захват AR-пространства, отзывы в приложении и платежи.

Для каждой функции агент импортирует фабрику, создаёт сервис и проверяет isAvailable() перед вызовом. Затем он использует актуальный API, оборачивает промисы в try/catch и различает отмену, отказ в разрешении и недоступность сервиса. Проверка isAvailable() обязательна: на desktop и в мобильном вебе сервис вернётся, но сама возможность будет недоступна.

LWC должен запускаться в Salesforce Mobile App или Field Service Mobile App. Для проверки мобильной офлайн-готовности нужен другой скилл mobile-platform-offline-validate, а для выбора базовых компонентов Lightning — design-systems-slds-apply.

Какие задачи решает

  • добавить сканирование штрихкода в Salesforce LWC
  • запросить биометрическую проверку на устройстве
  • прочитать координаты и отслеживать геозону
  • создать событие в календаре устройства
  • считать или записать NFC-метку

Примеры запросов агенту

  • Создай LWC, который сканирует штрихкод через lightning/mobileCapabilities и сохраняет результат в поле.
  • Добавь в компонент проверку биометрии и обработай отказ в разрешении.
  • Сделай LWC с получением геолокации, проверкой isAvailable() и сообщением для недоступного сервиса.

Как установить mobile-platform-native-capabilities-integrate

1Через Skills CLI (Vercel)

npx skills add forcedotcom/sf-skills --skill mobile-platform-native-capabilities-integrate -a claude-code

2Вручную: положить файлы

~/.claude/skills/mobile-platform-native-capabilities-integrate/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/mobile-platform-native-capabilities-integrate/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о mobile-platform-native-capabilities-integrate

Как установить mobile-platform-native-capabilities-integrate в Claude Code?

Выполните npx skills add forcedotcom/sf-skills --skill mobile-platform-native-capabilities-integrate -a claude-code, затем ещё раз npx skills add forcedotcom/sf-skills --skill mobile-platform-native-capabilities-integrate -a claude-code. После установки используйте ~/.claude/skills/mobile-platform-native-capabilities-integrate/SKILL.md.

Что делает mobile-platform-native-capabilities-integrate?

Скилл помогает агенту подключать нативные функции устройства к Salesforce LWC через lightning/mobileCapabilities. Он задаёт порядок выбора сервиса, чтения его типов, проверки доступности и обработки ошибок.

Где работают мобильные возможности Salesforce LWC?

Они доступны, когда LWC запущен в Salesforce Mobile App или Field Service Mobile App. На desktop и в мобильном вебе каждый вызов нужно проверять через isAvailable().

Исходный текст

SKILL.md · Apache-2.0
---
name: mobile-platform-native-capabilities-integrate
description: "Build a Salesforce LWC that uses native mobile device capabilities — barcode scanner, biometrics, location, NFC, calendar, contacts, document scanner, geofencing, AR space capture, app review, and payments. Use this skill when the user asks for an LWC that scans a barcode, captures a photo of a document, reads location or geofences, prompts for biometrics, reads/writes the device calendar or contacts, taps NFC, takes a payment, prompts for an app review, or scans an AR space. Also triggers on \"lightning/mobileCapabilities\", \"mobile capability\", \"Nimbus\", \"device capability\". Do not use for mobile offline / Komaci priming reviews (use `mobile-platform-offline-validate`) or for picking generic Lightning base components (use `design-systems-slds-apply`)."
metadata:
  version: "1.0"
  domains: ["Mobile"]
  relatedSkills:
    - "design-systems-slds-apply"
    - "mobile-platform-offline-validate"
---

# Using Mobile Native Capabilities

The `lightning/mobileCapabilities` module exposes a set of factory functions
that return service objects for native device features (barcode scanning,
biometrics, location, etc.). Each service extends a common
[BaseCapability](references/base-capability.md) with an `isAvailable()`
method, so an LWC can degrade gracefully on surfaces where the capability is
not present (desktop, mobile web).

This skill routes an agent through (1) picking the right capability, (2)
loading the authoritative type definitions, and (3) wiring the service into
an LWC with the correct availability gating, error handling, and
deprecation-aware API choice.

## When to Use This Skill

- User asks for an LWC that uses a device capability listed in the index
  below.
- User mentions `lightning/mobileCapabilities`, "mobile capability", or
  "Nimbus" by name.
- User wants to know which mobile native APIs are available, or which one
  fits their feature.

Do NOT use this skill for:

- Mobile-offline review of an LWC (lwc:if, inline GraphQL, Komaci-priming
  violations) — use `mobile-platform-offline-validate`.
- Choosing or styling generic Lightning Base Components / SLDS blueprints —
  use `design-systems-slds-apply`.

## Prerequisites

- Knowledge that the LWC will run inside a supported mobile container
  (Salesforce Mobile App, Field Service Mobile App). These capabilities are
  unavailable on desktop and mobile web; gate every call behind
  `isAvailable()`.
- Familiarity with the `lightning/mobileCapabilities` module declaration
  (see [mobile-capabilities](references/mobile-capabilities.md)).

## Capability Index

| Capability | Reference | One-line use |
| --- | --- | --- |
| App Review | [App Review](references/app-review.md) | Prompt the user for a native in-app review. |
| AR Space Capture | [AR Space Capture](references/ar-space-capture.md) | Capture a 3D scan of a physical space using AR. |
| Barcode Scanner | [Barcode Scanner](references/barcode-scanner.md) | Read QR / UPC / EAN / Code-128 / etc. from the camera. |
| Biometrics | [Biometrics](references/biometrics.md) | Authenticate via Face ID / fingerprint. |
| Calendar | [Calendar](references/calendar.md) | Read or create events on the device calendar. |
| Contacts | [Contacts](references/contacts.md) | Read or create entries in the device address book. |
| Document Scanner | [Document Scanner](references/document-scanner.md) | Scan paper documents using the camera with edge detection. |
| Geofencing | [Geofencing](references/geofencing.md) | Trigger logic when the device crosses a geographic boundary. |
| Location | [Location](references/location.md) | Read GPS coordinates and watch for updates. |
| NFC | [NFC](references/nfc.md) | Read or write NFC tags. |
| Payments | [Payments](references/payments.md) | Take an Apple Pay / Google Pay payment. |

## Workflow

### Step 1 — Identify the capability

Map the user's feature ask to one row of the capability index. If the ask
spans multiple capabilities (e.g. "scan a barcode and store it on a
contact"), plan for **each** capability separately — there is one factory
function per capability.

### Step 2 — Load the shared and capability-specific references

Read these two shared references **once** per session — they apply to every
capability and are not duplicated in the per-capability files:

- [BaseCapability](references/base-capability.md) — the common interface
  with `isAvailable()` that every service extends.
- [mobile-capabilities](references/mobile-capabilities.md) — the
  `lightning/mobileCapabilities` module declaration showing every
  re-exported service.

Then open the capability's reference file from the table above. Each
per-capability reference contains the service-specific TypeScript API
(factory function, service interface, options types, result types, error
types) and assumes the two shared references above are already in context.

Do not infer the API from memory — read it. The services evolve and some
methods are explicitly `@deprecated` in favor of newer alternatives.

### Step 3 — Wire the service into the LWC

For each capability:

1. Import the factory from `lightning/mobileCapabilities`:
   ```js
   import { getBarcodeScanner } from 'lightning/mobileCapabilities';
   ```
2. Get an instance: `const scanner = getBarcodeScanner();`
3. Gate the call behind `isAvailable()`:
   ```js
   if (!scanner.isAvailable()) {
     // graceful fallback or user message
     return;
   }
   ```
4. Call the **non-deprecated** entry point. Several services keep older
   methods marked `@deprecated` alongside the recommended one — always
   prefer the recommended method in the reference.
5. Wrap the promise in `try/catch` and handle the typed failure codes the
   service exposes (e.g. `BarcodeScannerFailureCode`,
   `LocationServiceFailureCode`). User-cancelled vs. permission-denied vs.
   service-unavailable are distinct UX states.

### Step 4 — Surface failure modes to the user

Each service defines its own failure-code enum. Translate codes into
user-actionable messages: a `USER_DENIED_PERMISSION` should ask the user to
grant permission; a `USER_DISABLED_PERMISSION` must direct them to the OS
settings; a `SERVICE_NOT_ENABLED` should be a developer-visible error, not
shown to the user.

### Step 5 — Stay inside the supported surface

Mobile capabilities are available **only** when the LWC runs inside a
supported Salesforce mobile app. If the same component is rendered on
desktop or mobile web, the factory will still return an object but
`isAvailable()` will return `false`. Never assume availability — gate every
call.


## Examples

### Example — "Scan a barcode and write it into a field"

1. Map to: Barcode Scanner.
2. Read [Barcode Scanner](references/barcode-scanner.md).
3. Use `scan(options)` (not the deprecated `beginCapture` / `resumeCapture`
   / `endCapture` triple).
4. In options, set the `barcodeTypes` to the symbologies needed (default is
   all supported types) and `enableMultiScan: false` for a single read.
5. On resolve, write `result[0].value` to the bound field. On reject,
   inspect `error.code` against `BarcodeScannerFailureCode`.

### Example — "Take an Apple Pay payment for an order total"

1. Map to: Payments.
2. Read [Payments](references/payments.md).
3. Gate on `isAvailable()`.
4. Build the payment request object per the reference.
5. On resolve, surface the transaction id to the calling flow. On reject,
   handle user-cancelled and payment-failed paths separately.


## Verification Checklist

- [ ] Every capability call is preceded by `isAvailable()`.
- [ ] The non-deprecated entry point is used (no `beginCapture` /
      `resumeCapture` / `endCapture` for barcode, etc.).
- [ ] Each rejection path is mapped to the typed failure code enum.
- [ ] Imports come from `lightning/mobileCapabilities`, not from a private
      path.
- [ ] No assumption that the capability runs on desktop or mobile web.


## Troubleshooting

- **`isAvailable()` returns `false` on a real device** — the device is
  running an unsupported app surface (not Salesforce Mobile or Field
  Service Mobile), or the service is gated by an org-level setting. The
  fix is org configuration, not code.
- **TypeScript can't find the import** — confirm the LWC has access to
  `lightning/mobileCapabilities`. The module is declared globally inside
  Salesforce mobile containers; outside that, the types must be installed
  separately.
- **Deprecated barcode methods still work** — yes, but new code must use
  `scan()` and `dismiss()`. Refactor any sample code the agent received
  before returning it.
- **Multiple capabilities in one component** — get separate instances per
  capability (they are independent service objects); do not try to share
  state between them.

© forcedotcom · Apache-2.0 · forcedotcom/sf-skills

Похожие скиллы

Всё по теме «Мобильная разработка» →
salesforce-component-standards официальный github Задаёт стандарты разработки компонентов Salesforce для LWC, Aura и Visualforce. Помогает настроить безопасность, доступ к данным и интерфейс. 770установок Salesforce UI Development (Aura & LWC) официальный github Субагент для GitHub Copilot, который собирает компоненты Lightning Web Components и Aura с оглядкой на доступность и SLDS. ★ 40 418звёзд репо salesforce-development Mindrally Скилл задаёт агенту правила разработки на Salesforce: Apex, триггеры, Lightning Web Components, SOQL и метаданные. Пригодится, когда пишете код для org и хотите, чтобы агент держал стиль и лимиты платформы. CX Codex +1 659установок mobile-native emilkowalski Убирает мелочи, из-за которых веб-приложение на телефоне выдаёт себя: залипающий hover, вспышку при тапе, ошибку с 100vh. CX Codex +1 86 600установок godot-platform-mobile thedivergentai Скилл для ИИ-агента, который ведёт мобильную сборку Godot: тач-ввод, вырезы экрана, троттлинг и права Android. CX Codex +1 421установок native-feel-cross-platform-desktop yetone Скилл для проектирования кросс-платформенных десктопных приложений, которые ощущаются нативными: окна, хоткеи, материалы, запуск. CX Codex +1 608установок

Из того же набора167

omnistudio-datamapper-generate Скилл собирает и проверяет OmniStudio Data Mapper: Extract, Transform, Load и Turbo Extract с оценкой по 100-балльной шкале. Пригодится, когда нужно разметить поля объектов Salesforce. CX Codex +1 4 800установок dx-code-analyzer-custom-rule-create Скилл помогает создавать пользовательские правила для Salesforce Code Analyzer на базе Regex, PMD и ESLint. Пригодится, когда встроенных проверок кода Apex или метаданных недостаточно. CX Codex +1 4 800установок commerce-b2b-store-create Ведёт по шагам к созданию B2B-магазина Commerce в Salesforce и выгружает метаданные витрины в репозиторий. Пригодится, когда нужно развернуть витрину из уже готового магазина. CX Codex +1 4 700установок mobile-platform-offline-validate Проверяет компоненты LWC на совместимость с офлайн-режимом Komaci в Salesforce Mobile App Plus. Находит ошибки прайминга и формирует исправления кода. CX Codex +1 4 700установок commerce-b2b-open-code-components-replace Меняет стандартные B2B Commerce компоненты на открытые аналоги в content.json метаданных сайта. Или просто показывает соответствия, если менять файлы не нужно. CX Codex +1 4 600установок commerce-b2b-open-code-components-integrate Копирует открытые компоненты Salesforce B2B Commerce из GitHub в метаданные сайта магазина, чтобы они появились в палитре Experience Builder. CX Codex +1 4 600установок platform-policy-rule-generate Помогает писать метаданные PolicyRuleDefinition и PolicyRuleDefinitionSet для Salesforce Data Cloud: схема, дерево категорий, проверки перед деплоем. CX Codex +1 4 100установок platform-custom-report-type-generate Помогает агенту создавать и проверять метаданные Salesforce Custom Report Type: база, связи, доступные поля. Пригодится при разборе ошибок деплоя .reportType-meta.xml. CX Codex +1 4 000установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой