本文へ移動

Apsule Host API ​

実装ステータス: 実行可能なHostはruntime discoveryで報告されるAPI familyを実装しています。networking、project data/files、timer/crypto、image/document processing、Local Network、Location/BLE、Camera/Audio/Photos、Apple Music、AuthenticationServices、WeatherKit、Translation、Nearby Interaction、Core Spotlight、Wallet/PassKit、Notifications、Background Tasks、system utilities、Live Activities、Biometrics、Vision、Contacts、Calendar/Reminders、Motion、Speech、geocoding/directions、NFC、HealthKit、HomeKit、Widget state、WebView controlなどが含まれます。インストール済みHostについてはruntime discoveryが正本です。Apple entitlement/capabilityに依存するfamilyは、signed Hostに必要なものがない場合、runtime/platform errorを返すことがあります。

命名 ​

Host APIとは、iPhone上のApsule Hostがproject JavaScriptへ公開するnative functionalityを指します。意図的にCapabilityとは呼びません。Capabilityという用語はConductor用に予約されています。

すべてのAPIはhost.<family>.<operation>配下にあります。

javascript
await host.http.request(...);
await host.location.current(...);
await host.bluetooth.scan(...);

有限operationにはPromise-based call、streamにはcancel可能なsubscription/eventを使います。新しいHost API familyはfamily固有のcallback/synchronous conventionを作らず、この共通grammarに従います。

共通動作 ​

すべてのHost APIは次を満たす必要があります。

  • native access前にproject permissionをvalidateする。
  • 明示的に別途記載しない限りJSON-serializable valueを返す。
  • 共通のstructured error shapeを使う。
  • 意味がある場合はcancellation/timeoutに対応する。
  • secretを漏らさずruntime consoleへ有用なdiagnosticを出す。
  • runtime feature/schema discoveryから検出できる。

Host rebuildを減らす: high-level API + constrained raw API ​

ApsuleではProject feature追加のたびに必要となるHost rebuildを最小化します。インストール済みHostとは独立してremote APIが進化できるnative/service integrationでは、2層構造のHost APIを優先します。

  1. High-level wrapper: 一般的なoperation向け。安定して使いやすいProject APIを提供し、error/resultをnormalizeし、permissionを強制し、provider credential/tokenを隠します。
  2. 制限付きraw/provider request API: 新しいiOS framework、entitlement、Info.plist declaration、extension、その他compile-time Host capabilityを必要としない対応operation向け。

raw layerは無制限networkingではありません。provider scopeとpermission gateを維持します。provider credentialとuser tokenはHost内部に保持し、許可destination/methodを制限し、responseは通常のJSON-serializable Host API contractへ変換します。Projectが利用前にcompatibilityを確認できるよう、runtime discoveryはraw APIを別にadvertiseする必要があります。

たとえばApple Music integrationでは、playback、queue、library、history、recommendationなどの一般操作向けAPIに加え、MusicKit/Apple Music authenticationをHostが安全に適用できる制限付きApple Music API request primitiveを公開します。Appleが将来互換性のあるREST endpointを追加した場合、理想的にはApsuleをrebuildせずProjectから利用できます。

一方、新しくcompileされたnative framework/API surface、新entitlement/signing capability、新しいInfo.plist usage description/background mode、extension、Project JavaScriptから動的追加できないplatform-level declarationが必要な場合はHost rebuildが必要です。

提案するerror shape:

json
{
  "code": "bluetooth.service_not_found",
  "message": "Requested service was not found.",
  "details": {}
}

Network ​

host.http.request(options) ​

generic HTTP clientで、次に対応します。

  • GET/POST/PUT/PATCH/DELETEおよび任意のstandard method。
  • header。
  • query parameter。
  • JSON/text/binary request body。
  • JSON/text/binary response。
  • timeout。
  • multipart upload。

