@circle-fin/daa-react-native-sdk 0.0.0-stage → 0.4.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.
Files changed (304) hide show
  1. package/DaaReactNativeSdk.podspec +63 -0
  2. package/LICENSE +176 -0
  3. package/README.md +217 -2
  4. package/android/build.gradle +97 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
  7. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +121 -0
  8. package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
  9. package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
  10. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +73 -0
  11. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +185 -0
  12. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +73 -0
  13. package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
  14. package/build/DaaClient.d.ts +57 -0
  15. package/build/DaaClient.js +158 -0
  16. package/build/api/AccountLimitsClient.d.ts +79 -0
  17. package/build/api/AccountLimitsClient.js +142 -0
  18. package/build/api/AccountsClient.d.ts +95 -0
  19. package/build/api/AccountsClient.js +276 -0
  20. package/build/api/AchFiatAccountsClient.d.ts +92 -0
  21. package/build/api/AchFiatAccountsClient.js +142 -0
  22. package/build/api/AuthClient.d.ts +120 -0
  23. package/build/api/AuthClient.js +257 -0
  24. package/build/api/DaaUserClient.d.ts +124 -0
  25. package/build/api/DaaUserClient.js +245 -0
  26. package/build/api/DepositAddressesClient.d.ts +112 -0
  27. package/build/api/DepositAddressesClient.js +222 -0
  28. package/build/api/DepositsClient.d.ts +106 -0
  29. package/build/api/DepositsClient.js +183 -0
  30. package/build/api/FiatAccountsClient.d.ts +43 -0
  31. package/build/api/FiatAccountsClient.js +46 -0
  32. package/build/api/TransactionsClient.d.ts +64 -0
  33. package/build/api/TransactionsClient.js +120 -0
  34. package/build/api/TransfersClient.d.ts +104 -0
  35. package/build/api/TransfersClient.js +321 -0
  36. package/build/api/WireFiatAccountsClient.d.ts +99 -0
  37. package/build/api/WireFiatAccountsClient.js +156 -0
  38. package/build/api/WithdrawalsClient.d.ts +94 -0
  39. package/build/api/WithdrawalsClient.js +305 -0
  40. package/build/api/loginFailure.d.ts +43 -0
  41. package/build/api/loginFailure.js +64 -0
  42. package/build/api/pagination.d.ts +29 -0
  43. package/build/api/pagination.js +50 -0
  44. package/build/api/queryParameters.d.ts +23 -0
  45. package/build/api/queryParameters.js +77 -0
  46. package/build/api/resourceRequest.d.ts +60 -0
  47. package/build/api/resourceRequest.js +79 -0
  48. package/build/api/signedResource.d.ts +77 -0
  49. package/build/api/signedResource.js +168 -0
  50. package/build/auth/RegistrationFlowKey.d.ts +93 -0
  51. package/build/auth/RegistrationFlowKey.js +203 -0
  52. package/build/auth/daaRegistrationNative.d.ts +80 -0
  53. package/build/auth/daaRegistrationNative.js +184 -0
  54. package/build/auth/deviceAuthorization.d.ts +73 -0
  55. package/build/auth/deviceAuthorization.js +243 -0
  56. package/build/auth/ownerGrant.d.ts +29 -0
  57. package/build/auth/ownerGrant.js +90 -0
  58. package/build/auth/prepareReceipt.d.ts +150 -0
  59. package/build/auth/prepareReceipt.js +357 -0
  60. package/build/auth/registrationAuthorization.d.ts +48 -0
  61. package/build/auth/registrationAuthorization.js +243 -0
  62. package/build/auth/registrationCodeVerifier.d.ts +31 -0
  63. package/build/auth/registrationCodeVerifier.js +75 -0
  64. package/build/config.d.ts +79 -0
  65. package/build/config.js +116 -0
  66. package/build/crypto/base64url.d.ts +26 -0
  67. package/build/crypto/base64url.js +87 -0
  68. package/build/crypto/bytes.d.ts +27 -0
  69. package/build/crypto/bytes.js +32 -0
  70. package/build/crypto/es256Jws.d.ts +56 -0
  71. package/build/crypto/es256Jws.js +196 -0
  72. package/build/crypto/jwkThumbprint.d.ts +32 -0
  73. package/build/crypto/jwkThumbprint.js +49 -0
  74. package/build/crypto/random.d.ts +35 -0
  75. package/build/crypto/random.js +106 -0
  76. package/build/crypto/serialization.d.ts +26 -0
  77. package/build/crypto/serialization.js +43 -0
  78. package/build/crypto/sha256.d.ts +18 -0
  79. package/build/crypto/sha256.js +100 -0
  80. package/build/errors.d.ts +190 -0
  81. package/build/errors.js +252 -0
  82. package/build/index.d.ts +61 -0
  83. package/build/index.js +67 -0
  84. package/build/models/Account.d.ts +201 -0
  85. package/build/models/Account.js +147 -0
  86. package/build/models/AccountLimitsUsage.d.ts +169 -0
  87. package/build/models/AccountLimitsUsage.js +86 -0
  88. package/build/models/Ach.d.ts +135 -0
  89. package/build/models/Ach.js +184 -0
  90. package/build/models/AddressObject.d.ts +128 -0
  91. package/build/models/AddressObject.js +141 -0
  92. package/build/models/BusinessPii.d.ts +84 -0
  93. package/build/models/BusinessPii.js +142 -0
  94. package/build/models/CreateAccountRequest.d.ts +74 -0
  95. package/build/models/CreateAccountRequest.js +19 -0
  96. package/build/models/CreateTransferRequest.d.ts +91 -0
  97. package/build/models/CreateTransferRequest.js +19 -0
  98. package/build/models/CreateWithdrawalRequest.d.ts +99 -0
  99. package/build/models/CreateWithdrawalRequest.js +19 -0
  100. package/build/models/DaaUserContext.d.ts +96 -0
  101. package/build/models/DaaUserContext.js +133 -0
  102. package/build/models/Deposit.d.ts +241 -0
  103. package/build/models/Deposit.js +149 -0
  104. package/build/models/DepositSummary.d.ts +91 -0
  105. package/build/models/DepositSummary.js +114 -0
  106. package/build/models/FiatAccount.d.ts +99 -0
  107. package/build/models/FiatAccount.js +151 -0
  108. package/build/models/GenerateAddressRequest.d.ts +67 -0
  109. package/build/models/GenerateAddressRequest.js +68 -0
  110. package/build/models/Money.d.ts +76 -0
  111. package/build/models/Money.js +99 -0
  112. package/build/models/Page.d.ts +33 -0
  113. package/build/models/Page.js +57 -0
  114. package/build/models/PendingDeviceRegistration.d.ts +90 -0
  115. package/build/models/PendingDeviceRegistration.js +180 -0
  116. package/build/models/PreparedSocialLogin.d.ts +155 -0
  117. package/build/models/PreparedSocialLogin.js +235 -0
  118. package/build/models/Transaction.d.ts +187 -0
  119. package/build/models/Transaction.js +134 -0
  120. package/build/models/Transfer.d.ts +335 -0
  121. package/build/models/Transfer.js +240 -0
  122. package/build/models/Wire.d.ts +213 -0
  123. package/build/models/Wire.js +264 -0
  124. package/build/models/Withdrawal.d.ts +201 -0
  125. package/build/models/Withdrawal.js +156 -0
  126. package/build/models/redaction.d.ts +18 -0
  127. package/build/models/redaction.js +23 -0
  128. package/build/sca/ScaClient.d.ts +105 -0
  129. package/build/sca/ScaClient.js +193 -0
  130. package/build/securekey/InMemorySecureKey.d.ts +23 -0
  131. package/build/securekey/InMemorySecureKey.js +127 -0
  132. package/build/securekey/NativeSecureKey.d.ts +24 -0
  133. package/build/securekey/NativeSecureKey.js +178 -0
  134. package/build/securekey/NativeSecureKeyBridge.d.ts +83 -0
  135. package/build/securekey/NativeSecureKeyBridge.js +19 -0
  136. package/build/securekey/SecureKey.d.ts +137 -0
  137. package/build/securekey/SecureKey.js +19 -0
  138. package/build/securekey/alias.d.ts +88 -0
  139. package/build/securekey/alias.js +175 -0
  140. package/build/securekey/ownerAuthKeyResolver.d.ts +56 -0
  141. package/build/securekey/ownerAuthKeyResolver.js +63 -0
  142. package/build/securekey/resolveNativeBridge.d.ts +30 -0
  143. package/build/securekey/resolveNativeBridge.js +120 -0
  144. package/build/testing.d.ts +18 -0
  145. package/build/testing.js +34 -0
  146. package/build/transport/DaaTransport.d.ts +35 -0
  147. package/build/transport/DaaTransport.js +19 -0
  148. package/build/transport/headers.d.ts +30 -0
  149. package/build/transport/headers.js +45 -0
  150. package/build/validation/requestBody.d.ts +27 -0
  151. package/build/validation/requestBody.js +56 -0
  152. package/build/validation/uuid.d.ts +25 -0
  153. package/build/validation/uuid.js +33 -0
  154. package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
  155. package/build/wire/accountLimitsUsagePayload.js +130 -0
  156. package/build/wire/accountPayload.d.ts +36 -0
  157. package/build/wire/accountPayload.js +100 -0
  158. package/build/wire/achPayload.d.ts +24 -0
  159. package/build/wire/achPayload.js +82 -0
  160. package/build/wire/addressObjectPayload.d.ts +44 -0
  161. package/build/wire/addressObjectPayload.js +64 -0
  162. package/build/wire/daaStatusCodes.d.ts +64 -0
  163. package/build/wire/daaStatusCodes.js +69 -0
  164. package/build/wire/dataEnvelope.d.ts +40 -0
  165. package/build/wire/dataEnvelope.js +79 -0
  166. package/build/wire/depositPayload.d.ts +42 -0
  167. package/build/wire/depositPayload.js +159 -0
  168. package/build/wire/deviceContextPayload.d.ts +33 -0
  169. package/build/wire/deviceContextPayload.js +57 -0
  170. package/build/wire/deviceRegistrationResultPayload.d.ts +32 -0
  171. package/build/wire/deviceRegistrationResultPayload.js +128 -0
  172. package/build/wire/errorEnvelope.d.ts +43 -0
  173. package/build/wire/errorEnvelope.js +85 -0
  174. package/build/wire/fiatAccountPayload.d.ts +37 -0
  175. package/build/wire/fiatAccountPayload.js +93 -0
  176. package/build/wire/instant.d.ts +27 -0
  177. package/build/wire/instant.js +91 -0
  178. package/build/wire/jsonNumber.d.ts +30 -0
  179. package/build/wire/jsonNumber.js +34 -0
  180. package/build/wire/moneyPayload.d.ts +30 -0
  181. package/build/wire/moneyPayload.js +56 -0
  182. package/build/wire/paginationLinks.d.ts +28 -0
  183. package/build/wire/paginationLinks.js +167 -0
  184. package/build/wire/payload.d.ts +60 -0
  185. package/build/wire/payload.js +121 -0
  186. package/build/wire/pendingRegistrationPayload.d.ts +32 -0
  187. package/build/wire/pendingRegistrationPayload.js +54 -0
  188. package/build/wire/socialLoginRequestPayload.d.ts +31 -0
  189. package/build/wire/socialLoginRequestPayload.js +72 -0
  190. package/build/wire/transactionPayload.d.ts +31 -0
  191. package/build/wire/transactionPayload.js +126 -0
  192. package/build/wire/transferPayload.d.ts +43 -0
  193. package/build/wire/transferPayload.js +218 -0
  194. package/build/wire/wireEnums.d.ts +22 -0
  195. package/build/wire/wireEnums.js +69 -0
  196. package/build/wire/wirePayload.d.ts +29 -0
  197. package/build/wire/wirePayload.js +138 -0
  198. package/build/wire/withdrawalPayload.d.ts +27 -0
  199. package/build/wire/withdrawalPayload.js +179 -0
  200. package/expo-module.config.json +14 -0
  201. package/ios/DaaRegistrationExceptions.swift +58 -0
  202. package/ios/DaaRegistrationModule.swift +143 -0
  203. package/ios/DaaScaExceptions.swift +96 -0
  204. package/ios/DaaScaModule.swift +125 -0
  205. package/ios/DaaSecureKeyExceptions.swift +77 -0
  206. package/ios/DaaSecureKeyModule.swift +162 -0
  207. package/ios/InstallationIdentityStore.swift +126 -0
  208. package/ios/UnpaddedBase64URL.swift +42 -0
  209. package/package.json +114 -4
  210. package/src/DaaClient.ts +171 -0
  211. package/src/api/AccountLimitsClient.ts +146 -0
  212. package/src/api/AccountsClient.ts +305 -0
  213. package/src/api/AchFiatAccountsClient.ts +147 -0
  214. package/src/api/AuthClient.ts +331 -0
  215. package/src/api/DaaUserClient.ts +270 -0
  216. package/src/api/DepositAddressesClient.ts +239 -0
  217. package/src/api/DepositsClient.ts +208 -0
  218. package/src/api/FiatAccountsClient.ts +50 -0
  219. package/src/api/TransactionsClient.ts +137 -0
  220. package/src/api/TransfersClient.ts +361 -0
  221. package/src/api/WireFiatAccountsClient.ts +172 -0
  222. package/src/api/WithdrawalsClient.ts +339 -0
  223. package/src/api/loginFailure.ts +75 -0
  224. package/src/api/pagination.ts +63 -0
  225. package/src/api/queryParameters.ts +82 -0
  226. package/src/api/resourceRequest.ts +135 -0
  227. package/src/api/signedResource.ts +267 -0
  228. package/src/auth/RegistrationFlowKey.ts +274 -0
  229. package/src/auth/daaRegistrationNative.ts +236 -0
  230. package/src/auth/deviceAuthorization.ts +302 -0
  231. package/src/auth/ownerGrant.ts +102 -0
  232. package/src/auth/prepareReceipt.ts +522 -0
  233. package/src/auth/registrationAuthorization.ts +306 -0
  234. package/src/auth/registrationCodeVerifier.ts +76 -0
  235. package/src/config.ts +156 -0
  236. package/src/crypto/base64url.ts +88 -0
  237. package/src/crypto/bytes.ts +30 -0
  238. package/src/crypto/es256Jws.ts +240 -0
  239. package/src/crypto/jwkThumbprint.ts +65 -0
  240. package/src/crypto/random.ts +113 -0
  241. package/src/crypto/serialization.ts +42 -0
  242. package/src/crypto/sha256.ts +105 -0
  243. package/src/errors.ts +319 -0
  244. package/src/index.ts +223 -0
  245. package/src/models/Account.ts +264 -0
  246. package/src/models/AccountLimitsUsage.ts +192 -0
  247. package/src/models/Ach.ts +269 -0
  248. package/src/models/AddressObject.ts +169 -0
  249. package/src/models/BusinessPii.ts +154 -0
  250. package/src/models/CreateAccountRequest.ts +109 -0
  251. package/src/models/CreateTransferRequest.ts +114 -0
  252. package/src/models/CreateWithdrawalRequest.ts +120 -0
  253. package/src/models/DaaUserContext.ts +172 -0
  254. package/src/models/Deposit.ts +307 -0
  255. package/src/models/DepositSummary.ts +142 -0
  256. package/src/models/FiatAccount.ts +195 -0
  257. package/src/models/GenerateAddressRequest.ts +101 -0
  258. package/src/models/Money.ts +91 -0
  259. package/src/models/Page.ts +48 -0
  260. package/src/models/PendingDeviceRegistration.ts +197 -0
  261. package/src/models/PreparedSocialLogin.ts +287 -0
  262. package/src/models/Transaction.ts +247 -0
  263. package/src/models/Transfer.ts +459 -0
  264. package/src/models/Wire.ts +405 -0
  265. package/src/models/Withdrawal.ts +283 -0
  266. package/src/models/redaction.ts +22 -0
  267. package/src/sca/ScaClient.ts +289 -0
  268. package/src/securekey/InMemorySecureKey.ts +138 -0
  269. package/src/securekey/NativeSecureKey.ts +179 -0
  270. package/src/securekey/NativeSecureKeyBridge.ts +109 -0
  271. package/src/securekey/SecureKey.ts +149 -0
  272. package/src/securekey/alias.ts +204 -0
  273. package/src/securekey/ownerAuthKeyResolver.ts +96 -0
  274. package/src/securekey/resolveNativeBridge.ts +185 -0
  275. package/src/testing.ts +32 -0
  276. package/src/transport/DaaTransport.ts +42 -0
  277. package/src/transport/headers.ts +46 -0
  278. package/src/validation/requestBody.ts +60 -0
  279. package/src/validation/uuid.ts +31 -0
  280. package/src/wire/accountLimitsUsagePayload.ts +182 -0
  281. package/src/wire/accountPayload.ts +108 -0
  282. package/src/wire/achPayload.ts +98 -0
  283. package/src/wire/addressObjectPayload.ts +64 -0
  284. package/src/wire/daaStatusCodes.ts +69 -0
  285. package/src/wire/dataEnvelope.ts +80 -0
  286. package/src/wire/depositPayload.ts +186 -0
  287. package/src/wire/deviceContextPayload.ts +58 -0
  288. package/src/wire/deviceRegistrationResultPayload.ts +153 -0
  289. package/src/wire/errorEnvelope.ts +87 -0
  290. package/src/wire/fiatAccountPayload.ts +112 -0
  291. package/src/wire/instant.ts +93 -0
  292. package/src/wire/jsonNumber.ts +33 -0
  293. package/src/wire/moneyPayload.ts +55 -0
  294. package/src/wire/paginationLinks.ts +204 -0
  295. package/src/wire/payload.ts +146 -0
  296. package/src/wire/pendingRegistrationPayload.ts +75 -0
  297. package/src/wire/socialLoginRequestPayload.ts +89 -0
  298. package/src/wire/transactionPayload.ts +145 -0
  299. package/src/wire/transferPayload.ts +249 -0
  300. package/src/wire/wireEnums.ts +74 -0
  301. package/src/wire/wirePayload.ts +160 -0
  302. package/src/wire/withdrawalPayload.ts +219 -0
  303. package/testing.d.ts +19 -0
  304. package/testing.js +25 -0
