@circle-fin/daa-react-native-sdk 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DaaReactNativeSdk.podspec +69 -0
- package/LICENSE +176 -0
- package/README.md +691 -2
- package/android/build.gradle +102 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +104 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +107 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +318 -0
- package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +122 -0
- package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
- package/build/DaaClient.d.ts +237 -0
- package/build/DaaClient.js +442 -0
- package/build/api/AccountLimitsClient.d.ts +79 -0
- package/build/api/AccountLimitsClient.js +142 -0
- package/build/api/AccountsClient.d.ts +98 -0
- package/build/api/AccountsClient.js +279 -0
- package/build/api/AchFiatAccountsClient.d.ts +92 -0
- package/build/api/AchFiatAccountsClient.js +142 -0
- package/build/api/AuthClient.d.ts +95 -0
- package/build/api/AuthClient.js +221 -0
- package/build/api/ContractExecutionsClient.d.ts +114 -0
- package/build/api/ContractExecutionsClient.js +462 -0
- package/build/api/DaaUserClient.d.ts +187 -0
- package/build/api/DaaUserClient.js +312 -0
- package/build/api/DepositAddressesClient.d.ts +112 -0
- package/build/api/DepositAddressesClient.js +222 -0
- package/build/api/DepositsClient.d.ts +106 -0
- package/build/api/DepositsClient.js +183 -0
- package/build/api/FiatAccountsClient.d.ts +43 -0
- package/build/api/FiatAccountsClient.js +46 -0
- package/build/api/TransactionsClient.d.ts +64 -0
- package/build/api/TransactionsClient.js +121 -0
- package/build/api/TransfersClient.d.ts +107 -0
- package/build/api/TransfersClient.js +324 -0
- package/build/api/WireFiatAccountsClient.d.ts +99 -0
- package/build/api/WireFiatAccountsClient.js +156 -0
- package/build/api/WithdrawalsClient.d.ts +97 -0
- package/build/api/WithdrawalsClient.js +308 -0
- package/build/api/deviceApproval.d.ts +48 -0
- package/build/api/deviceApproval.js +247 -0
- package/build/api/deviceStatus.d.ts +61 -0
- package/build/api/deviceStatus.js +216 -0
- package/build/api/loginFailure.d.ts +51 -0
- package/build/api/loginFailure.js +95 -0
- package/build/api/pagination.d.ts +29 -0
- package/build/api/pagination.js +50 -0
- package/build/api/queryParameters.d.ts +23 -0
- package/build/api/queryParameters.js +77 -0
- package/build/api/resourceRequest.d.ts +60 -0
- package/build/api/resourceRequest.js +79 -0
- package/build/api/signedResource.d.ts +124 -0
- package/build/api/signedResource.js +267 -0
- package/build/auth/RegistrationFlowKey.d.ts +93 -0
- package/build/auth/RegistrationFlowKey.js +203 -0
- package/build/auth/daaRegistrationNative.d.ts +58 -0
- package/build/auth/daaRegistrationNative.js +158 -0
- package/build/auth/deviceAuthorization.d.ts +87 -0
- package/build/auth/deviceAuthorization.js +295 -0
- package/build/auth/ownerGrant.d.ts +29 -0
- package/build/auth/ownerGrant.js +90 -0
- package/build/auth/registrationAuthorization.d.ts +48 -0
- package/build/auth/registrationAuthorization.js +246 -0
- package/build/auth/registrationCodeVerifier.d.ts +31 -0
- package/build/auth/registrationCodeVerifier.js +75 -0
- package/build/config.d.ts +106 -0
- package/build/config.js +131 -0
- package/build/crypto/base64url.d.ts +26 -0
- package/build/crypto/base64url.js +87 -0
- package/build/crypto/bytes.d.ts +27 -0
- package/build/crypto/bytes.js +32 -0
- package/build/crypto/jwkThumbprint.d.ts +32 -0
- package/build/crypto/jwkThumbprint.js +49 -0
- package/build/crypto/matchingCode.d.ts +47 -0
- package/build/crypto/matchingCode.js +93 -0
- package/build/crypto/random.d.ts +35 -0
- package/build/crypto/random.js +106 -0
- package/build/crypto/serialization.d.ts +26 -0
- package/build/crypto/serialization.js +43 -0
- package/build/crypto/sha256.d.ts +18 -0
- package/build/crypto/sha256.js +100 -0
- package/build/errors.d.ts +307 -0
- package/build/errors.js +413 -0
- package/build/index.d.ts +69 -0
- package/build/index.js +67 -0
- package/build/models/Account.d.ts +201 -0
- package/build/models/Account.js +147 -0
- package/build/models/AccountLimitsUsage.d.ts +169 -0
- package/build/models/AccountLimitsUsage.js +86 -0
- package/build/models/Ach.d.ts +135 -0
- package/build/models/Ach.js +184 -0
- package/build/models/AddressObject.d.ts +128 -0
- package/build/models/AddressObject.js +141 -0
- package/build/models/BusinessPii.d.ts +84 -0
- package/build/models/BusinessPii.js +142 -0
- package/build/models/ContractExecution.d.ts +197 -0
- package/build/models/ContractExecution.js +130 -0
- package/build/models/CreateAccountRequest.d.ts +74 -0
- package/build/models/CreateAccountRequest.js +19 -0
- package/build/models/CreateContractExecutionRequest.d.ts +81 -0
- package/build/models/CreateContractExecutionRequest.js +19 -0
- package/build/models/CreateTransferRequest.d.ts +91 -0
- package/build/models/CreateTransferRequest.js +19 -0
- package/build/models/CreateWithdrawalRequest.d.ts +99 -0
- package/build/models/CreateWithdrawalRequest.js +19 -0
- package/build/models/DaaUserContext.d.ts +146 -0
- package/build/models/DaaUserContext.js +164 -0
- package/build/models/Deposit.d.ts +241 -0
- package/build/models/Deposit.js +149 -0
- package/build/models/DepositSummary.d.ts +91 -0
- package/build/models/DepositSummary.js +114 -0
- package/build/models/DeviceStatus.d.ts +69 -0
- package/build/models/DeviceStatus.js +19 -0
- package/build/models/FiatAccount.d.ts +99 -0
- package/build/models/FiatAccount.js +151 -0
- package/build/models/GenerateAddressRequest.d.ts +67 -0
- package/build/models/GenerateAddressRequest.js +68 -0
- package/build/models/Money.d.ts +76 -0
- package/build/models/Money.js +99 -0
- package/build/models/Page.d.ts +33 -0
- package/build/models/Page.js +57 -0
- package/build/models/PendingDeviceApproval.d.ts +121 -0
- package/build/models/PendingDeviceApproval.js +208 -0
- package/build/models/PendingDeviceRegistration.d.ts +229 -0
- package/build/models/PendingDeviceRegistration.js +636 -0
- package/build/models/PreparedContractExecution.d.ts +70 -0
- package/build/models/PreparedContractExecution.js +77 -0
- package/build/models/PreparedSocialLogin.d.ts +148 -0
- package/build/models/PreparedSocialLogin.js +252 -0
- package/build/models/Transaction.d.ts +233 -0
- package/build/models/Transaction.js +182 -0
- package/build/models/Transfer.d.ts +335 -0
- package/build/models/Transfer.js +240 -0
- package/build/models/Wire.d.ts +213 -0
- package/build/models/Wire.js +264 -0
- package/build/models/Withdrawal.d.ts +201 -0
- package/build/models/Withdrawal.js +156 -0
- package/build/models/codeSecrets.d.ts +100 -0
- package/build/models/codeSecrets.js +321 -0
- package/build/models/redaction.d.ts +18 -0
- package/build/models/redaction.js +23 -0
- package/build/sca/ScaClient.d.ts +105 -0
- package/build/sca/ScaClient.js +193 -0
- package/build/securekey/InMemorySecureKey.d.ts +25 -0
- package/build/securekey/InMemorySecureKey.js +168 -0
- package/build/securekey/NativeSecureKey.d.ts +26 -0
- package/build/securekey/NativeSecureKey.js +355 -0
- package/build/securekey/NativeSecureKeyBridge.d.ts +151 -0
- package/build/securekey/NativeSecureKeyBridge.js +19 -0
- package/build/securekey/SecureKey.d.ts +257 -0
- package/build/securekey/SecureKey.js +19 -0
- package/build/securekey/alias.d.ts +97 -0
- package/build/securekey/alias.js +184 -0
- package/build/securekey/ownerAuthKeyResolver.d.ts +73 -0
- package/build/securekey/ownerAuthKeyResolver.js +78 -0
- package/build/securekey/registration.d.ts +19 -0
- package/build/securekey/registration.js +38 -0
- package/build/securekey/resolveNativeBridge.d.ts +33 -0
- package/build/securekey/resolveNativeBridge.js +201 -0
- package/build/testing.d.ts +18 -0
- package/build/testing.js +34 -0
- package/build/transport/DaaTransport.d.ts +35 -0
- package/build/transport/DaaTransport.js +19 -0
- package/build/transport/headers.d.ts +41 -0
- package/build/transport/headers.js +81 -0
- package/build/validation/requestBody.d.ts +27 -0
- package/build/validation/requestBody.js +56 -0
- package/build/validation/uuid.d.ts +25 -0
- package/build/validation/uuid.js +33 -0
- package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
- package/build/wire/accountLimitsUsagePayload.js +130 -0
- package/build/wire/accountPayload.d.ts +36 -0
- package/build/wire/accountPayload.js +100 -0
- package/build/wire/achPayload.d.ts +24 -0
- package/build/wire/achPayload.js +82 -0
- package/build/wire/addressObjectPayload.d.ts +44 -0
- package/build/wire/addressObjectPayload.js +64 -0
- package/build/wire/contractExecutionPayload.d.ts +24 -0
- package/build/wire/contractExecutionPayload.js +130 -0
- package/build/wire/daaStatusCodes.d.ts +81 -0
- package/build/wire/daaStatusCodes.js +86 -0
- package/build/wire/dataEnvelope.d.ts +40 -0
- package/build/wire/dataEnvelope.js +79 -0
- package/build/wire/depositPayload.d.ts +42 -0
- package/build/wire/depositPayload.js +159 -0
- package/build/wire/deviceContextPayload.d.ts +35 -0
- package/build/wire/deviceContextPayload.js +59 -0
- package/build/wire/deviceRegistrationResultPayload.d.ts +77 -0
- package/build/wire/deviceRegistrationResultPayload.js +162 -0
- package/build/wire/deviceStatusPayload.d.ts +20 -0
- package/build/wire/deviceStatusPayload.js +66 -0
- package/build/wire/errorEnvelope.d.ts +43 -0
- package/build/wire/errorEnvelope.js +85 -0
- package/build/wire/fiatAccountPayload.d.ts +37 -0
- package/build/wire/fiatAccountPayload.js +93 -0
- package/build/wire/instant.d.ts +27 -0
- package/build/wire/instant.js +94 -0
- package/build/wire/jsonNumber.d.ts +30 -0
- package/build/wire/jsonNumber.js +34 -0
- package/build/wire/moneyPayload.d.ts +30 -0
- package/build/wire/moneyPayload.js +56 -0
- package/build/wire/paginationLinks.d.ts +28 -0
- package/build/wire/paginationLinks.js +167 -0
- package/build/wire/payload.d.ts +60 -0
- package/build/wire/payload.js +121 -0
- package/build/wire/pendingRegistrationPayload.d.ts +48 -0
- package/build/wire/pendingRegistrationPayload.js +72 -0
- package/build/wire/socialLoginRequestPayload.d.ts +26 -0
- package/build/wire/socialLoginRequestPayload.js +55 -0
- package/build/wire/transactionPayload.d.ts +31 -0
- package/build/wire/transactionPayload.js +149 -0
- package/build/wire/transferPayload.d.ts +43 -0
- package/build/wire/transferPayload.js +218 -0
- package/build/wire/wireEnums.d.ts +22 -0
- package/build/wire/wireEnums.js +69 -0
- package/build/wire/wirePayload.d.ts +29 -0
- package/build/wire/wirePayload.js +138 -0
- package/build/wire/withdrawalPayload.d.ts +27 -0
- package/build/wire/withdrawalPayload.js +179 -0
- package/expo-module.config.json +14 -0
- package/ios/DaaRegistrationExceptions.swift +58 -0
- package/ios/DaaRegistrationModule.swift +125 -0
- package/ios/DaaScaExceptions.swift +96 -0
- package/ios/DaaScaModule.swift +125 -0
- package/ios/DaaSecureKeyExceptions.swift +125 -0
- package/ios/DaaSecureKeyModule.swift +306 -0
- package/ios/InstallationIdentityStore.swift +162 -0
- package/ios/UnpaddedBase64URL.swift +42 -0
- package/package.json +114 -4
- package/src/DaaClient.ts +509 -0
- package/src/api/AccountLimitsClient.ts +146 -0
- package/src/api/AccountsClient.ts +308 -0
- package/src/api/AchFiatAccountsClient.ts +147 -0
- package/src/api/AuthClient.ts +266 -0
- package/src/api/ContractExecutionsClient.ts +527 -0
- package/src/api/DaaUserClient.ts +345 -0
- package/src/api/DepositAddressesClient.ts +239 -0
- package/src/api/DepositsClient.ts +208 -0
- package/src/api/FiatAccountsClient.ts +50 -0
- package/src/api/TransactionsClient.ts +138 -0
- package/src/api/TransfersClient.ts +364 -0
- package/src/api/WireFiatAccountsClient.ts +172 -0
- package/src/api/WithdrawalsClient.ts +342 -0
- package/src/api/deviceApproval.ts +306 -0
- package/src/api/deviceStatus.ts +238 -0
- package/src/api/loginFailure.ts +112 -0
- package/src/api/pagination.ts +63 -0
- package/src/api/queryParameters.ts +82 -0
- package/src/api/resourceRequest.ts +135 -0
- package/src/api/signedResource.ts +427 -0
- package/src/auth/RegistrationFlowKey.ts +274 -0
- package/src/auth/daaRegistrationNative.ts +191 -0
- package/src/auth/deviceAuthorization.ts +365 -0
- package/src/auth/ownerGrant.ts +102 -0
- package/src/auth/registrationAuthorization.ts +309 -0
- package/src/auth/registrationCodeVerifier.ts +76 -0
- package/src/config.ts +192 -0
- package/src/crypto/base64url.ts +88 -0
- package/src/crypto/bytes.ts +30 -0
- package/src/crypto/jwkThumbprint.ts +65 -0
- package/src/crypto/matchingCode.ts +100 -0
- package/src/crypto/random.ts +113 -0
- package/src/crypto/serialization.ts +42 -0
- package/src/crypto/sha256.ts +105 -0
- package/src/errors.ts +576 -0
- package/src/index.ts +258 -0
- package/src/models/Account.ts +264 -0
- package/src/models/AccountLimitsUsage.ts +192 -0
- package/src/models/Ach.ts +269 -0
- package/src/models/AddressObject.ts +169 -0
- package/src/models/BusinessPii.ts +154 -0
- package/src/models/ContractExecution.ts +250 -0
- package/src/models/CreateAccountRequest.ts +109 -0
- package/src/models/CreateContractExecutionRequest.ts +100 -0
- package/src/models/CreateTransferRequest.ts +114 -0
- package/src/models/CreateWithdrawalRequest.ts +120 -0
- package/src/models/DaaUserContext.ts +228 -0
- package/src/models/Deposit.ts +307 -0
- package/src/models/DepositSummary.ts +142 -0
- package/src/models/DeviceStatus.ts +50 -0
- package/src/models/FiatAccount.ts +195 -0
- package/src/models/GenerateAddressRequest.ts +101 -0
- package/src/models/Money.ts +91 -0
- package/src/models/Page.ts +48 -0
- package/src/models/PendingDeviceApproval.ts +229 -0
- package/src/models/PendingDeviceRegistration.ts +791 -0
- package/src/models/PreparedContractExecution.ts +128 -0
- package/src/models/PreparedSocialLogin.ts +297 -0
- package/src/models/Transaction.ts +322 -0
- package/src/models/Transfer.ts +459 -0
- package/src/models/Wire.ts +405 -0
- package/src/models/Withdrawal.ts +283 -0
- package/src/models/codeSecrets.ts +360 -0
- package/src/models/redaction.ts +22 -0
- package/src/sca/ScaClient.ts +289 -0
- package/src/securekey/InMemorySecureKey.ts +192 -0
- package/src/securekey/NativeSecureKey.ts +388 -0
- package/src/securekey/NativeSecureKeyBridge.ts +189 -0
- package/src/securekey/SecureKey.ts +279 -0
- package/src/securekey/alias.ts +212 -0
- package/src/securekey/ownerAuthKeyResolver.ts +135 -0
- package/src/securekey/registration.ts +40 -0
- package/src/securekey/resolveNativeBridge.ts +343 -0
- package/src/testing.ts +32 -0
- package/src/transport/DaaTransport.ts +42 -0
- package/src/transport/headers.ts +93 -0
- package/src/validation/requestBody.ts +60 -0
- package/src/validation/uuid.ts +31 -0
- package/src/wire/accountLimitsUsagePayload.ts +182 -0
- package/src/wire/accountPayload.ts +108 -0
- package/src/wire/achPayload.ts +98 -0
- package/src/wire/addressObjectPayload.ts +64 -0
- package/src/wire/contractExecutionPayload.ts +152 -0
- package/src/wire/daaStatusCodes.ts +86 -0
- package/src/wire/dataEnvelope.ts +80 -0
- package/src/wire/depositPayload.ts +186 -0
- package/src/wire/deviceContextPayload.ts +60 -0
- package/src/wire/deviceRegistrationResultPayload.ts +211 -0
- package/src/wire/deviceStatusPayload.ts +68 -0
- package/src/wire/errorEnvelope.ts +87 -0
- package/src/wire/fiatAccountPayload.ts +112 -0
- package/src/wire/instant.ts +96 -0
- package/src/wire/jsonNumber.ts +33 -0
- package/src/wire/moneyPayload.ts +55 -0
- package/src/wire/paginationLinks.ts +204 -0
- package/src/wire/payload.ts +146 -0
- package/src/wire/pendingRegistrationPayload.ts +118 -0
- package/src/wire/socialLoginRequestPayload.ts +66 -0
- package/src/wire/transactionPayload.ts +181 -0
- package/src/wire/transferPayload.ts +249 -0
- package/src/wire/wireEnums.ts +74 -0
- package/src/wire/wirePayload.ts +160 -0
- package/src/wire/withdrawalPayload.ts +219 -0
- package/testing.d.ts +19 -0
- package/testing.js +25 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { contractViolation, isDaaError } from '../errors'
|
|
20
|
+
import type { DeviceStatus } from '../models/DeviceStatus'
|
|
21
|
+
import type { DaaTransport } from '../transport/DaaTransport'
|
|
22
|
+
import { isUuid } from '../validation/uuid'
|
|
23
|
+
import { toDeviceStatus } from '../wire/deviceStatusPayload'
|
|
24
|
+
import { readResource } from './resourceRequest'
|
|
25
|
+
|
|
26
|
+
/** The add-a-device routes of one AuthKey: this prefix, then its `authKeyId`. */
|
|
27
|
+
export const DEVICE_PATH_PREFIX = '/v1/accounts/auth/devices/'
|
|
28
|
+
|
|
29
|
+
/** How often `watchDeviceStatus` reads the status while nothing fails. */
|
|
30
|
+
export const POLL_INTERVAL_MS = 5_000
|
|
31
|
+
/** The longest wait between reads after errors, and during a cool-down. */
|
|
32
|
+
export const MAX_POLL_INTERVAL_MS = 30_000
|
|
33
|
+
/** Retryable failures in a row after which `watchDeviceStatus` gives up. */
|
|
34
|
+
export const MAX_CONSECUTIVE_ERRORS = 10
|
|
35
|
+
|
|
36
|
+
/** The statuses in which the request can still change; any other ends a watch. */
|
|
37
|
+
const WAITING_STATUSES: ReadonlySet<DeviceStatus['status']> = new Set([
|
|
38
|
+
'pending_approval',
|
|
39
|
+
'pending_activation',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `GET /v1/accounts/auth/devices/{authKeyId}`. A transport throw must already
|
|
44
|
+
* be a `transport` DaaError (the caller wraps the transport).
|
|
45
|
+
*
|
|
46
|
+
* `authKeyId` may come in either case (Swift's `uuidString` is uppercase); it
|
|
47
|
+
* is lowercased before it goes into the path and before the response's
|
|
48
|
+
* `authKeyId`, which DAA writes lowercase, is compared with it.
|
|
49
|
+
*/
|
|
50
|
+
export async function readDeviceStatus(
|
|
51
|
+
transport: DaaTransport,
|
|
52
|
+
authKeyId: string,
|
|
53
|
+
): Promise<DeviceStatus> {
|
|
54
|
+
if (!isUuid(authKeyId)) {
|
|
55
|
+
throw contractViolation('authKeyId must be a UUID')
|
|
56
|
+
}
|
|
57
|
+
const id = authKeyId.toLowerCase()
|
|
58
|
+
const status = await readResource({
|
|
59
|
+
transport,
|
|
60
|
+
path: DEVICE_PATH_PREFIX + id,
|
|
61
|
+
decode: toDeviceStatus,
|
|
62
|
+
})
|
|
63
|
+
if (status.authKeyId.toLowerCase() !== id) {
|
|
64
|
+
throw contractViolation('the device status names a different AuthKey')
|
|
65
|
+
}
|
|
66
|
+
return status
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Read the status until it is no longer `pending_approval` or
|
|
71
|
+
* `pending_activation`, and resolve with that status.
|
|
72
|
+
*
|
|
73
|
+
* Only DAA's answer ends the watch: DAA reports `expired` once `expiresAt`
|
|
74
|
+
* passes on its clock, so this device's clock, which may be wrong, never
|
|
75
|
+
* decides when the request is over. Reads every 5 s while `pending_approval`.
|
|
76
|
+
* During `pending_activation` it reads at `readyAt`, but at least every 30 s,
|
|
77
|
+
* since the cool-down can last hours. After a failure marked `retryable`
|
|
78
|
+
* (`transport`, or `api` with `429`/`5xx`) the wait doubles, up to 30 s, and after 10 in a
|
|
79
|
+
* row it rejects with the last one; any other failure rejects at once. Each
|
|
80
|
+
* wait after a failure is a random time between half of that and all of it, so
|
|
81
|
+
* watches that failed together (a gateway outage) don't all retry together.
|
|
82
|
+
*
|
|
83
|
+
* `onStatus` is called with the first status and with every change; if it
|
|
84
|
+
* throws, the watch rejects with that error. Aborting `signal` stops the watch
|
|
85
|
+
* at once, also during a read, and rejects with the signal's `reason` (an
|
|
86
|
+
* `Error` when the runtime's `AbortSignal` has none); a read that answers
|
|
87
|
+
* after the abort is ignored, and `onStatus` is not called for it.
|
|
88
|
+
*/
|
|
89
|
+
export async function watchDeviceStatus(
|
|
90
|
+
transport: DaaTransport,
|
|
91
|
+
args: {
|
|
92
|
+
readonly authKeyId: string
|
|
93
|
+
readonly onStatus?: (status: DeviceStatus) => void
|
|
94
|
+
readonly signal?: AbortSignal
|
|
95
|
+
},
|
|
96
|
+
): Promise<DeviceStatus> {
|
|
97
|
+
const { authKeyId, onStatus, signal } = args
|
|
98
|
+
let last: DeviceStatus | null = null
|
|
99
|
+
let errors = 0
|
|
100
|
+
let errorWait = POLL_INTERVAL_MS
|
|
101
|
+
for (;;) {
|
|
102
|
+
let status: DeviceStatus
|
|
103
|
+
try {
|
|
104
|
+
status = await untilAborted(() => readDeviceStatus(transport, authKeyId), signal)
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if (signal?.aborted === true) {
|
|
107
|
+
throw abortReason(signal)
|
|
108
|
+
}
|
|
109
|
+
errors += 1
|
|
110
|
+
if (!isRetryable(err) || errors >= MAX_CONSECUTIVE_ERRORS) {
|
|
111
|
+
throw err
|
|
112
|
+
}
|
|
113
|
+
errorWait = Math.min(errorWait * 2, MAX_POLL_INTERVAL_MS)
|
|
114
|
+
await sleep(jittered(errorWait), signal)
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
// The abort can land after the read settled but before this resumes; the
|
|
118
|
+
// app has cancelled by then, so it gets no status and no result.
|
|
119
|
+
if (signal?.aborted === true) {
|
|
120
|
+
throw abortReason(signal)
|
|
121
|
+
}
|
|
122
|
+
errors = 0
|
|
123
|
+
errorWait = POLL_INTERVAL_MS
|
|
124
|
+
if (last === null || !sameStatus(last, status)) {
|
|
125
|
+
onStatus?.(status)
|
|
126
|
+
}
|
|
127
|
+
last = status
|
|
128
|
+
if (!WAITING_STATUSES.has(status.status)) {
|
|
129
|
+
return status
|
|
130
|
+
}
|
|
131
|
+
await sleep(nextRead(status), signal)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A random time between half of `ms` and all of it. */
|
|
136
|
+
function jittered(ms: number): number {
|
|
137
|
+
return Math.round(ms / 2 + Math.random() * (ms / 2))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function nextRead(status: DeviceStatus): number {
|
|
141
|
+
if (status.status !== 'pending_activation') {
|
|
142
|
+
return POLL_INTERVAL_MS
|
|
143
|
+
}
|
|
144
|
+
const untilReady = Date.parse(status.readyAt) - Date.now()
|
|
145
|
+
// The decoder checks `readyAt`'s shape, not its calendar (`2026-13-24…`
|
|
146
|
+
// passes), and JS engines differ in what `Date.parse` accepts. A NaN would
|
|
147
|
+
// make the timer fire at once and the watch poll without pause; read every
|
|
148
|
+
// 30 s instead and let DAA's status end the cool-down.
|
|
149
|
+
if (!Number.isFinite(untilReady)) {
|
|
150
|
+
return MAX_POLL_INTERVAL_MS
|
|
151
|
+
}
|
|
152
|
+
return Math.min(Math.max(untilReady, POLL_INTERVAL_MS), MAX_POLL_INTERVAL_MS)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function sameStatus(a: DeviceStatus, b: DeviceStatus): boolean {
|
|
156
|
+
return JSON.stringify(a) === JSON.stringify(b)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// `retryable` decides for both kinds: a transport that throws its own
|
|
160
|
+
// `DaaError` with `retryable: false` has said a retry cannot help.
|
|
161
|
+
function isRetryable(err: unknown): boolean {
|
|
162
|
+
return (
|
|
163
|
+
isDaaError(err) &&
|
|
164
|
+
(err.detail.kind === 'transport' || err.detail.kind === 'api') &&
|
|
165
|
+
err.detail.retryable
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Only `aborted` and the abort event: older React Native `AbortSignal`
|
|
170
|
+
// polyfills have neither `throwIfAborted()` nor always a `reason`.
|
|
171
|
+
function abortReason(signal: AbortSignal): unknown {
|
|
172
|
+
return signal.reason ?? new Error('DAA: watchDeviceStatus was aborted')
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* `start()`, or a rejection as soon as `signal` aborts, whichever comes first.
|
|
177
|
+
* Nothing starts once `signal` has aborted, and a result that arrives after
|
|
178
|
+
* the abort is dropped; the caller checks `signal.aborted` to tell the two
|
|
179
|
+
* rejections apart. The abort listener is in place before `start()` runs, so
|
|
180
|
+
* an abort during `start()` itself (say, inside the transport's `send`) is
|
|
181
|
+
* not missed.
|
|
182
|
+
*/
|
|
183
|
+
function untilAborted<T>(start: () => Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
184
|
+
if (signal === undefined) {
|
|
185
|
+
return start()
|
|
186
|
+
}
|
|
187
|
+
if (signal.aborted) {
|
|
188
|
+
return Promise.reject(abortReason(signal))
|
|
189
|
+
}
|
|
190
|
+
return new Promise<T>((resolve, reject) => {
|
|
191
|
+
const onAbort = () => reject(abortReason(signal))
|
|
192
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
193
|
+
let promise: Promise<T>
|
|
194
|
+
try {
|
|
195
|
+
promise = start()
|
|
196
|
+
} catch (err: unknown) {
|
|
197
|
+
signal.removeEventListener('abort', onAbort)
|
|
198
|
+
reject(err)
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
promise.then(
|
|
202
|
+
(value) => {
|
|
203
|
+
signal.removeEventListener('abort', onAbort)
|
|
204
|
+
if (signal.aborted) {
|
|
205
|
+
reject(abortReason(signal))
|
|
206
|
+
} else {
|
|
207
|
+
resolve(value)
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
(err: unknown) => {
|
|
211
|
+
signal.removeEventListener('abort', onAbort)
|
|
212
|
+
reject(err)
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
if (signal === undefined) {
|
|
221
|
+
setTimeout(resolve, ms)
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
if (signal.aborted) {
|
|
225
|
+
reject(abortReason(signal))
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
const onAbort = () => {
|
|
229
|
+
clearTimeout(timer)
|
|
230
|
+
reject(abortReason(signal))
|
|
231
|
+
}
|
|
232
|
+
const timer = setTimeout(() => {
|
|
233
|
+
signal.removeEventListener('abort', onAbort)
|
|
234
|
+
resolve()
|
|
235
|
+
}, ms)
|
|
236
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
237
|
+
})
|
|
238
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
contractViolation,
|
|
21
|
+
deviceRegistrationFailure,
|
|
22
|
+
idempotencyConflict,
|
|
23
|
+
loginRequestExpired,
|
|
24
|
+
type DaaError,
|
|
25
|
+
} from '../errors'
|
|
26
|
+
import type { DaaHttpResponse } from '../transport/DaaTransport'
|
|
27
|
+
import { headerValueIgnoringCase } from '../transport/headers'
|
|
28
|
+
import { isDaaStatus } from '../wire/daaStatusCodes'
|
|
29
|
+
import { readDaaStatusCode } from '../wire/errorEnvelope'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The failure the three login calls (Prepare, Social Session, and Device
|
|
33
|
+
* Registration Complete) classify themselves, or `null` when the response is
|
|
34
|
+
* left to `decodeResourceResponse`, which decodes the success status and turns
|
|
35
|
+
* every other status into `api`.
|
|
36
|
+
*
|
|
37
|
+
* Classified on the numeric code only (a non-numeric string `code`, even a
|
|
38
|
+
* name such as `IDEMPOTENCY_KEY_REUSED`, is left to `api`):
|
|
39
|
+
*
|
|
40
|
+
* - `410` is `login_request_expired`.
|
|
41
|
+
* - `IDEMPOTENCY_KEY_REUSED` (`420034`) on a `409` is `idempotency_conflict`,
|
|
42
|
+
* with the key the SDK minted for this request. That key is in the bytes the
|
|
43
|
+
* SDK serialized and sent, so it is never read from the response.
|
|
44
|
+
* - `LOGIN_REQUEST_CONSUMED` (`420039`) is `contract_violation`. An identical
|
|
45
|
+
* successful step converges and never returns it, so it means that a
|
|
46
|
+
* different request used the login request.
|
|
47
|
+
* - The four add-a-device codes, which only Device Registration Complete
|
|
48
|
+
* sends: `DEVICE_REGISTRATION_LIMIT` (`420109`) is
|
|
49
|
+
* `device_registration_limit`, with `retryAfterSeconds` when `Retry-After` is
|
|
50
|
+
* a whole number of seconds; `DEVICE_DENIED` (`420111`) is `device_denied`;
|
|
51
|
+
* `DEVICE_APPROVAL_CONFLICT` (`420112`) is `device_approval_conflict`; and
|
|
52
|
+
* `DEVICE_APPROVAL_UNAVAILABLE` (`420113`) is `device_approval_unavailable`.
|
|
53
|
+
* See `deviceRegistrationFailure`.
|
|
54
|
+
* - DAA also returns `409` for `AUTH_KEY_BINDING_CONFLICT` (`420038`) and for
|
|
55
|
+
* `PASSKEY_OWNER_CREDENTIAL_KIND_MISMATCH` (`420080`), which classify as
|
|
56
|
+
* `api`, not retryable. A `409` without a code that this
|
|
57
|
+
* SDK classifies, or without a readable body, is `api` too. So no status
|
|
58
|
+
* alone produces `idempotency_conflict`.
|
|
59
|
+
*
|
|
60
|
+
* A `2xx` response is never classified here, even when its body has a `code`.
|
|
61
|
+
*/
|
|
62
|
+
export function loginStepFailure(
|
|
63
|
+
response: DaaHttpResponse,
|
|
64
|
+
idempotencyKey: string,
|
|
65
|
+
): DaaError | null {
|
|
66
|
+
const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
|
|
67
|
+
if (response.status === 410) {
|
|
68
|
+
return loginRequestExpired(correlationId)
|
|
69
|
+
}
|
|
70
|
+
if (response.status >= 200 && response.status < 300) {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
const daaStatusCode = readDaaStatusCode(response.bodyBytes)
|
|
74
|
+
if (response.status === 409 && isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) {
|
|
75
|
+
return idempotencyConflict(idempotencyKey, correlationId)
|
|
76
|
+
}
|
|
77
|
+
if (isDaaStatus(daaStatusCode, 'LOGIN_REQUEST_CONSUMED')) {
|
|
78
|
+
return contractViolation(
|
|
79
|
+
'the login request was already used by a different request',
|
|
80
|
+
correlationId,
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_REGISTRATION_LIMIT')) {
|
|
84
|
+
return deviceRegistrationFailure(
|
|
85
|
+
'device_registration_limit',
|
|
86
|
+
correlationId,
|
|
87
|
+
retryAfterSeconds(response),
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_DENIED')) {
|
|
91
|
+
return deviceRegistrationFailure('device_denied', correlationId)
|
|
92
|
+
}
|
|
93
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_APPROVAL_CONFLICT')) {
|
|
94
|
+
return deviceRegistrationFailure('device_approval_conflict', correlationId)
|
|
95
|
+
}
|
|
96
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_APPROVAL_UNAVAILABLE')) {
|
|
97
|
+
return deviceRegistrationFailure('device_approval_unavailable', correlationId)
|
|
98
|
+
}
|
|
99
|
+
return null
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `Retry-After` as whole seconds, or `null` when it is absent or in any other
|
|
104
|
+
* form (an HTTP date, a fraction, a sign). DAA sends seconds.
|
|
105
|
+
*/
|
|
106
|
+
function retryAfterSeconds(response: DaaHttpResponse): number | null {
|
|
107
|
+
const value = headerValueIgnoringCase(response.headers, 'Retry-After')?.trim()
|
|
108
|
+
if (value === undefined || !/^\d{1,9}$/.test(value)) {
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
return Number(value)
|
|
112
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { isDaaError, malformedResponse } from '../errors'
|
|
20
|
+
import { Page } from '../models/Page'
|
|
21
|
+
import type { DaaTransport } from '../transport/DaaTransport'
|
|
22
|
+
import { headerValueIgnoringCase } from '../transport/headers'
|
|
23
|
+
import { trustedPaginationTargets } from '../wire/paginationLinks'
|
|
24
|
+
import type { TrustedPaginationTargets } from '../wire/paginationLinks'
|
|
25
|
+
import { decodeResourceResponse } from './resourceRequest'
|
|
26
|
+
|
|
27
|
+
type PageRequestOptions<T> = Readonly<{
|
|
28
|
+
transport: DaaTransport
|
|
29
|
+
publicApiOrigin: string
|
|
30
|
+
path: string
|
|
31
|
+
query: string | null
|
|
32
|
+
decode: (value: unknown) => readonly T[]
|
|
33
|
+
}>
|
|
34
|
+
|
|
35
|
+
/** Load one exact collection request and bind its links to the same collection. */
|
|
36
|
+
export async function readPage<T>(options: PageRequestOptions<T>): Promise<Page<T>> {
|
|
37
|
+
const response = await options.transport.send({
|
|
38
|
+
method: 'GET',
|
|
39
|
+
path: options.path,
|
|
40
|
+
query: options.query,
|
|
41
|
+
headers: {},
|
|
42
|
+
bodyBytes: null,
|
|
43
|
+
})
|
|
44
|
+
const items = decodeResourceResponse({ response, expectedStatus: 200, decode: options.decode })
|
|
45
|
+
let targets: TrustedPaginationTargets
|
|
46
|
+
try {
|
|
47
|
+
targets = trustedPaginationTargets(response, options.publicApiOrigin, options.path)
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (isDaaError(err) && err.detail.kind === 'contract_violation') {
|
|
50
|
+
throw malformedResponse(headerValueIgnoringCase(response.headers, 'X-Request-Id'))
|
|
51
|
+
}
|
|
52
|
+
throw err
|
|
53
|
+
}
|
|
54
|
+
const load = (query: string | null): Promise<Page<T>> => readPage({ ...options, query })
|
|
55
|
+
const nextQuery = targets.next?.query
|
|
56
|
+
const previousQuery = targets.previous?.query
|
|
57
|
+
|
|
58
|
+
return new Page(
|
|
59
|
+
items,
|
|
60
|
+
targets.next === null ? null : () => load(nextQuery ?? null),
|
|
61
|
+
targets.previous === null ? null : () => load(previousQuery ?? null),
|
|
62
|
+
)
|
|
63
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { contractViolation } from '../errors'
|
|
20
|
+
import { isUuid } from '../validation/uuid'
|
|
21
|
+
|
|
22
|
+
export function append(parts: string[], name: string, value: string): void {
|
|
23
|
+
try {
|
|
24
|
+
parts.push(`${name}=${encodeURIComponent(value)}`)
|
|
25
|
+
} catch {
|
|
26
|
+
throw contractViolation(`${name} contains an invalid Unicode value`)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function appendString(parts: string[], name: string, value: string | undefined): void {
|
|
31
|
+
if (value === undefined) return
|
|
32
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
33
|
+
throw contractViolation(`${name} must be a non-empty string`)
|
|
34
|
+
}
|
|
35
|
+
append(parts, name, value)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function appendStrings(
|
|
39
|
+
parts: string[],
|
|
40
|
+
name: string,
|
|
41
|
+
values: readonly string[] | undefined,
|
|
42
|
+
): void {
|
|
43
|
+
if (values === undefined) return
|
|
44
|
+
if (!Array.isArray(values)) {
|
|
45
|
+
throw contractViolation(`${name} must be an array`)
|
|
46
|
+
}
|
|
47
|
+
for (const value of values) appendString(parts, name, value)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function appendUuid(parts: string[], name: string, value: string | undefined): void {
|
|
51
|
+
if (value === undefined) return
|
|
52
|
+
if (typeof value !== 'string' || !isUuid(value)) {
|
|
53
|
+
throw contractViolation(`${name} must be a UUID`)
|
|
54
|
+
}
|
|
55
|
+
append(parts, name, value)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function appendEnum<const T extends string>(
|
|
59
|
+
parts: string[],
|
|
60
|
+
name: string,
|
|
61
|
+
value: T | undefined,
|
|
62
|
+
allowed: readonly T[],
|
|
63
|
+
): void {
|
|
64
|
+
if (value === undefined) return
|
|
65
|
+
if (typeof value !== 'string' || !allowed.includes(value)) {
|
|
66
|
+
throw contractViolation(`${name} is not supported`)
|
|
67
|
+
}
|
|
68
|
+
append(parts, name, value)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function appendEnums<const T extends string>(
|
|
72
|
+
parts: string[],
|
|
73
|
+
name: string,
|
|
74
|
+
values: readonly T[] | undefined,
|
|
75
|
+
allowed: readonly T[],
|
|
76
|
+
): void {
|
|
77
|
+
if (values === undefined) return
|
|
78
|
+
if (!Array.isArray(values)) {
|
|
79
|
+
throw contractViolation(`${name} must be an array`)
|
|
80
|
+
}
|
|
81
|
+
for (const value of values) appendEnum(parts, name, value, allowed)
|
|
82
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { apiFailure, malformedResponse, type DaaError } from '../errors'
|
|
20
|
+
import { headerValueIgnoringCase } from '../transport/headers'
|
|
21
|
+
import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
|
|
22
|
+
import { decodeDataEnvelope } from '../wire/dataEnvelope'
|
|
23
|
+
import { readDaaStatusCode } from '../wire/errorEnvelope'
|
|
24
|
+
import { MalformedPayloadError } from '../wire/payload'
|
|
25
|
+
|
|
26
|
+
type ReadResourceOptions<T> = Readonly<{
|
|
27
|
+
transport: DaaTransport
|
|
28
|
+
path: string
|
|
29
|
+
/**
|
|
30
|
+
* Exact percent-encoded query without the leading `?`, or `null`/omitted for
|
|
31
|
+
* none. Unlike a signed write (signed v1 endpoints do not accept query
|
|
32
|
+
* parameters), an unsigned read may carry one — see the
|
|
33
|
+
* `DaaTransport.query` note — so this is opt-in per call.
|
|
34
|
+
*/
|
|
35
|
+
query?: string | null
|
|
36
|
+
decode: (value: unknown) => T
|
|
37
|
+
}>
|
|
38
|
+
|
|
39
|
+
type PostResourceOptions<T> = Readonly<{
|
|
40
|
+
transport: DaaTransport
|
|
41
|
+
path: string
|
|
42
|
+
query: string | null
|
|
43
|
+
headers: Readonly<Record<string, string>>
|
|
44
|
+
/** Final serialized bytes. Signed writes must sign and pass this same slice. */
|
|
45
|
+
bodyBytes: Uint8Array
|
|
46
|
+
expectedStatus: number
|
|
47
|
+
decode: (value: unknown) => T
|
|
48
|
+
/**
|
|
49
|
+
* Endpoint-specific classification of a response, checked before the
|
|
50
|
+
* expected status.
|
|
51
|
+
* A non-`null` result is thrown; `null` leaves the response to the common
|
|
52
|
+
* contract.
|
|
53
|
+
*/
|
|
54
|
+
failure?: (response: DaaHttpResponse) => DaaError | null
|
|
55
|
+
}>
|
|
56
|
+
|
|
57
|
+
type DecodeResourceResponseOptions<T> = Readonly<{
|
|
58
|
+
response: DaaHttpResponse
|
|
59
|
+
expectedStatus: number
|
|
60
|
+
decode: (value: unknown) => T
|
|
61
|
+
}>
|
|
62
|
+
|
|
63
|
+
/** Decode the common exact-status public resource response contract. */
|
|
64
|
+
export function decodeResourceResponse<T>({
|
|
65
|
+
response,
|
|
66
|
+
expectedStatus,
|
|
67
|
+
decode,
|
|
68
|
+
}: DecodeResourceResponseOptions<T>): T {
|
|
69
|
+
const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
|
|
70
|
+
|
|
71
|
+
if (response.status !== expectedStatus) {
|
|
72
|
+
throw apiFailure({
|
|
73
|
+
httpStatus: response.status,
|
|
74
|
+
daaStatusCode: readDaaStatusCode(response.bodyBytes),
|
|
75
|
+
correlationId,
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
if (response.bodyBytes === null) {
|
|
79
|
+
throw malformedResponse(correlationId)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const data = decodeDataEnvelope(response.bodyBytes, correlationId)
|
|
83
|
+
try {
|
|
84
|
+
return decode(data)
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (err instanceof MalformedPayloadError) {
|
|
87
|
+
throw malformedResponse(correlationId)
|
|
88
|
+
}
|
|
89
|
+
throw err
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Execute the common public GET contract, with an optional exact query string. */
|
|
94
|
+
export async function readResource<T>({
|
|
95
|
+
transport,
|
|
96
|
+
path,
|
|
97
|
+
query,
|
|
98
|
+
decode,
|
|
99
|
+
}: ReadResourceOptions<T>): Promise<T> {
|
|
100
|
+
const response = await transport.send({
|
|
101
|
+
method: 'GET',
|
|
102
|
+
path,
|
|
103
|
+
query: query ?? null,
|
|
104
|
+
headers: {},
|
|
105
|
+
bodyBytes: null,
|
|
106
|
+
})
|
|
107
|
+
// These by-id reads document exactly 200. Other statuses, including another
|
|
108
|
+
// 2xx, are observable API failures rather than silently accepted variants.
|
|
109
|
+
return decodeResourceResponse({ response, expectedStatus: 200, decode })
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Execute a public POST without transforming its endpoint-specific request. */
|
|
113
|
+
export async function postResource<T>({
|
|
114
|
+
transport,
|
|
115
|
+
path,
|
|
116
|
+
query,
|
|
117
|
+
headers,
|
|
118
|
+
bodyBytes,
|
|
119
|
+
expectedStatus,
|
|
120
|
+
decode,
|
|
121
|
+
failure,
|
|
122
|
+
}: PostResourceOptions<T>): Promise<T> {
|
|
123
|
+
const response = await transport.send({
|
|
124
|
+
method: 'POST',
|
|
125
|
+
path,
|
|
126
|
+
query,
|
|
127
|
+
headers,
|
|
128
|
+
bodyBytes,
|
|
129
|
+
})
|
|
130
|
+
const mapped = failure?.(response) ?? null
|
|
131
|
+
if (mapped !== null) {
|
|
132
|
+
throw mapped
|
|
133
|
+
}
|
|
134
|
+
return decodeResourceResponse({ response, expectedStatus, decode })
|
|
135
|
+
}
|