game stats APIなどAPI固有のintegrationは通常、このprimitive上にproject JavaScriptとして実装し、Hostへ追加しません。

実行可能clientはJSON/text body、Base64 binary body、Project-sandbox file body、multipart field/file、Base64 binary response、responseをProject sandboxへ直接保存するdownloadToに対応します。file-backed request/response modeでは追加でstorage: trueが必要です。

HTTP cookieはprocess-global cookie storeではなく、実行中Project runtimeごとに分離します。

  • host.cookies.list(options)
  • host.cookies.set(options)
  • host.cookies.delete(options)
  • host.cookies.clear()

requestはdefaultでこのcookie jarを使います。無効にする場合はrequestへcookies: falseを渡します。

host.webAuthentication.authorize(options) ​

Passkey/OAuth形式のbrowser authentication用にASWebAuthenticationSessionを表示し、callback URLをproject JavaScriptへ返します。Projectのnetwork permissionが必要です。現在のHostはHTTPS url、登録済みcallbackScheme: "apsule"、optionalなprefersEphemeralSessionを受け取り、resolved valueにはurl、scheme、host、string query objectを含めます。callback schemeをHost所有のapsule schemeに限定することで、他のinstalled appが所有するcallbackをprojectが偽装することを防ぎます。

WebSocket ​

  • host.websocket.connect(options)
  • connectionのsend/close。
  • message/open/close/error event subscription。

connect(options, onEvent)はconnection handleのPromiseを返します。handleはconnectionId、send(message)、close(code, reason)を公開します。textとBase64 binary payloadに対応し、Project runtime停止時にconnectionを自動closeします。

SSEとprogress transfer ​

  • host.sse.connect(options, onEvent) / host.sse.close(id)
  • host.transfer.download(options, onEvent)
  • host.transfer.upload(options, onEvent)
  • host.transfer.cancel(id)

SSEはstandardなevent、data、id、retry fieldをparseし、cancel可能なconnectionを返します。file transferにはNetworkとStorage permissionの両方が必要です。download/upload callbackはstart、byte progress、complete、error、cancelled eventを受け取り、call自体はcancel可能なtransfer handleを即時返します。

Storage ​

  • host.storage.get(key)
  • host.storage.set(key, value)
  • host.storage.delete(key)
  • host.storage.list(options)

StorageはApsule Project単位でnamespace化されます。

現在の実装はJSON-serializable valueをproject Sandbox内へ永続化し、manifestでstorage: trueを宣言していない場合はaccessを拒否します。

Database ​

  • host.database.execute(statement, parameters)
  • host.database.query(statement, parameters)

実装にはSQLiteを使用できます。database fileはdefaultでproject scopeにします。

実行可能Hostはproject Sandboxごとに1つのSQLite databaseを使います。statementはJSON arrayとして渡すpositional ? parameterに対応します。executeはaffected-row countとlast insert row idを返し、queryはJSON-serializable row objectを返します。現在database accessにはprojectのstorage permissionを使います。

Files ​

  • host.files.read(path, options)
  • host.files.write(path, data, options)
  • host.files.list(path)
  • host.files.delete(path)
  • host.files.pick(options)
  • host.files.export(paths)
  • host.files.createDirectory(path)
  • host.files.move(source, destination)
  • host.files.copy(source, destination)

default read/writeはproject sandbox内に制限します。userが明示的に選択したfileは、任意のglobal filesystem pathではなくscoped handleとして表現できます。

実行可能Hostはsandbox内のread/write/list/delete/createDirectory/move/copyとnative import/export pickerを実装します。readはdecode可能ならUTF-8 textに加えてBase64とbyte sizeを返します。writeは{ text }または{ base64 }を受け取ります。import fileはProject sandboxへcopyし、exportは明示的に指定されたsandbox fileだけを公開します。Files accessにはProjectのstorage permissionを使います。

Keychain ​

  • host.keychain.get(key)
  • host.keychain.set(key, value)
  • host.keychain.delete(key)