@@ -0,0 +1,339 @@
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 { serializeBody } from '../crypto/serialization'
20
+ import { contractViolation } from '../errors'
21
+ import type {
22
+ CreateWithdrawalAmount,
23
+ CreateWithdrawalDestination,
24
+ CreateWithdrawalRequest,
25
+ CreateWithdrawalRiskSignals,
26
+ CreateWithdrawalSource,
27
+ CreateWithdrawalToAmount,
28
+ } from '../models/CreateWithdrawalRequest'
29
+ import type { Page } from '../models/Page'
30
+ import type { WithdrawalDetail } from '../models/Withdrawal'
31
+ import type { DaaTransport } from '../transport/DaaTransport'
32
+ import { requireBodyObject, requireKnownProperties } from '../validation/requestBody'
33
+ import { isUuid } from '../validation/uuid'
34
+ import { JSON_NUMBER } from '../wire/jsonNumber'
35
+ import { toWithdrawalDetail, toWithdrawalDetails } from '../wire/withdrawalPayload'
36
+ import { readPage } from './pagination'
37
+ import { append, appendEnum, appendEnums, appendString, appendUuid } from './queryParameters'
38
+ import { readResource } from './resourceRequest'
39
+ import { postSignedResource, type DaaUserSigning } from './signedResource'
40
+
41
+ /**
42
+ * `GET /v1/accounts/withdrawals[/{withdrawalId}]` — the **public** path,
43
+ * exactly as for Transfers (`TransfersClient.ts`).
44
+ */
45
+ const WITHDRAWAL_PATH_PREFIX = '/v1/accounts/withdrawals/'
46
+ const WITHDRAWAL_COLLECTION_PATH = '/v1/accounts/withdrawals'
47
+
48
+ /** The closed set of withdrawal list statuses; mirrors `models/Withdrawal.ts`'s `WithdrawalStatus` kinds. */
49
+ const WITHDRAWAL_LIST_STATUSES = Object.freeze(['pending', 'complete', 'failed'] as const)
50
+
51
+ export type WithdrawalListQuery = Readonly<{
52
+ /** Select a backing source explicitly; omitted derives from `accountId` or defaults to omnibus. */
53
+ custodyType?: 'omnibus' | 'segregated' | 'self'
54
+ /** Match withdrawals funded from this source account. Account ids are strings, not necessarily UUIDs. */
55
+ accountId?: string
56
+ /** Match any of these withdrawal statuses. Repeatable `status` query params. */
57
+ status?: readonly (typeof WITHDRAWAL_LIST_STATUSES)[number][]
58
+ /** Inclusive RFC 3339 creation-time lower bound. */
59
+ from?: string
60
+ /** Inclusive RFC 3339 creation-time upper bound. */
61
+ to?: string
62
+ /** Initial forward keyset cursor. Link-derived navigation remains opaque. */
63
+ pageAfter?: string
64
+ /** Initial backward keyset cursor. Link-derived navigation remains opaque. */
65
+ pageBefore?: string
66
+ pageSize?: number
67
+ }>
68
+
69
+ /**
70
+ * The properties the Owner-authorization registry's `withdrawal` schema names,
71
+ * in the order it names them, at each level of the body. See
72
+ * `TransfersClient`'s equivalent constant for why order matters: these are the
73
+ * bytes that get signed.
74
+ */
75
+ const WITHDRAWAL_PROPERTIES = Object.freeze([
76
+ 'idempotencyKey',
77
+ 'source',
78
+ 'destination',
79
+ 'amount',
80
+ 'toAmount',
81
+ 'riskSignals',
82
+ 'burnAll',
83
+ ])
84
+ const WITHDRAWAL_SOURCE_PROPERTIES = Object.freeze(['type', 'id'])
85
+ const WITHDRAWAL_DESTINATION_PROPERTIES = Object.freeze(['type', 'id', 'name'])
86
+ const WITHDRAWAL_AMOUNT_PROPERTIES = Object.freeze(['amount', 'currency'])
87
+ const WITHDRAWAL_TO_AMOUNT_PROPERTIES = Object.freeze(['amount', 'currency'])
88
+ const WITHDRAWAL_RISK_SIGNAL_PROPERTIES = Object.freeze(['ipAddress', 'sessionId', 'deviceId'])
89
+ const WITHDRAWAL_TO_AMOUNT_CURRENCIES = Object.freeze(['USD', 'EUR'])
90
+
91
+ /**
92
+ * Reads over DAA withdrawals, plus the signed withdrawal create, as the SDK
93
+ * contract's `WithdrawalsClient`.
94
+ *
95
+ * {@link list} retains the API's RFC 8288 navigation queries as opaque text.
96
+ * Collection rows use the same public projection {@link get} uses;
97
+ * `policyEvaluation` is GET-only and is omitted (decoded as `null`) on list
98
+ * items. {@link create} is an Owner-authorized write: it carries an
99
+ * `X-Device-Authorization` bound to the exact bytes it sends and cannot happen
100
+ * without the registered AuthKey `forUser` supplies.
101
+ *
102
+ * Not constructible by a consumer: exported from `index.ts` as a type only, and
103
+ * the `#transport` field makes the type nominal.
104
+ */
105
+ export class WithdrawalsClient {
106
+ readonly #transport: DaaTransport
107
+ readonly #publicApiOrigin: string
108
+ readonly #signing: DaaUserSigning
109
+
110
+ /** @internal Constructed only through the internal user-client factory. */
111
+ constructor(transport: DaaTransport, publicApiOrigin: string, signing: DaaUserSigning) {
112
+ this.#transport = transport
113
+ this.#publicApiOrigin = publicApiOrigin
114
+ this.#signing = signing
115
+ Object.freeze(this)
116
+ }
117
+
118
+ /** List withdrawals and retain the API's opaque navigation queries unchanged. */
119
+ async list(query?: WithdrawalListQuery): Promise<Page<WithdrawalDetail>> {
120
+ return readPage({
121
+ transport: this.#transport,
122
+ publicApiOrigin: this.#publicApiOrigin,
123
+ path: WITHDRAWAL_COLLECTION_PATH,
124
+ query: withdrawalListQuery(query),
125
+ decode: toWithdrawalDetails,
126
+ })
127
+ }
128
+
129
+ /** Read one withdrawal over the public Accounts route. */
130
+ async get(withdrawalId: string): Promise<WithdrawalDetail> {
131
+ if (!isUuid(withdrawalId)) {
132
+ throw contractViolation('withdrawalId must be a UUID')
133
+ }
134
+
135
+ return readResource({
136
+ transport: this.#transport,
137
+ path: WITHDRAWAL_PATH_PREFIX + withdrawalId,
138
+ decode: toWithdrawalDetail,
139
+ })
140
+ }
141
+
142
+ /**
143
+ * Create a withdrawal, authorized by the registered device key.
144
+ *
145
+ * The body is validated, serialized **once**, and that exact byte slice is
146
+ * both hashed into the authorization's `body_sha256` claim and sent as the
147
+ * request entity. Nothing between here and the transport re-serializes it.
148
+ *
149
+ * Neither the method nor the path is chosen here. `postSignedResource`
150
+ * resolves both from the registry entry for `withdrawal`, so a signed write
151
+ * cannot be aimed somewhere the operation does not name.
152
+ *
153
+ * The response decodes through the same public projection {@link get} uses:
154
+ * `policyEvaluation` is GET-only and is omitted (decoded as `null`) here too.
155
+ *
156
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a request
157
+ * the registry schema would reject, for an AuthKey that is not yet
158
+ * registered — the create is refused locally, before anything is signed or
159
+ * sent — for a rejected or replayed authorization (including a key that is
160
+ * no longer active: DAA has no revoked-credential code, so this never
161
+ * throws `device_revoked`), and for a response the SDK cannot read;
162
+ * `idempotency_conflict`, with the request's key, for a `409` with
163
+ * `IDEMPOTENCY_KEY_REUSED` (`420034`): reconcile the original withdrawal with
164
+ * the same key; do not mint a new key for it;
165
+ * `detail.kind === 'api'` for a status other than the documented `201`; and
166
+ * `detail.kind === 'transport'` if the consumer's transport throws, with the
167
+ * thrown value as `err.cause` and the request's `idempotencyKey` on the
168
+ * detail.
169
+ */
170
+ async create(request: CreateWithdrawalRequest): Promise<WithdrawalDetail> {
171
+ const bodyBytes = serializeBody(createWithdrawalBody(request))
172
+ return postSignedResource({
173
+ transport: this.#transport,
174
+ operation: 'withdrawal',
175
+ authKey: await this.#signing.resolveAuthKey(),
176
+ authKeyId: this.#signing.authKeyId,
177
+ bodyBytes,
178
+ // The contract documents exactly 201, with a Location header. Another
179
+ // 2xx is an observable API failure rather than a silently accepted
180
+ // variant, the same rule the by-id read applies to 200.
181
+ expectedStatus: 201,
182
+ decode: toWithdrawalDetail,
183
+ })
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Project a validated request onto the registry's `withdrawal` shape.
189
+ *
190
+ * Returned rather than serialized here so the caller can hold the one byte
191
+ * slice this body becomes; see {@link WithdrawalsClient.create}.
192
+ */
193
+ function createWithdrawalBody(request: CreateWithdrawalRequest): object {
194
+ requireBodyObject(request, 'withdrawal create request')
195
+ requireKnownProperties(request, WITHDRAWAL_PROPERTIES, 'withdrawal create request')
196
+
197
+ const { idempotencyKey, source, destination, amount, toAmount, riskSignals, burnAll } = request
198
+
199
+ // The registry types this `format: uuid` and, like `transfer`, narrows it no
200
+ // further — unlike `create_account`, whose own contract text says v4.
201
+ if (typeof idempotencyKey !== 'string' || !isUuid(idempotencyKey)) {
202
+ throw contractViolation('idempotencyKey must be a UUID')
203
+ }
204
+
205
+ return {
206
+ idempotencyKey,
207
+ ...(source === undefined ? {} : { source: withdrawalSource(source) }),
208
+ destination: withdrawalDestination(destination),
209
+ amount: withdrawalAmount(amount),
210
+ ...(toAmount === undefined ? {} : { toAmount: withdrawalToAmount(toAmount) }),
211
+ ...(riskSignals === undefined ? {} : { riskSignals: withdrawalRiskSignals(riskSignals) }),
212
+ ...(burnAll === undefined ? {} : { burnAll: withdrawalBurnAll(burnAll) }),
213
+ }
214
+ }
215
+
216
+ function withdrawalSource(source: CreateWithdrawalSource): object {
217
+ requireBodyObject(source, 'withdrawal source')
218
+ requireKnownProperties(source, WITHDRAWAL_SOURCE_PROPERTIES, 'withdrawal source')
219
+ const { type, id } = source
220
+ if (type !== 'account') {
221
+ throw contractViolation('withdrawal source type must be account')
222
+ }
223
+ if (typeof id !== 'string' || id.length === 0) {
224
+ throw contractViolation('withdrawal source id must be a non-empty string')
225
+ }
226
+ return { type, id }
227
+ }
228
+
229
+ function withdrawalDestination(destination: CreateWithdrawalDestination): object {
230
+ requireBodyObject(destination, 'withdrawal destination')
231
+ requireKnownProperties(destination, WITHDRAWAL_DESTINATION_PROPERTIES, 'withdrawal destination')
232
+ const { type, id, name } = destination
233
+ if (type !== 'wire' && type !== 'ach') {
234
+ throw contractViolation('withdrawal destination type must be wire or ach')
235
+ }
236
+ // Unlike a transfer's account-leg id, the registry types this `format: uuid`:
237
+ // a withdrawal destination names a registered fiat account, not a public
238
+ // account id.
239
+ if (typeof id !== 'string' || !isUuid(id)) {
240
+ throw contractViolation('withdrawal destination id must be a UUID')
241
+ }
242
+ if (name !== undefined && (typeof name !== 'string' || name.length === 0)) {
243
+ throw contractViolation('withdrawal destination name must be a non-empty string')
244
+ }
245
+ return {
246
+ type,
247
+ id,
248
+ ...(name === undefined ? {} : { name }),
249
+ }
250
+ }
251
+
252
+ function withdrawalAmount(amount: CreateWithdrawalAmount): object {
253
+ requireBodyObject(amount, 'withdrawal amount')
254
+ requireKnownProperties(amount, WITHDRAWAL_AMOUNT_PROPERTIES, 'withdrawal amount')
255
+ const { amount: amountValue, currency } = amount
256
+ if (typeof amountValue !== 'string' || !JSON_NUMBER.test(amountValue)) {
257
+ throw contractViolation('withdrawal amount must be a decimal string, e.g. "10.25"')
258
+ }
259
+ if (typeof currency !== 'string' || currency.length === 0) {
260
+ throw contractViolation('withdrawal amount currency must be a non-empty string')
261
+ }
262
+ return { amount: amountValue, currency }
263
+ }
264
+
265
+ function withdrawalToAmount(toAmount: CreateWithdrawalToAmount): object {
266
+ requireBodyObject(toAmount, 'withdrawal toAmount')
267
+ requireKnownProperties(toAmount, WITHDRAWAL_TO_AMOUNT_PROPERTIES, 'withdrawal toAmount')
268
+ const { amount, currency } = toAmount
269
+ if (amount !== undefined && (typeof amount !== 'string' || !JSON_NUMBER.test(amount))) {
270
+ throw contractViolation('withdrawal toAmount amount must be a decimal string, e.g. "10.25"')
271
+ }
272
+ if (typeof currency !== 'string' || !WITHDRAWAL_TO_AMOUNT_CURRENCIES.includes(currency)) {
273
+ throw contractViolation('withdrawal toAmount currency must be USD or EUR')
274
+ }
275
+ return {
276
+ ...(amount === undefined ? {} : { amount }),
277
+ currency,
278
+ }
279
+ }
280
+
281
+ function withdrawalRiskSignals(riskSignals: CreateWithdrawalRiskSignals): object {
282
+ requireBodyObject(riskSignals, 'withdrawal risk signals')
283
+ requireKnownProperties(riskSignals, WITHDRAWAL_RISK_SIGNAL_PROPERTIES, 'withdrawal risk signals')
284
+ const { ipAddress, sessionId, deviceId } = riskSignals
285
+ requireOptionalRiskSignal(ipAddress, 'ipAddress')
286
+ requireOptionalRiskSignal(sessionId, 'sessionId')
287
+ requireOptionalRiskSignal(deviceId, 'deviceId')
288
+ // The registry requires none of these, so an object with none of them is a
289
+ // valid `riskSignals` and is sent as the empty object the caller asked for.
290
+ return {
291
+ ...(ipAddress === undefined ? {} : { ipAddress }),
292
+ ...(sessionId === undefined ? {} : { sessionId }),
293
+ ...(deviceId === undefined ? {} : { deviceId }),
294
+ }
295
+ }
296
+
297
+ function requireOptionalRiskSignal(value: string | undefined, name: string): void {
298
+ if (value !== undefined && (typeof value !== 'string' || value.length === 0)) {
299
+ throw contractViolation(`withdrawal risk signal ${name} must be a non-empty string`)
300
+ }
301
+ }
302
+
303
+ function withdrawalBurnAll(value: boolean): boolean {
304
+ if (typeof value !== 'boolean') {
305
+ throw contractViolation('withdrawal burnAll must be a boolean')
306
+ }
307
+ return value
308
+ }
309
+
310
+ function withdrawalListQuery(query: WithdrawalListQuery | undefined): string | null {
311
+ if (query === undefined) return null
312
+ if (typeof query !== 'object' || query === null || Array.isArray(query)) {
313
+ throw contractViolation('withdrawal list query must be an object')
314
+ }
315
+ if (query.pageAfter !== undefined && query.pageBefore !== undefined) {
316
+ throw contractViolation('pageAfter and pageBefore cannot be used together')
317
+ }
318
+ if (query.status !== undefined && (!Array.isArray(query.status) || query.status.length === 0)) {
319
+ throw contractViolation('status must be a non-empty array')
320
+ }
321
+
322
+ const parts: string[] = []
323
+ appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self'])
324
+ appendString(parts, 'accountId', query.accountId)
325
+ appendEnums(parts, 'status', query.status, WITHDRAWAL_LIST_STATUSES)
326
+ appendString(parts, 'from', query.from)
327
+ appendString(parts, 'to', query.to)
328
+ // Unlike account cursors, the service models withdrawal cursors as UUID
329
+ // withdrawal ids — the same rule `get`'s `withdrawalId` guard applies.
330
+ appendUuid(parts, 'pageAfter', query.pageAfter)
331
+ appendUuid(parts, 'pageBefore', query.pageBefore)
332
+ if (query.pageSize !== undefined) {
333
+ if (!Number.isInteger(query.pageSize) || query.pageSize < 1) {
334
+ throw contractViolation('pageSize must be a positive integer')
335
+ }
336
+ append(parts, 'pageSize', String(query.pageSize))
337
+ }
338
+ return parts.length === 0 ? null : parts.join('&')
339
+ }
@@ -0,0 +1,75 @@
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
+ idempotencyConflict,
22
+ loginRequestExpired,
23
+ type DaaError,
24
+ } from '../errors'
25
+ import type { DaaHttpResponse } from '../transport/DaaTransport'
26
+ import { headerValueIgnoringCase } from '../transport/headers'
27
+ import { isDaaStatus } from '../wire/daaStatusCodes'
28
+ import { readDaaStatusCode } from '../wire/errorEnvelope'
29
+
30
+ /**
31
+ * The failure the three login calls (Prepare, Social Session, and Device
32
+ * Registration Complete) classify themselves, or `null` when the response is
33
+ * left to `decodeResourceResponse`, which decodes the success status and turns
34
+ * every other status into `api`.
35
+ *
36
+ * Classified on the numeric code only (a non-numeric string `code`, even a
37
+ * name such as `IDEMPOTENCY_KEY_REUSED`, is left to `api`):
38
+ *
39
+ * - `410` is `login_request_expired`.
40
+ * - `IDEMPOTENCY_KEY_REUSED` (`420034`) on a `409` is `idempotency_conflict`,
41
+ * with the key the SDK minted for this request. That key is in the bytes the
42
+ * SDK serialized and sent, so it is never read from the response.
43
+ * - `LOGIN_REQUEST_CONSUMED` (`420039`) is `contract_violation`. An identical
44
+ * successful step converges and never returns it, so it means that a
45
+ * different request used the login request.
46
+ * - DAA also returns `409` for `AUTH_KEY_BINDING_CONFLICT` (`420038`), which
47
+ * classifies as `api`, not retryable. A `409` without a code that this
48
+ * SDK classifies, or without a readable body, is `api` too. So no status
49
+ * alone produces `idempotency_conflict`.
50
+ *
51
+ * A `2xx` response is never classified here, even when its body has a `code`.
52
+ */
53
+ export function loginStepFailure(
54
+ response: DaaHttpResponse,
55
+ idempotencyKey: string,
56
+ ): DaaError | null {
57
+ const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
58
+ if (response.status === 410) {
59
+ return loginRequestExpired(correlationId)
60
+ }
61
+ if (response.status >= 200 && response.status < 300) {
62
+ return null
63
+ }
64
+ const daaStatusCode = readDaaStatusCode(response.bodyBytes)
65
+ if (response.status === 409 && isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) {
66
+ return idempotencyConflict(idempotencyKey, correlationId)
67
+ }
68
+ if (isDaaStatus(daaStatusCode, 'LOGIN_REQUEST_CONSUMED')) {
69
+ return contractViolation(
70
+ 'the login request was already used by a different request',
71
+ correlationId,
72
+ )
73
+ }
74
+ return null
75
+ }
@@ -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
+ }