token/secretにはplain project storageではなくこちらを使います。

実行可能HostはKeychain itemをproject IDでnamespace化し、device-only Keychain accessibilityを使ってJSON-serializable valueを保存します。現在Keychain accessにはprojectのstorage permissionを使います。

Location ​

  • host.location.authorization()
  • host.location.current(options)
  • host.location.watch(options, callback)
  • host.location.heading(options, callback)
  • host.location.monitorRegion(options, callback)
  • host.location.stopMonitoringRegion(id)
  • host.location.monitoredRegions()
  • host.location.monitorVisits(callback)

実行可能Hostはcurrent position、継続location/heading stream、circular regionのenter/exit monitoring、visit monitoringを実装します。watch系operationはcancel可能handleを返します。region/visit monitoringにはProjectのlocation: "always"が必要で、foregroundのcurrent/watch/headingはwhenInUseでも利用できます。

foreground locationがあるだけでbackground locationが暗黙許可されることはありません。明示的なHost/runtime supportと適切なiOS configurationが必要です。

Bluetooth Low Energy ​

CoreBluetoothを利用します。実行可能Hostは次を実装します。

  • host.bluetooth.authorization()
  • host.bluetooth.scan(options)
  • host.bluetooth.stopScan()
  • host.bluetooth.connect(deviceId, options)
  • host.bluetooth.disconnect(deviceId)
  • host.bluetooth.services(deviceId)
  • host.bluetooth.characteristics(deviceId, serviceId)
  • host.bluetooth.read(request)
  • host.bluetooth.write(request)
  • host.bluetooth.subscribe(request, callback)

subscriptionはcancel可能handleを返します。

projectへ公開するdevice identifierはiOS/CoreBluetoothが許す範囲でのみstableです。project logicはhardware MAC-address accessを前提にしてはいけません。

CameraとPhotos ​

  • host.camera.capture(options)
  • host.camera.captureDirect(options)
  • host.camera.startRecording(options)
  • host.camera.pauseRecording()
  • host.camera.resumeRecording()
  • host.camera.stopRecording()
  • host.camera.recordingStatus()
  • host.camera.list()
  • host.camera.capabilities(position)
  • host.camera.setZoom(options)
  • host.camera.setTorch(options)
  • host.camera.focus(options)
  • host.camera.setExposure(options)
  • host.audio.startRecording(options)
  • host.audio.stopRecording()
  • host.audio.recordingStatus()
  • host.photos.authorization()
  • host.photos.pick(options)
  • host.photos.save(asset, options)
  • host.photos.list(options)
  • host.photos.get(id)
  • host.photos.albums(options)
  • host.photos.createAlbum(options)
  • host.photos.update(id, options)
  • host.photos.delete(options)
  • host.photos.addToAlbum(options)
  • host.photos.removeFromAlbum(options)

capture/selectされたmediaはProject sandboxへcopyし、安全なmetadataとして返します。capture()はsystem still-camera UIを表示し、captureDirect()はpickerを出さずAVCapturePhotoOutputを使います。Direct captureはposition/uniqueIdとflashに対応します。video recordingはQuickTime movieを書き出し、cameraとmicrophone accessが両方承認されている場合はmicrophone audioも含められます。recording optionはpositionまたはcamera uniqueId、resolution(4k、1080p、720p、480p)、fps、quality、audioに対応します。pause/resumeは内部recording segmentで実装し、stopRecording()でそれらを1つのmovie pathへmergeします。CameraPreview、VideoPlayer、AudioPlayer、MediaImageはsandbox pathをnative UIへ接続します。

PhotoKit accessはpicker/saveだけでなくlibrary managementにも対応します。photos: trueのProjectはasset/album一覧、album作成、favorite/hidden/creation-date metadata更新、asset削除、user albumへのasset追加・削除を行えます。iOSのread/write Photos authorizationは引き続き適用され、limited-library authorizationの場合はProjectから見えるassetもその範囲に制限されます。

record/import済みaudioはhost.media.waveform({ path, points })でwaveform peak bucketへ縮約できます。生成済みVideoPlayer/AudioPlayer nodeはnode idを使い、host.mediaPlayer.play、pause、seek、setVolume、setRate、statusでcontrolできます。

Notifications ​

  • host.notification.authorization()
  • host.notification.schedule(options)
  • host.notification.cancel(id)
  • host.notification.cancelAll()
  • host.notification.list()

Project Notification scopeはlocal notificationです。Apsule Host-level background synchronizationは別のRelay/APNs channelを使い、Projectのnotification permissionを消費しません。

実行可能Hostはone-shot/repeating time trigger、ISO date trigger、calendar-component trigger、title/subtitle/body、sound、badge、custom action button、cancellation、pending-list inspectionに対応します。identifier/categoryはProject namespaceです。Notification responseは対象Projectがactiveな間、actions.notification(payload)へ渡されます。

schedule済みlocal notificationはOS-managed persistent workです。iOSへの登録成功後、projectをstopまたは別projectへswitchしても暗黙cancelされません。listing/cancellation上はそのprojectが所有し続け、明示的なcancellation/removal policyでのみ削除します。

Apsule自体もproject update適用やsync failureなどHost-level event用にiOS local notificationを利用できます。これらのApsule System NotificationsはProject Notificationsとは別で、projectのnotification permissionを消費しません。

System utilities ​

  • host.clipboard.read()
  • host.clipboard.write(value)
  • host.haptics.trigger(style)
  • host.share.present(items, options)
  • host.url.open(url)
  • host.device.info()

これらは実装済みです。Clipboard accessはiOS pasteboard privacy behaviorに従い、share/URL operationはnative system presentation/openingを利用します。Hapticsはselection、success/warning/error、standard impact styleに対応します。

host.share.presentではProject-sandbox pathも共有できます。Apsuleには外部text/URL/image/file contentをProjectへ取り込むShare Extension/Open-In pathがあります。external URLはactions.openURL(payload)へ渡し、import fileはtarget Project sandboxへcopyします。

Apple Music ​

Apple Music accessにはProject permissionのmusic: trueと通常のMusicKit user authorizationが必要です。HostにはNSAppleMusicUsageDescriptionがありMusicKitをlinkします。Hostのsign/installに使用するApsule App IDでもApple MusicKit App Serviceを有効にする必要があります。

Authorization/subscription/storefront:

  • host.music.authorization.status()
  • host.music.authorization.request()
  • host.music.subscription.current()
  • host.music.subscription.showOffer(options)
  • host.music.storefront.current()

subscription.showOffer()はApple native subscription sheetを表示します。optional valueにはmessage: "join" | "addMusic" | "playMusic"、itemId、affiliateToken、campaignTokenがあります。ProjectへApple Music authentication tokenを返すことはありません。

Playbackとqueue control:

  • host.music.player.play(options)
  • host.music.player.prepare(options)
  • host.music.player.pause(options)
  • host.music.player.stop(options)
  • host.music.player.next(options)
  • host.music.player.previous(options)
  • host.music.player.seek(seconds, options)
  • host.music.player.status(options)
  • host.music.player.playbackState(options)
  • host.music.player.nowPlaying(options)
  • host.music.player.setShuffle(mode, options)
  • host.music.player.setRepeat(mode, options)
  • host.music.player.setCrossfade(options)
  • host.music.queue.get(options)
  • host.music.queue.replace({ items, player })
  • host.music.queue.playNext(options)
  • host.music.queue.playLater(options)
  • host.music.queue.setAffectsListeningHistory(enabled, options)

playback optionのdefaultは{ player: "system" }で、SystemMusicPlayer経由でMusic appをcontrolします。Apsule所有playbackを行う場合はApplicationMusicPlayerを使う{ player: "application" }を指定します。playable catalog song/music videoは{ id, kind: "song" | "musicVideo" }で選択できます。prepare()はplayback前に現在queueのprepareをMusicKitへ要求します。Crossfadeはapplication-playerのみで、iOS 26以降が必要です。queue.setAffectsListeningHistoryはiOS 26.4以降が必要で、それより前のOSではqueue.get()の該当fieldは利用不可として返します。

Catalog/library/service convenienceは同じprovider-scoped data bridge上に実装されています。

  • host.music.catalog.search/get/song/album/artist/playlist/musicVideo/station/radioShow/curator/recordLabel/genre/relationship/view
  • host.music.library.list/get/search/songs/albums/artists/playlists/musicVideos/recentlyAdded/relationship/add
  • host.music.playlist.create/get/getTracks/addTracks/rootFolder/folder/folderChildren/createFolder
  • host.music.favorites.add/status
  • host.music.ratings.get/set/remove
  • host.music.history.recentlyPlayed/recentlyPlayedTracks/recentlyPlayedStations/heavyRotation
  • host.music.recommendations.get/getAll/getById/contents
  • host.music.replay.summary/topSongs/topArtists/topAlbums
  • host.music.charts.get

generic catalog.relationship、catalog.view、library.get、library.relationship helperにより、Apple Music relationship/resource viewごとに新Host methodを追加する必要を減らします。これらも同じprovider-scoped Apple Music bridgeとProject music permissionを通ります。

Replayは現在Appleが対応するfilter[year]=latestを送ります。専用Replay helperはこのendpointで任意のhistorical yearをadvertiseしません。

low-level escape hatch:

javascript
const result = await host.music.api.request({
  method: "GET",
  path: "/v1/me/recent/played/tracks",
  query: { limit: 10, types: ["songs", "music-videos"] }
});

host.music.api.requestが受け付けるのはrelative /v1/... Apple Music API pathだけで、destinationは常にapi.music.apple.comへ固定します。Project codeはAuthorization headerを指定できず、MusicKit tokenも読めません。必要なprovider/user authenticationはHost内部でMusicKitが注入します。raw bridgeは現在GET、POST、PUT、PATCH、DELETEに対応し、安全なrepresentation header(Accept、Content-Type、Accept-Language)だけをforwardします。

この分割は意図的です。一般操作には安定したhigh-level wrapperを用意し、新たに追加された互換性のあるApple Music REST endpointは新しいApsule Host buildを待たずmusic.api.requestから利用できます。将来のApple Music機能そのものが新しいcompiled native support、Info.plist declaration、extension、signing/App Services、その他platform configurationを必要とする場合はHost rebuildが必要です。

AuthenticationServices ​

  • host.authentication.apple.signIn(options)
  • host.authentication.passkey.register(options)
  • host.authentication.passkey.assert(options)

これらにはauthentication: trueが必要です。Sign in with AppleはApple user identifierに加え、Appleが提供した場合はauthorization code/identity tokenをBase64 dataとして返します。Passkey registration/assertionはplatform authenticatorを利用し、Project JavaScriptがrelying-party identifierとWebAuthn challenge materialを渡し、server側検証に使うcredential/authenticator dataを受け取ります。

必要なAssociated Domains、Sign in with Apple capability、その他signing configurationはProjectからruntime中に作成できません。選択したflowに必要なApple capabilityがインストール済みHost signatureにない場合は、platform boundaryを弱めずcallを失敗させます。

WeatherKit ​

  • host.weather.current(options)
  • host.weather.hourly(options)
  • host.weather.daily(options)
  • host.weather.alerts(options)
  • host.weather.attribution()

Weather callにはweather: trueが必要で、latitude/longitudeを受け取ります。hourly/dailyではboundedなlimitも指定できます。resultはcondition、temperature、precipitation、alert metadataなどをJSON-friendlyな値で返します。Apple Weather dataの表示にはWeatherKit attributionが必要なため、attribution()からprovider name、legal page/text、Apple Weather mark URLも取得できます。

WeatherKitはsigned App ID/build側のApple Weather capability/service configurationにも依存します。runtime discoveryは含まれるcodeを報告するだけで、特定のsideload signatureでserviceが利用できることまでは保証しません。

Translation ​

  • host.translation.translate(options)
  • host.translation.supportedLanguages()
  • host.translation.availability(options)

translation: trueでsystem Translation framework sessionを利用できます。translationではoptions.textが必須で、sourceとtargetは任意のlanguage identifierです。sourceを省略すると、可能な場合frameworkが言語を判定します。Projectは対応BCP-47 language一覧を取得し、translation開始前にlanguage pairがinstalled/supportedか確認できます。SwiftUI translation task/sessionはHostが所有し、Project JavaScriptへはtranslated textと言語metadataだけを返します。

Nearby Interaction ​

  • host.nearbyInteraction.availability()
  • host.nearbyInteraction.create(callback)
  • host.nearbyInteraction.run(sessionId, options)
  • host.nearbyInteraction.pause(sessionId)
  • host.nearbyInteraction.close(sessionId)

nearbyInteraction: trueのProjectはNISessionを作成し、返されたdiscovery tokenをProject自身のtransportでpeerと交換した後、peer rangingを開始して対応deviceではdistance/direction eventを受け取れます。optionalなcamera assistanceは対応deviceでのみ有効化します。

Nearby Interactionのsupportはhardwareで異なり、一部configurationにはAppleのsigning capability/entitlementも必要です。Projectはsession開始前にavailability()でprecise distance、direction、camera assistanceの対応状況を確認できます。

Core Spotlight ​

  • host.spotlight.index(options)
  • host.spotlight.delete(options)
  • host.spotlight.clear()

spotlight: trueでProjectのcontentをon-device Spotlight indexへ公開できます。item identifierはProject IDでnamespace化し、clear()はそのProjectのdomainだけを削除して他Projectのindexを触りません。

Wallet / PassKit ​

  • host.wallet.availability()
  • host.wallet.add(options)

wallet: trueでWallet accessをgateします。add({ path })は追加でstorage: trueが必要で、Project sandbox内の.pkpassを読み込み、PKPassとして検証してApple native add-pass sheetを表示します。Projectが無関係なWallet dataへアクセスすることはありません。

Timerとutility crypto ​

JavaScript runtimeはbrowser-styleのsetTimeout、clearTimeout、setInterval、clearIntervalを提供します。Project停止時にactive timerをすべてcancelします。host.timer.sleep(ms)はaction code向けPromise-based equivalentです。

host.cryptoはrandomUUID、secure random byte、SHA-256/SHA-512 hash、HMAC、Base64 encode/decode、URL encode/decode、verificationを行わないJWT header/payload decodeを提供します。Hash/HMAC inputはpermissionなしでtextまたはBase64を利用できます。file-backed inputでは追加でStorageが必要で、Project sandbox内に制限されます。

Imageとdocument processing ​

  • host.image.info(path)
  • host.image.process(options)
  • host.image.thumbnail(options)
  • host.document.pdfInfo(path)
  • host.document.createPDF(options)
  • host.document.renderPage(options)
  • host.document.preview(path)
  • host.document.scan(options)

Image operationはsandbox-onlyで、crop、rotation、resize/max-dimension、JPEG/PNG/HEIC output、quality controlに対応します。PDF operationはsandbox documentのinspect、create、render、QuickLook previewに対応します。Document scanはVisionKitを使い、page imageと生成PDFを返します。document/image operationはすべてStorageが必要で、scanには追加でCameraが必要です。

Local Network ​

  • host.localNetwork.browse(options, onEvent)
  • host.localNetwork.stopBrowse(id)
  • host.localNetwork.connect(options, onEvent)
  • host.localNetwork.send(id, options)
  • host.localNetwork.close(id)

このfamilyはInternet HTTP accessとは別で、localNetwork: trueが必要です。Bonjour discoveryと直接TCP/UDP connectionに対応します。default Hostは一般的なBonjour service type(_apsule._tcp、_http._tcp、_https._tcp、_ssh._tcp)を宣言します。iOSではBonjour typeをInfo.plistへ宣言する必要があるため、別service typeにはHost rebuildが必要になる場合があります。

Permission introspection ​

host.permissions.summary()はProjectのeffective Host approvalを返します。status(name)はdirect status APIがある場合、そのapprovalとiOS authorizationを組み合わせます。request(name)はCamera、Microphone、Photos、Notifications、Contacts、Calendar、Reminders、Speechなど対応iOS permissionを明示的に要求します。その他familyは自身のHost APIを初回利用したときに引き続きpromptします。openSettings()はApsuleのiOS Settings pageを開きます。

Live Activities / Dynamic Island ​

  • host.liveActivity.authorization()
  • host.liveActivity.start(options)
  • host.liveActivity.update(id, state)
  • host.liveActivity.end(id, state)
  • host.liveActivity.list()

Live ActivitiesはActivityKit/WidgetKit-backed generic Apsule Widget Extensionを使います。Project stateはtitle、subtitle、status、detail、progress、SF Symbol iconなどのcommon fieldに対応します。このstable generic stateによりProject APIを変えず、将来Hostにpresentation templateを追加できます。start/update/endにはProject permission setのliveActivities: trueが必要です。local Live ActivitiesはRelayとは独立して動作します。remote ActivityKit push updateにはApple push entitlementを含むsigning setupとRelay APNs credentialが必要です。

Map ​

Mapは主にUI componentです。marker/polyline dataを扱い、map-tap/region-change eventをemitします。location dataはhost.locationから取得します。address lookupとroute calculationには次を使います。

  • host.geocoding.geocode(address)
  • host.geocoding.reverse(latitude, longitude)
  • host.directions.calculate(options)

Background Project actionとProject push ​

  • host.background.schedule(options)
  • host.background.list()
  • host.background.cancel(id)
  • host.background.cancelAll()

background jobはBGTaskSchedulerを使います。earliestSecondsやrepeated intervalはiOSへのhintでありexact timerではありません。appへexecution timeを与える時刻はsystemが決めます。job実行時、Apsuleは対象Projectをheadlessにloadし、設定actionをinvokeし、そのPromiseを待ってからruntimeをstopします。

HostはRelay/APNs Project eventも受信できます。push: true、device APNs registration、Relay APNs credentialが必要です。actions.push({ name, data, receivedAt })へdeliveryします。このProject event channelはHost update commandともlocal-notification permissionとも別です。

BiometricsとVision ​

  • host.biometrics.status()
  • host.biometrics.evaluate(options)
  • host.vision.recognizeText(options)
  • host.vision.barcodes(options)

BiometricsはLocalAuthenticationを使いbiometrics: trueが必要です。VisionはProject-sandbox imageを読むためstorage accessが必要です。OCRはrecognized text/confidence/bounds、barcode detectionはpayload/symbology/confidence/boundsを返します。

Contacts、Calendar、Reminders ​

  • host.contacts.authorization() / list(options) / create(options) / update(id, options) / delete(id)
  • host.calendar.listCalendars() / listEvents(options) / createEvent(options) / updateEvent(id, options) / deleteEvent(id)
  • host.reminders.list(options) / create(options) / update(id, options) / delete(id)

これらはContacts/EventKitに対するpermission-gated CRUD wrapperです。event/reminder updateではdate、completion state、notes/location、relative alarmなど一般的なmetadataを扱えます。Projectがpermissionを宣言しただけでHostがaccessを許可することはなく、通常のiOS authorization promptも適用されます。

MotionとSpeech ​

  • host.motion.availability()
  • host.motion.watch(type, options, callback)
  • host.motion.pedometer(options)
  • host.motion.pedometerWatch(options, callback)
  • host.motion.activityWatch(callback)
  • host.speech.authorization()
  • host.speech.transcribe(options)
  • host.speech.speak(options)
  • host.speech.stop()

Motionはaccelerometer、gyro、device-motion、magnetometer updateをcancel可能subscriptionとしてstreamします。Pedometer APIは対応deviceでstep count、distance、floor、pace/cadenceを公開し、activity monitoringはstationary/walking/running/automotive/cycling classificationを返します。speech-to-textはProject-sandbox audio fileを対象とし、Speech、Microphone、Storage approvalが必要です。text-to-speechはfileなしでSpeech permissionを使います。

NFC、Health、Home ​

  • host.nfc.availability() / scan(options) / write(options)
  • host.health.availability() / authorize(options) / queryQuantity(options) / saveQuantity(options)
  • host.home.authorization() / listHomes() / accessories(homeId)
  • host.home.readCharacteristic(homeId, characteristicId) / writeCharacteristic(homeId, characteristicId, value)
  • host.home.actionSets(homeId) / executeActionSet(homeId, actionSetId)

NFCはNDEF recordのreadに加え、writable tagへtext、URL、または明示的にencodeしたNDEF record setを書き込めます。HomeKitはhome一覧だけでなくhome/accessory/service/characteristic graph、characteristic read/write、action-set実行まで公開します。これらのAPIはgeneric wrapperとして実装されていますが、Apple側でもsigning entitlement/capabilityによって制限されます。default Apsule signing configurationはrestricted entitlementを強制追加しません。含まないdevelopment/sideload profileを壊してしまうためです。device上で利用するには、対応entitlementを含むHost buildが必要です。

WebView control ​

WebViewは明示的opt-in componentのままです。各instanceはnon-persistent WebKit data storeを使い、あるProject/WebViewが別instanceのcookieを引き継がないようにします。Project JavaScriptはnode IDを指定してhost.webView.back、forward、reload、evaluateで生成済みWebViewをcontrolできます。host.webView.cookies.list/set/delete/clearはそのinstanceのWebKit cookie storeだけをcontrolします。pageはwindow.webkit.messageHandlers.apsule.postMessage(...)からJSON-compatible messageを返せ、それがnodeのmessage eventになります。popup/new-window navigationは管理外browser stateを新規生成せず、同じWebViewへredirectします。

Home-screen Project widget ​

WidgetKit extensionには設定可能なApsule Project launcher widgetがあります。userがProject ID/title/subtitle/iconを設定し、tapするとapsule://runを開いてHostがそのinstalled Projectをlaunchします。host.widget.update({ title, subtitle, value, progress, icon })とhost.widget.clear()はgeneric data-driven display stateを提供します。shared dynamic stateにはHostとWidget extensionが設定済みApsule App Group付きでsignされている必要があります。そのentitlementがない場合は、更新したふりをせずAPIが明示的に失敗します。

App Intents / Shortcuts ​

HostにはgenericなRun Apsule Action App Intentが含まれます。Shortcutsからinstalled Project ID、action name、JSON payloadを渡せます。Apsuleは要求されたProjectを開き、通常のpermission approval flowを適用した後、渡されたpayloadでそのProject actionをinvokeします。Project固有intentをHostへcompileすることは意図的に行いません。

Platform制約 ​

Runtime discoveryが説明するのはHostに含まれるcodeであり、特定signature/profileへAppleが付与したcapabilityではありません。entitlement-restricted APIは利用できない場合、deviceが対応しているふりをせず明示的に失敗する必要があります。background executionはopportunisticで、system privacy indicatorはiOSが管理し、extensionもiOS sandbox/privacy ruleを回避できません。