@paxosglobal/sdk 0.0.0-stage → 0.1.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 (212) hide show
  1. package/AGENTS.md +268 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +191 -0
  4. package/README.md +445 -2
  5. package/dist/auth.d.ts +60 -0
  6. package/dist/auth.js +248 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +353 -0
  9. package/dist/client.js +967 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/constants.d.ts +16 -0
  12. package/dist/constants.js +17 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/decimal-fields.d.ts +16 -0
  15. package/dist/decimal-fields.js +570 -0
  16. package/dist/decimal-fields.js.map +1 -0
  17. package/dist/decimal.d.ts +25 -0
  18. package/dist/decimal.js +93 -0
  19. package/dist/decimal.js.map +1 -0
  20. package/dist/decode.d.ts +34 -0
  21. package/dist/decode.js +118 -0
  22. package/dist/decode.js.map +1 -0
  23. package/dist/enums.d.ts +1080 -0
  24. package/dist/enums.js +1031 -0
  25. package/dist/enums.js.map +1 -0
  26. package/dist/errors.d.ts +142 -0
  27. package/dist/errors.js +261 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/generated-types.d.ts +13629 -0
  30. package/dist/generated-types.js +3 -0
  31. package/dist/generated-types.js.map +1 -0
  32. package/dist/index.d.ts +32 -0
  33. package/dist/index.js +31 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/models.d.ts +299 -0
  36. package/dist/models.js +3 -0
  37. package/dist/models.js.map +1 -0
  38. package/dist/paxos-client.d.ts +107 -0
  39. package/dist/paxos-client.js +157 -0
  40. package/dist/paxos-client.js.map +1 -0
  41. package/dist/query-keys.d.ts +1 -0
  42. package/dist/query-keys.js +31 -0
  43. package/dist/query-keys.js.map +1 -0
  44. package/dist/response-defaults.d.ts +2 -0
  45. package/dist/response-defaults.js +109 -0
  46. package/dist/response-defaults.js.map +1 -0
  47. package/dist/services/account-members.d.ts +32 -0
  48. package/dist/services/account-members.js +46 -0
  49. package/dist/services/account-members.js.map +1 -0
  50. package/dist/services/accounts.d.ts +74 -0
  51. package/dist/services/accounts.js +71 -0
  52. package/dist/services/accounts.js.map +1 -0
  53. package/dist/services/address-verification.d.ts +72 -0
  54. package/dist/services/address-verification.js +64 -0
  55. package/dist/services/address-verification.js.map +1 -0
  56. package/dist/services/api-credentials.d.ts +44 -0
  57. package/dist/services/api-credentials.js +42 -0
  58. package/dist/services/api-credentials.js.map +1 -0
  59. package/dist/services/claims.d.ts +68 -0
  60. package/dist/services/claims.js +67 -0
  61. package/dist/services/claims.js.map +1 -0
  62. package/dist/services/cross-chain-transfer.d.ts +71 -0
  63. package/dist/services/cross-chain-transfer.js +68 -0
  64. package/dist/services/cross-chain-transfer.js.map +1 -0
  65. package/dist/services/crypto-deposits.d.ts +30 -0
  66. package/dist/services/crypto-deposits.js +39 -0
  67. package/dist/services/crypto-deposits.js.map +1 -0
  68. package/dist/services/crypto-withdrawals.d.ts +60 -0
  69. package/dist/services/crypto-withdrawals.js +42 -0
  70. package/dist/services/crypto-withdrawals.js.map +1 -0
  71. package/dist/services/deposit-addresses.d.ts +54 -0
  72. package/dist/services/deposit-addresses.js +36 -0
  73. package/dist/services/deposit-addresses.js.map +1 -0
  74. package/dist/services/events.d.ts +53 -0
  75. package/dist/services/events.js +39 -0
  76. package/dist/services/events.js.map +1 -0
  77. package/dist/services/exchange.d.ts +52 -0
  78. package/dist/services/exchange.js +30 -0
  79. package/dist/services/exchange.js.map +1 -0
  80. package/dist/services/fees.d.ts +15 -0
  81. package/dist/services/fees.js +24 -0
  82. package/dist/services/fees.js.map +1 -0
  83. package/dist/services/fiat-transfers.d.ts +133 -0
  84. package/dist/services/fiat-transfers.js +127 -0
  85. package/dist/services/fiat-transfers.js.map +1 -0
  86. package/dist/services/identity-controls.d.ts +43 -0
  87. package/dist/services/identity-controls.js +42 -0
  88. package/dist/services/identity-controls.js.map +1 -0
  89. package/dist/services/identity-documents.d.ts +45 -0
  90. package/dist/services/identity-documents.js +50 -0
  91. package/dist/services/identity-documents.js.map +1 -0
  92. package/dist/services/identity.d.ts +122 -0
  93. package/dist/services/identity.js +66 -0
  94. package/dist/services/identity.js.map +1 -0
  95. package/dist/services/index.d.ts +89 -0
  96. package/dist/services/index.js +55 -0
  97. package/dist/services/index.js.map +1 -0
  98. package/dist/services/institution-members.d.ts +30 -0
  99. package/dist/services/institution-members.js +44 -0
  100. package/dist/services/institution-members.js.map +1 -0
  101. package/dist/services/internal-transfers.d.ts +15 -0
  102. package/dist/services/internal-transfers.js +26 -0
  103. package/dist/services/internal-transfers.js.map +1 -0
  104. package/dist/services/issuer-quotes.d.ts +72 -0
  105. package/dist/services/issuer-quotes.js +66 -0
  106. package/dist/services/issuer-quotes.js.map +1 -0
  107. package/dist/services/limits.d.ts +20 -0
  108. package/dist/services/limits.js +23 -0
  109. package/dist/services/limits.js.map +1 -0
  110. package/dist/services/market-data.d.ts +15 -0
  111. package/dist/services/market-data.js +23 -0
  112. package/dist/services/market-data.js.map +1 -0
  113. package/dist/services/monitoring-addresses.d.ts +64 -0
  114. package/dist/services/monitoring-addresses.js +68 -0
  115. package/dist/services/monitoring-addresses.js.map +1 -0
  116. package/dist/services/orchestration-rules.d.ts +53 -0
  117. package/dist/services/orchestration-rules.js +47 -0
  118. package/dist/services/orchestration-rules.js.map +1 -0
  119. package/dist/services/orchestrations.d.ts +70 -0
  120. package/dist/services/orchestrations.js +45 -0
  121. package/dist/services/orchestrations.js.map +1 -0
  122. package/dist/services/orders.d.ts +86 -0
  123. package/dist/services/orders.js +67 -0
  124. package/dist/services/orders.js.map +1 -0
  125. package/dist/services/paxos-transfers.d.ts +24 -0
  126. package/dist/services/paxos-transfers.js +35 -0
  127. package/dist/services/paxos-transfers.js.map +1 -0
  128. package/dist/services/payments.d.ts +46 -0
  129. package/dist/services/payments.js +35 -0
  130. package/dist/services/payments.js.map +1 -0
  131. package/dist/services/payout-groups.d.ts +59 -0
  132. package/dist/services/payout-groups.js +59 -0
  133. package/dist/services/payout-groups.js.map +1 -0
  134. package/dist/services/pricing.d.ts +67 -0
  135. package/dist/services/pricing.js +42 -0
  136. package/dist/services/pricing.js.map +1 -0
  137. package/dist/services/profiles.d.ts +106 -0
  138. package/dist/services/profiles.js +84 -0
  139. package/dist/services/profiles.js.map +1 -0
  140. package/dist/services/quote-executions.d.ts +51 -0
  141. package/dist/services/quote-executions.js +41 -0
  142. package/dist/services/quote-executions.js.map +1 -0
  143. package/dist/services/quotes.d.ts +44 -0
  144. package/dist/services/quotes.js +48 -0
  145. package/dist/services/quotes.js.map +1 -0
  146. package/dist/services/reward-addresses.d.ts +80 -0
  147. package/dist/services/reward-addresses.js +79 -0
  148. package/dist/services/reward-addresses.js.map +1 -0
  149. package/dist/services/rewards-statements.d.ts +35 -0
  150. package/dist/services/rewards-statements.js +32 -0
  151. package/dist/services/rewards-statements.js.map +1 -0
  152. package/dist/services/rewards.d.ts +34 -0
  153. package/dist/services/rewards.js +37 -0
  154. package/dist/services/rewards.js.map +1 -0
  155. package/dist/services/sandbox-deposits.d.ts +15 -0
  156. package/dist/services/sandbox-deposits.js +22 -0
  157. package/dist/services/sandbox-deposits.js.map +1 -0
  158. package/dist/services/sandbox-fiat-transfers.d.ts +15 -0
  159. package/dist/services/sandbox-fiat-transfers.js +24 -0
  160. package/dist/services/sandbox-fiat-transfers.js.map +1 -0
  161. package/dist/services/sandbox-identity.d.ts +39 -0
  162. package/dist/services/sandbox-identity.js +60 -0
  163. package/dist/services/sandbox-identity.js.map +1 -0
  164. package/dist/services/settlement.d.ts +76 -0
  165. package/dist/services/settlement.js +79 -0
  166. package/dist/services/settlement.js.map +1 -0
  167. package/dist/services/stablecoin-conversion.d.ts +70 -0
  168. package/dist/services/stablecoin-conversion.js +65 -0
  169. package/dist/services/stablecoin-conversion.js.map +1 -0
  170. package/dist/services/statements.d.ts +44 -0
  171. package/dist/services/statements.js +35 -0
  172. package/dist/services/statements.js.map +1 -0
  173. package/dist/services/tax-documentation.d.ts +21 -0
  174. package/dist/services/tax-documentation.js +33 -0
  175. package/dist/services/tax-documentation.js.map +1 -0
  176. package/dist/services/tax-forms.d.ts +45 -0
  177. package/dist/services/tax-forms.js +38 -0
  178. package/dist/services/tax-forms.js.map +1 -0
  179. package/dist/services/transfers.d.ts +96 -0
  180. package/dist/services/transfers.js +37 -0
  181. package/dist/services/transfers.js.map +1 -0
  182. package/dist/services/travel-rule.d.ts +32 -0
  183. package/dist/services/travel-rule.js +30 -0
  184. package/dist/services/travel-rule.js.map +1 -0
  185. package/dist/services/user-audit-logs.d.ts +45 -0
  186. package/dist/services/user-audit-logs.js +27 -0
  187. package/dist/services/user-audit-logs.js.map +1 -0
  188. package/dist/services/webhooks.d.ts +58 -0
  189. package/dist/services/webhooks.js +42 -0
  190. package/dist/services/webhooks.js.map +1 -0
  191. package/dist/signing.d.ts +33 -0
  192. package/dist/signing.js +186 -0
  193. package/dist/signing.js.map +1 -0
  194. package/dist/testing/fixtures.d.ts +40 -0
  195. package/dist/testing/fixtures.js +131 -0
  196. package/dist/testing/fixtures.js.map +1 -0
  197. package/dist/testing/index.d.ts +28 -0
  198. package/dist/testing/index.js +28 -0
  199. package/dist/testing/index.js.map +1 -0
  200. package/dist/testing/mock-server.d.ts +121 -0
  201. package/dist/testing/mock-server.js +276 -0
  202. package/dist/testing/mock-server.js.map +1 -0
  203. package/dist/timeouts.d.ts +13 -0
  204. package/dist/timeouts.js +71 -0
  205. package/dist/timeouts.js.map +1 -0
  206. package/dist/types.d.ts +6 -0
  207. package/dist/types.js +7 -0
  208. package/dist/types.js.map +1 -0
  209. package/dist/version.d.ts +1 -0
  210. package/dist/version.js +2 -0
  211. package/dist/version.js.map +1 -0
  212. package/package.json +67 -4
package/dist/auth.js ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * OAuth2 client credentials token manager.
3
+ *
4
+ * Tokens are cached and refreshed 60 seconds before expiry.
5
+ * Concurrent calls share a single in-flight refresh request to avoid
6
+ * stampeding the token endpoint.
7
+ */
8
+ import { AUTH_SCHEME_BEARER, CONTENT_TYPE_FORM, DEFAULT_CALL_TIMEOUT_MS, ERROR_TITLE_REQUEST_TIMED_OUT, HEADER_CONTENT_TYPE, HEADER_REQUEST_ID, OAUTH_GRANT_CLIENT_CREDENTIALS, } from "./constants.js";
9
+ import { budget, cancellable, validateTimeout } from "./timeouts.js";
10
+ import { describeNetworkError, PaxosAuthenticationError, PaxosNetworkError, PaxosTimeoutError } from "./errors.js";
11
+ const TOKEN_EXPIRY_BUFFER_MS = 60_000;
12
+ /**
13
+ * Sane upper bound on a token response's `expires_in` (seconds), applied
14
+ * before computing an expiry timestamp. Without this, a malformed/malicious
15
+ * value pins the cached token's validity arbitrarily far into the future,
16
+ * and the SDK would never refresh it again.
17
+ */
18
+ const MAX_EXPIRES_IN_SECONDS = 100 * 365 * 24 * 60 * 60; // ~100 years
19
+ const OAUTH_ERROR_CODES = new Set([
20
+ "invalid_request",
21
+ "invalid_client",
22
+ "invalid_grant",
23
+ "unauthorized_client",
24
+ "unsupported_grant_type",
25
+ "invalid_scope",
26
+ "server_error",
27
+ "temporarily_unavailable",
28
+ ]);
29
+ /**
30
+ * TokenManager handles automatic OAuth2 token acquisition and caching.
31
+ *
32
+ * Users of the SDK never need to call this directly — the PaxosClient
33
+ * injects the Bearer token on every request.
34
+ */
35
+ export class TokenManager {
36
+ clientId;
37
+ #clientSecret;
38
+ tokenUrl;
39
+ scopes;
40
+ timeoutMs;
41
+ fetchFn;
42
+ refreshController = null;
43
+ #waiters = new Map();
44
+ #cachedToken = null;
45
+ expiresAt = 0;
46
+ // A single Promise for any in-flight token fetch. This prevents concurrent
47
+ // callers from each making a separate token request.
48
+ #refreshPromise = null;
49
+ // Bumped on every invalidate(). Guards against a refresh that was already
50
+ // in flight when invalidate() ran: without this, it could resolve *after*
51
+ // a newer refresh and silently overwrite the cache with its own result —
52
+ // which, if the OAuth endpoint returns the same token for a rapid repeat
53
+ // request, could even be the just-revoked token that triggered the
54
+ // invalidate() in the first place.
55
+ refreshGeneration = 0;
56
+ constructor(clientId, clientSecret, tokenUrl, scopes, timeoutMs, fetchFn) {
57
+ this.clientId = clientId;
58
+ this.#clientSecret = clientSecret;
59
+ this.tokenUrl = tokenUrl;
60
+ this.scopes = scopes ?? [];
61
+ this.fetchFn = fetchFn ?? ((input, init) => globalThis.fetch(input, init));
62
+ validateTimeout(timeoutMs, "token timeout");
63
+ this.timeoutMs = timeoutMs === undefined ? DEFAULT_CALL_TIMEOUT_MS : timeoutMs;
64
+ }
65
+ /**
66
+ * Return a valid access token, fetching a new one if the cached token
67
+ * has expired or is about to expire within the 60-second buffer.
68
+ *
69
+ * `timeoutMs`, if given, bounds the token request only if a refresh is
70
+ * actually triggered — used internally by pagination to keep a
71
+ * mid-iteration refresh inside the remaining `maxDuration` budget rather
72
+ * than this manager's own default timeout.
73
+ *
74
+ * If a refresh is already in-flight from another caller, this call joins
75
+ * it (concurrent refreshes share a single fetch) rather than starting a
76
+ * duplicate one — but `timeoutMs`, if given, bounds *this* caller's own
77
+ * wait for that shared refresh, not the original caller's timeout, so a
78
+ * short remaining budget here can't be blocked past it by someone else's
79
+ * slower refresh.
80
+ */
81
+ async getToken(timeoutMs, signal) {
82
+ const now = Date.now();
83
+ if (this.#cachedToken !== null && now < this.expiresAt) {
84
+ return this.#cachedToken;
85
+ }
86
+ return this.refresh(timeoutMs, signal);
87
+ }
88
+ /**
89
+ * Return the current cached token without triggering a refresh.
90
+ */
91
+ peekToken() {
92
+ const now = Date.now();
93
+ if (this.#cachedToken !== null && now < this.expiresAt) {
94
+ return this.#cachedToken;
95
+ }
96
+ return null;
97
+ }
98
+ /**
99
+ * Invalidate the cached token so the next call to getToken() forces a refresh.
100
+ *
101
+ * Called automatically on 401 responses to handle server-side token revocation.
102
+ */
103
+ invalidate(rejectedToken) {
104
+ // A delayed 401 must preserve a newer token or an already-started refresh.
105
+ if (rejectedToken !== undefined && this.#cachedToken !== rejectedToken)
106
+ return;
107
+ this.#cachedToken = null;
108
+ this.expiresAt = 0;
109
+ // Expiry refreshes retain the old cached token until they finish. A 401
110
+ // for that old token should join the refresh, not detach it and fetch twice.
111
+ if (rejectedToken !== undefined && this.#refreshPromise !== null)
112
+ return;
113
+ // Cancel the in-flight promise so a fresh fetch is started next time.
114
+ this.#refreshPromise = null;
115
+ this.refreshGeneration++;
116
+ }
117
+ /**
118
+ * Fetch a fresh token from the OAuth2 endpoint.
119
+ *
120
+ * Multiple concurrent callers share a single in-flight fetch (singleflight pattern).
121
+ */
122
+ async refresh(timeoutMs, signal) {
123
+ validateTimeout(timeoutMs, "token timeout");
124
+ signal?.throwIfAborted();
125
+ const joining = this.#refreshPromise !== null;
126
+ if (this.#refreshPromise === null) {
127
+ const generation = this.refreshGeneration;
128
+ const controller = new AbortController();
129
+ this.refreshController = controller;
130
+ const promise = this.fetchToken(controller.signal, generation).finally(() => {
131
+ if (this.#refreshPromise === promise)
132
+ this.#refreshPromise = null;
133
+ });
134
+ this.#refreshPromise = promise;
135
+ }
136
+ const promise = this.#refreshPromise;
137
+ const controller = this.refreshController;
138
+ this.#waiters.set(promise, (this.#waiters.get(promise) ?? 0) + 1);
139
+ const wait = budget(joining && signal ? null : timeoutMs === undefined ? this.timeoutMs : timeoutMs, signal, "OAuth attempt");
140
+ try {
141
+ return await cancellable(promise, wait.signal);
142
+ }
143
+ finally {
144
+ wait.cleanup();
145
+ const remaining = (this.#waiters.get(promise) ?? 1) - 1;
146
+ if (remaining)
147
+ this.#waiters.set(promise, remaining);
148
+ else {
149
+ this.#waiters.delete(promise);
150
+ controller.abort();
151
+ if (this.#refreshPromise === promise)
152
+ this.#refreshPromise = null;
153
+ }
154
+ }
155
+ }
156
+ async fetchToken(signal, generation) {
157
+ const body = new URLSearchParams({
158
+ grant_type: OAUTH_GRANT_CLIENT_CREDENTIALS,
159
+ client_id: this.clientId,
160
+ client_secret: this.#clientSecret,
161
+ });
162
+ if (this.scopes.length > 0) {
163
+ body.set("scope", this.scopes.join(" "));
164
+ }
165
+ let response;
166
+ try {
167
+ response = await cancellable(this.fetchFn(this.tokenUrl, {
168
+ method: "POST",
169
+ headers: {
170
+ [HEADER_CONTENT_TYPE]: CONTENT_TYPE_FORM,
171
+ },
172
+ body: body.toString(),
173
+ redirect: "error",
174
+ // Bound the token request explicitly — without this, a stalled OAuth2
175
+ // endpoint hangs forever, outside any timeout the caller configured
176
+ // for API requests (which this fetch call is not one of).
177
+ signal,
178
+ }), signal);
179
+ }
180
+ catch (err) {
181
+ if (err instanceof Error && err.name === "TimeoutError") {
182
+ throw new PaxosTimeoutError({ title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: `Token request failed: ${err}` }, { cause: err });
183
+ }
184
+ signal.throwIfAborted();
185
+ throw new PaxosNetworkError(`Token request failed: ${describeNetworkError(err, this.tokenUrl)}`, { cause: err });
186
+ }
187
+ const readBody = async (read) => {
188
+ try {
189
+ return await cancellable(read(), signal);
190
+ }
191
+ catch (err) {
192
+ if (signal.aborted) {
193
+ throw new PaxosTimeoutError({ title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: `Token response timed out: ${err}` }, { cause: err });
194
+ }
195
+ throw new PaxosNetworkError("Failed to read token response body", { cause: err });
196
+ }
197
+ };
198
+ // Read under the same deadline, but do not expose raw OAuth response text or
199
+ // JSON parser causes: those can contain credentials or issued tokens.
200
+ const text = await readBody(() => response.text());
201
+ let parsed;
202
+ try {
203
+ parsed = JSON.parse(text);
204
+ }
205
+ catch {
206
+ parsed = undefined;
207
+ }
208
+ const data = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
209
+ ? parsed
210
+ : {};
211
+ const requestId = typeof data["request_id"] === "string" && data["request_id"]
212
+ ? data["request_id"]
213
+ : response.headers?.get(HEADER_REQUEST_ID) || undefined;
214
+ const code = typeof data["error"] === "string" && OAUTH_ERROR_CODES.has(data["error"]) ? data["error"] : undefined;
215
+ if (response.status !== 200)
216
+ throw new PaxosAuthenticationError(response.status, requestId, code);
217
+ const token = data["access_token"];
218
+ const rawExpiresIn = data["expires_in"] === undefined ? 3600 : data["expires_in"];
219
+ const tokenType = data["token_type"] === undefined ? AUTH_SCHEME_BEARER : data["token_type"];
220
+ if (typeof token !== "string" ||
221
+ !token.trim() ||
222
+ typeof tokenType !== "string" ||
223
+ tokenType.toLowerCase() !== AUTH_SCHEME_BEARER.toLowerCase() ||
224
+ typeof rawExpiresIn !== "number" ||
225
+ !Number.isFinite(rawExpiresIn) ||
226
+ !Number.isInteger(rawExpiresIn)) {
227
+ throw new PaxosAuthenticationError(response.status, requestId, code);
228
+ }
229
+ const expiresIn = Math.min(Math.max(rawExpiresIn, 0), MAX_EXPIRES_IN_SECONDS);
230
+ const expiresInMs = expiresIn * 1000;
231
+ // Apply expiry buffer so we refresh before the server considers it
232
+ // expired. Clamped to half the token's lifetime (not just its full
233
+ // lifetime) so a short-lived token still gets cached for a while instead
234
+ // of being treated as already-expired the instant it's issued.
235
+ const bufferMs = Math.min(TOKEN_EXPIRY_BUFFER_MS, expiresInMs / 2);
236
+ // Only update the shared cache if no invalidate() has superseded this
237
+ // fetch since it started. A fetch that started before an invalidate()
238
+ // still resolves successfully with a validly-issued token — it's
239
+ // returned to its own caller below regardless — but must not overwrite
240
+ // state a newer, post-invalidate refresh has since set.
241
+ if (generation === this.refreshGeneration) {
242
+ this.#cachedToken = token;
243
+ this.expiresAt = Date.now() + expiresInMs - bufferMs;
244
+ }
245
+ return token;
246
+ }
247
+ }
248
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,uBAAuB,EACvB,6BAA6B,EAC7B,mBAAmB,EACnB,iBAAiB,EACjB,8BAA8B,GAC/B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAA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BAAkB,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC7F,IACE,OAAO,KAAK,KAAK,QAAQ;YACzB,CAAC,KAAK,CAAC,IAAI,EAAE;YACb,OAAO,SAAS,KAAK,QAAQ;YAC7B,SAAS,CAAC,WAAW,EAAE,KAAK,kBAAkB,CAAC,WAAW,EAAE;YAC5D,OAAO,YAAY,KAAK,QAAQ;YAChC,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;YAC9B,CAAC,MAAM,CAAC,SAAS,CAAC,YAAY,CAAC,EAC/B,CAAC;YACD,MAAM,IAAI,wBAAwB,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QACvE,CAAC;QACD,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE,CAAC,CAAC,EAAE,sBAAsB,CAAC,CAAC;QAC9E,MAAM,WAAW,GAAG,SAAS,GAAG,IAAI,CAAC;QACrC,mEAAmE;QACnE,mEAAmE;QACnE,yEAAyE;QACzE,+DAA+D;QAC/D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,WAAW,GAAG,CAAC,CAAC,CAAC;QACnE,sEAAsE;QACtE,sEAAsE;QACtE,iEAAiE;QACjE,uEAAuE;QACvE,wDAAwD;QACxD,IAAI,UAAU,KAAK,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC1C,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;YAC1B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,GAAG,QAAQ,CAAC;QACvD,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["/**\n * OAuth2 client credentials token manager.\n *\n * Tokens are cached and refreshed 60 seconds before expiry.\n * Concurrent calls share a single in-flight refresh request to avoid\n * stampeding the token endpoint.\n */\n\nimport {\n AUTH_SCHEME_BEARER,\n CONTENT_TYPE_FORM,\n DEFAULT_CALL_TIMEOUT_MS,\n ERROR_TITLE_REQUEST_TIMED_OUT,\n HEADER_CONTENT_TYPE,\n HEADER_REQUEST_ID,\n OAUTH_GRANT_CLIENT_CREDENTIALS,\n} from \"./constants.js\";\nimport { budget, cancellable, validateTimeout, type Timeout } from \"./timeouts.js\";\nimport { describeNetworkError, PaxosAuthenticationError, PaxosNetworkError, PaxosTimeoutError } from \"./errors.js\";\n\nconst TOKEN_EXPIRY_BUFFER_MS = 60_000;\n\n/**\n * Sane upper bound on a token response's `expires_in` (seconds), applied\n * before computing an expiry timestamp. Without this, a malformed/malicious\n * value pins the cached token's validity arbitrarily far into the future,\n * and the SDK would never refresh it again.\n */\nconst MAX_EXPIRES_IN_SECONDS = 100 * 365 * 24 * 60 * 60; // ~100 years\n\nconst OAUTH_ERROR_CODES = new Set([\n \"invalid_request\",\n \"invalid_client\",\n \"invalid_grant\",\n \"unauthorized_client\",\n \"unsupported_grant_type\",\n \"invalid_scope\",\n \"server_error\",\n \"temporarily_unavailable\",\n]);\n\n/**\n * TokenManager handles automatic OAuth2 token acquisition and caching.\n *\n * Users of the SDK never need to call this directly — the PaxosClient\n * injects the Bearer token on every request.\n */\nexport class TokenManager {\n private readonly clientId: string;\n readonly #clientSecret: string;\n private readonly tokenUrl: string;\n private readonly scopes: readonly string[];\n private readonly timeoutMs: Timeout;\n private readonly fetchFn: typeof fetch;\n private refreshController: AbortController | null = null;\n #waiters = new Map<Promise<string>, number>();\n\n #cachedToken: string | null = null;\n private expiresAt = 0;\n\n // A single Promise for any in-flight token fetch. This prevents concurrent\n // callers from each making a separate token request.\n #refreshPromise: Promise<string> | null = null;\n\n // Bumped on every invalidate(). Guards against a refresh that was already\n // in flight when invalidate() ran: without this, it could resolve *after*\n // a newer refresh and silently overwrite the cache with its own result —\n // which, if the OAuth endpoint returns the same token for a rapid repeat\n // request, could even be the just-revoked token that triggered the\n // invalidate() in the first place.\n private refreshGeneration = 0;\n\n constructor(\n clientId: string,\n clientSecret: string,\n tokenUrl: string,\n scopes?: readonly string[],\n timeoutMs?: Timeout,\n fetchFn?: typeof fetch,\n ) {\n this.clientId = clientId;\n this.#clientSecret = clientSecret;\n this.tokenUrl = tokenUrl;\n this.scopes = scopes ?? [];\n this.fetchFn = fetchFn ?? ((input, init) => globalThis.fetch(input, init));\n validateTimeout(timeoutMs, \"token timeout\");\n this.timeoutMs = timeoutMs === undefined ? DEFAULT_CALL_TIMEOUT_MS : timeoutMs;\n }\n\n /**\n * Return a valid access token, fetching a new one if the cached token\n * has expired or is about to expire within the 60-second buffer.\n *\n * `timeoutMs`, if given, bounds the token request only if a refresh is\n * actually triggered — used internally by pagination to keep a\n * mid-iteration refresh inside the remaining `maxDuration` budget rather\n * than this manager's own default timeout.\n *\n * If a refresh is already in-flight from another caller, this call joins\n * it (concurrent refreshes share a single fetch) rather than starting a\n * duplicate one — but `timeoutMs`, if given, bounds *this* caller's own\n * wait for that shared refresh, not the original caller's timeout, so a\n * short remaining budget here can't be blocked past it by someone else's\n * slower refresh.\n */\n async getToken(timeoutMs?: Timeout, signal?: AbortSignal): Promise<string> {\n const now = Date.now();\n if (this.#cachedToken !== null && now < this.expiresAt) {\n return this.#cachedToken;\n }\n return this.refresh(timeoutMs, signal);\n }\n\n /**\n * Return the current cached token without triggering a refresh.\n */\n peekToken(): string | null {\n const now = Date.now();\n if (this.#cachedToken !== null && now < this.expiresAt) {\n return this.#cachedToken;\n }\n return null;\n }\n\n /**\n * Invalidate the cached token so the next call to getToken() forces a refresh.\n *\n * Called automatically on 401 responses to handle server-side token revocation.\n */\n invalidate(rejectedToken?: string): void {\n // A delayed 401 must preserve a newer token or an already-started refresh.\n if (rejectedToken !== undefined && this.#cachedToken !== rejectedToken) return;\n this.#cachedToken = null;\n this.expiresAt = 0;\n // Expiry refreshes retain the old cached token until they finish. A 401\n // for that old token should join the refresh, not detach it and fetch twice.\n if (rejectedToken !== undefined && this.#refreshPromise !== null) return;\n // Cancel the in-flight promise so a fresh fetch is started next time.\n this.#refreshPromise = null;\n this.refreshGeneration++;\n }\n\n /**\n * Fetch a fresh token from the OAuth2 endpoint.\n *\n * Multiple concurrent callers share a single in-flight fetch (singleflight pattern).\n */\n private async refresh(timeoutMs?: Timeout, signal?: AbortSignal): Promise<string> {\n validateTimeout(timeoutMs, \"token timeout\");\n signal?.throwIfAborted();\n const joining = this.#refreshPromise !== null;\n if (this.#refreshPromise === null) {\n const generation = this.refreshGeneration;\n const controller = new AbortController();\n this.refreshController = controller;\n const promise = this.fetchToken(controller.signal, generation).finally(() => {\n if (this.#refreshPromise === promise) this.#refreshPromise = null;\n });\n this.#refreshPromise = promise;\n }\n const promise = this.#refreshPromise;\n const controller = this.refreshController!;\n this.#waiters.set(promise, (this.#waiters.get(promise) ?? 0) + 1);\n const wait = budget(\n joining && signal ? null : timeoutMs === undefined ? this.timeoutMs : timeoutMs,\n signal,\n \"OAuth attempt\",\n );\n try {\n return await cancellable(promise, wait.signal);\n } finally {\n wait.cleanup();\n const remaining = (this.#waiters.get(promise) ?? 1) - 1;\n if (remaining) this.#waiters.set(promise, remaining);\n else {\n this.#waiters.delete(promise);\n controller.abort();\n if (this.#refreshPromise === promise) this.#refreshPromise = null;\n }\n }\n }\n\n private async fetchToken(signal: AbortSignal, generation: number): Promise<string> {\n const body = new URLSearchParams({\n grant_type: OAUTH_GRANT_CLIENT_CREDENTIALS,\n client_id: this.clientId,\n client_secret: this.#clientSecret,\n });\n if (this.scopes.length > 0) {\n body.set(\"scope\", this.scopes.join(\" \"));\n }\n\n let response: Response;\n try {\n response = await cancellable(\n this.fetchFn(this.tokenUrl, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: CONTENT_TYPE_FORM,\n },\n body: body.toString(),\n redirect: \"error\",\n // Bound the token request explicitly — without this, a stalled OAuth2\n // endpoint hangs forever, outside any timeout the caller configured\n // for API requests (which this fetch call is not one of).\n signal,\n }),\n signal,\n );\n } catch (err) {\n if (err instanceof Error && err.name === \"TimeoutError\") {\n throw new PaxosTimeoutError(\n { title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: `Token request failed: ${err}` },\n { cause: err },\n );\n }\n signal.throwIfAborted();\n throw new PaxosNetworkError(`Token request failed: ${describeNetworkError(err, this.tokenUrl)}`, { cause: err });\n }\n\n const readBody = async <T>(read: () => Promise<T>): Promise<T> => {\n try {\n return await cancellable(read(), signal);\n } catch (err) {\n if (signal.aborted) {\n throw new PaxosTimeoutError(\n { title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: `Token response timed out: ${err}` },\n { cause: err },\n );\n }\n throw new PaxosNetworkError(\"Failed to read token response body\", { cause: err });\n }\n };\n // Read under the same deadline, but do not expose raw OAuth response text or\n // JSON parser causes: those can contain credentials or issued tokens.\n const text = await readBody(() => response.text());\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n const data =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n const requestId =\n typeof data[\"request_id\"] === \"string\" && data[\"request_id\"]\n ? data[\"request_id\"]\n : response.headers?.get(HEADER_REQUEST_ID) || undefined;\n const code = typeof data[\"error\"] === \"string\" && OAUTH_ERROR_CODES.has(data[\"error\"]) ? data[\"error\"] : undefined;\n if (response.status !== 200) throw new PaxosAuthenticationError(response.status, requestId, code);\n const token = data[\"access_token\"];\n const rawExpiresIn = data[\"expires_in\"] === undefined ? 3600 : data[\"expires_in\"];\n const tokenType = data[\"token_type\"] === undefined ? AUTH_SCHEME_BEARER : data[\"token_type\"];\n if (\n typeof token !== \"string\" ||\n !token.trim() ||\n typeof tokenType !== \"string\" ||\n tokenType.toLowerCase() !== AUTH_SCHEME_BEARER.toLowerCase() ||\n typeof rawExpiresIn !== \"number\" ||\n !Number.isFinite(rawExpiresIn) ||\n !Number.isInteger(rawExpiresIn)\n ) {\n throw new PaxosAuthenticationError(response.status, requestId, code);\n }\n const expiresIn = Math.min(Math.max(rawExpiresIn, 0), MAX_EXPIRES_IN_SECONDS);\n const expiresInMs = expiresIn * 1000;\n // Apply expiry buffer so we refresh before the server considers it\n // expired. Clamped to half the token's lifetime (not just its full\n // lifetime) so a short-lived token still gets cached for a while instead\n // of being treated as already-expired the instant it's issued.\n const bufferMs = Math.min(TOKEN_EXPIRY_BUFFER_MS, expiresInMs / 2);\n // Only update the shared cache if no invalidate() has superseded this\n // fetch since it started. A fetch that started before an invalidate()\n // still resolves successfully with a validly-issued token — it's\n // returned to its own caller below regardless — but must not overwrite\n // state a newer, post-invalidate refresh has since set.\n if (generation === this.refreshGeneration) {\n this.#cachedToken = token;\n this.expiresAt = Date.now() + expiresInMs - bufferMs;\n }\n return token;\n }\n}\n"]}
@@ -0,0 +1,353 @@
1
+ /**
2
+ * HttpClient — Layer 1 HTTP transport for the Paxos TypeScript SDK.
3
+ *
4
+ * Handles OAuth2 authentication, HTTP transport, retry logic, pagination,
5
+ * and telemetry header injection. All API service classes delegate their
6
+ * HTTP calls to the methods on this class.
7
+ *
8
+ * Users should import PaxosClient from paxos-client.ts (which extends
9
+ * this class and adds all service accessors).
10
+ */
11
+ import { type Timeout } from "./timeouts.js";
12
+ import type { KnownScope } from "./enums.js";
13
+ /** Per-request configuration overrides. */
14
+ export interface RequestOptions {
15
+ /** Ordinary retry limit (default 3); zero disables retries. */
16
+ maxRetries?: number;
17
+ /** Total budget covering auth, retries, backoff and response body. Default 30000ms. */
18
+ callTimeout?: Timeout;
19
+ /** Limit for each HTTP attempt, including OAuth. Default: no separate cap. */
20
+ callAttemptTimeout?: Timeout;
21
+ /** Additional headers to send with this request. */
22
+ extraHeaders?: Record<string, string>;
23
+ /**
24
+ * An AbortSignal that can be used to cancel the request.
25
+ * When aborted, the request will reject with an AbortError.
26
+ * This signal is combined with the timeout signal — whichever
27
+ * fires first will cancel the request.
28
+ */
29
+ signal?: AbortSignal;
30
+ /**
31
+ * Maximum number of items an auto-paginating iterator (e.g.
32
+ * `listTransfers`) will yield before stopping, regardless of how many
33
+ * pages remain on the server. Only consulted by paginated methods;
34
+ * ignored by single-item requests.
35
+ */
36
+ maxItems?: number;
37
+ /**
38
+ * Maximum wall-clock time, in milliseconds, an auto-paginating iterator
39
+ * may spend across all of its page fetches. Throws {@link PaxosTimeoutError}
40
+ * if exceeded. Only consulted by paginated methods; ignored by
41
+ * single-item requests.
42
+ */
43
+ maxDuration?: Timeout;
44
+ /** Called once with the terminal API response, or once per pagination page.
45
+ * Not called for failures without a terminal HTTP response. Throwing (or
46
+ * rejecting) aborts unchanged without retry and takes precedence over API errors.
47
+ */
48
+ onResponseMetadata?: (metadata: ResponseMetadata) => void | Promise<void>;
49
+ }
50
+ /** Metadata from a terminal API response. */
51
+ export interface ResponseMetadata {
52
+ /** Response request ID, falling back to the actual outgoing Paxos-Request-Id. */
53
+ requestId: string | undefined;
54
+ /** HTTP status code. */
55
+ statusCode: number;
56
+ /** Unmodified body of the final response as text, kept even if decoding fails; "" for an empty body. */
57
+ rawBody: string;
58
+ }
59
+ /**
60
+ * A decoded top-level response object (a list item or a non-list call's result) with its
61
+ * original JSON available as `rawJson`.
62
+ *
63
+ * `rawJson` is a non-enumerable, lazily parsed property: the object's JSON value as sent in the
64
+ * response (decimal fields as strings, unknown fields kept, missing arrays and maps not filled
65
+ * in; whitespace and number formatting are not preserved). It is not carried by spread,
66
+ * `Object.assign` or `JSON.stringify`, so copy it explicitly if it must travel with a copy. It is
67
+ * `undefined` on objects the caller built and on nested objects. The generator rejects any schema
68
+ * property named `rawJson`; at runtime an unknown response field of that name is kept and
69
+ * `rawJson` is not attached.
70
+ *
71
+ * `rawJson` is a mutable cached object: writes persist on later reads of the same object, and items
72
+ * on one page share a single parse but each has its own subtree. It is deliberately not frozen so
73
+ * it can be edited before forwarding. Each item keeps its page body alive through its closure and,
74
+ * after the first read of any item's `rawJson`, the whole parsed page, so holding one item from a
75
+ * large page pins that page.
76
+ */
77
+ export type WithRaw<T> = T & {
78
+ readonly rawJson?: Record<string, unknown>;
79
+ };
80
+ /** One fetched page of a list endpoint. */
81
+ export interface Page<T> {
82
+ /** Items on this page, trimmed to `maxItems` on the final page when set. */
83
+ items: T[];
84
+ /**
85
+ * Cursor for the next page, or undefined when there is none. Pass it as `page_cursor` to resume.
86
+ * Undefined on a page trimmed by `maxItems`, since resuming from it would skip the trimmed
87
+ * items; a page ending exactly on the cap keeps its cursor. An empty page reports its
88
+ * cursor as received even though iteration stops; a page stopped by the repeated-cursor
89
+ * guard has none.
90
+ */
91
+ nextCursor: string | undefined;
92
+ /** This page's own response metadata, independent of every other page's. */
93
+ metadata: ResponseMetadata;
94
+ }
95
+ /**
96
+ * Result of an auto-paginating list call. It is an `AsyncGenerator` of items,
97
+ * so `for await (const item of ...)` works unchanged, and `pages()` exposes
98
+ * the same traversal one {@link Page} at a time.
99
+ *
100
+ * Pages are fetched lazily, only as the iteration advances. Item iteration and
101
+ * `pages()` are mutually exclusive: calling `pages()` once item iteration has
102
+ * started, or advancing items once `pages()` has been called, throws a
103
+ * `RangeError`. Calling `pages()` again after partial or full consumption is
104
+ * allowed and continues from the next unfetched page. An empty page is yielded
105
+ * by `pages()` once, with its own metadata and the cursor as received unless it repeats the cursor just sent, and then iteration stops. An error is
106
+ * terminal: after a fetch fails, no further pages are fetched and later pulls end,
107
+ * in either view and without the mixing error. An invalid `maxItems` or `maxDuration`
108
+ * fails the first pull once, after which both views are done with no requests made.
109
+ * `return()` and disposal stop further fetching.
110
+ */
111
+ export declare class PageIterator<T> implements AsyncGenerator<T, void, undefined> {
112
+ private readonly itemStream;
113
+ private readonly pageGen;
114
+ private mode;
115
+ private ended;
116
+ next(): Promise<IteratorResult<T, void>>;
117
+ return(value?: void): Promise<IteratorResult<T, void>>;
118
+ throw(err: unknown): Promise<IteratorResult<T, void>>;
119
+ [Symbol.asyncIterator](): this;
120
+ [Symbol.asyncDispose](): Promise<void>;
121
+ /** Iterate whole pages, each with its own `nextCursor` and `metadata`. */
122
+ pages(): AsyncGenerator<Page<T>>;
123
+ }
124
+ export interface HookRequest {
125
+ method: string;
126
+ url: string;
127
+ headers: Headers;
128
+ body: string | undefined;
129
+ }
130
+ export interface HookResponse {
131
+ status: number;
132
+ headers: Headers;
133
+ body: string;
134
+ }
135
+ /** Hook called before each API attempt and signing. May add headers or override Paxos-Request-Id; changing method, url, body or other SDK-owned headers fails the call. Throw to abort without retry. */
136
+ export type BeforeRequestHook = (req: HookRequest) => void | Promise<void>;
137
+ /** Hook called only when an API response exists, with the buffered body. Throw to abort without retry. */
138
+ export type AfterResponseHook = (req: HookRequest, res: HookResponse) => void | Promise<void>;
139
+ /** Configuration options for PaxosClient. */
140
+ export interface PaxosClientOptions {
141
+ /** OAuth2 client ID. */
142
+ clientId: string;
143
+ /** OAuth2 client secret. */
144
+ clientSecret: string;
145
+ /**
146
+ * Set to true to target the Paxos sandbox environment.
147
+ * Sandbox credentials differ from production credentials.
148
+ * Cannot be combined with `baseUrl` or `tokenUrl`.
149
+ */
150
+ sandbox?: boolean;
151
+ /**
152
+ * Override the base URL entirely. Useful for local development or testing.
153
+ * It must include the API version prefix (for example `https://api.paxos.com/v2`);
154
+ * one trailing slash is ignored. Must be set together with `tokenUrl`, or both left unset.
155
+ * Cannot be combined with `sandbox`.
156
+ */
157
+ baseUrl?: string;
158
+ /**
159
+ * OAuth2 scopes to request when fetching tokens. At least one is required;
160
+ * a token issued without scopes cannot call any endpoint.
161
+ */
162
+ scopes: readonly KnownScope[];
163
+ /** Ordinary retry limit (default 3); zero disables retries. */
164
+ maxRetries?: number;
165
+ /** Total budget covering auth, retries, backoff and response body. Default 30000ms. */
166
+ callTimeout?: Timeout;
167
+ /** Limit for each HTTP attempt, including OAuth. Default: no separate cap. */
168
+ callAttemptTimeout?: Timeout;
169
+ /**
170
+ * Custom fetch implementation used for both API and OAuth token requests.
171
+ * Defaults to the global `fetch`; it must honour `init.signal`. Use it to route through a proxy, custom TLS or an undici dispatcher.
172
+ */
173
+ fetch?: typeof fetch;
174
+ /** Hook invoked before each request, useful for logging or custom headers. */
175
+ beforeRequest?: BeforeRequestHook;
176
+ /** Hook invoked after each response, useful for logging or metrics. */
177
+ afterResponse?: AfterResponseHook;
178
+ /**
179
+ * Override the OAuth2 token endpoint URL. Useful for testing against a local token server.
180
+ * One trailing slash is ignored. Must be set together with `baseUrl`, or both left unset.
181
+ * Cannot be combined with `sandbox`.
182
+ */
183
+ tokenUrl?: string;
184
+ /**
185
+ * Ed25519 private key for JWS request signing, as 128 hex chars (32-byte seed
186
+ * followed by the 32-byte public key), or an unencrypted PKCS#8 or SEC1 PEM
187
+ * (Ed25519 or P-256). Request
188
+ * signing requires contacting Paxos support to enable on the OAuth client.
189
+ * Both `signingKey` and `keyId` must be provided together.
190
+ */
191
+ signingKey?: string;
192
+ /** UUID of the registered public key for request signing. */
193
+ keyId?: string;
194
+ /** Optional logger callback for debug output. */
195
+ logger?: (level: "debug" | "info" | "warn" | "error", message: string, data?: Record<string, unknown>) => void;
196
+ }
197
+ export interface OperationSchemas {
198
+ responseSchema?: string;
199
+ requestSchema?: string;
200
+ replayProtected?: boolean;
201
+ }
202
+ /**
203
+ * HttpClient is the Layer 1 HTTP transport.
204
+ *
205
+ * Use {@link PaxosClient} (from paxos-client.ts) instead of this class
206
+ * directly — it extends HttpClient and adds all service accessors.
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * const client = new PaxosClient({
211
+ * clientId: process.env.PAXOS_CLIENT_ID!,
212
+ * clientSecret: process.env.PAXOS_CLIENT_SECRET!,
213
+ * scopes: [Scope.TRANSFER_READ_TRANSFER],
214
+ * sandbox: true,
215
+ * });
216
+ *
217
+ * const transfer = await client.transfers.getTransfer("txn_123");
218
+ * ```
219
+ */
220
+ export declare class HttpClient {
221
+ #private;
222
+ readonly baseUrl: string;
223
+ readonly isSandbox: boolean;
224
+ private readonly requestFailures;
225
+ private readonly tokenFailures;
226
+ private readonly maxRetries;
227
+ private readonly callTimeout;
228
+ private readonly fetchFn;
229
+ private readonly attemptTimeout;
230
+ private readonly beforeRequestHook?;
231
+ private readonly afterResponseHook?;
232
+ private readonly signingKeyId?;
233
+ private readonly logger?;
234
+ constructor(options: PaxosClientOptions);
235
+ /**
236
+ * Perform a GET request and return the parsed response body.
237
+ * Query parameters are serialized from `params`, omitting undefined/null values.
238
+ * `op.responseSchema` names the response's schema in the spec, so decimal fields are
239
+ * converted for that schema only (see `decodeResponse`).
240
+ */
241
+ get<T>(path: string, params?: Record<string, unknown> | object, opts?: RequestOptions, op?: OperationSchemas): Promise<T>;
242
+ /**
243
+ * Perform a POST request with a JSON body and return the parsed response body.
244
+ */
245
+ post<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<T>;
246
+ /**
247
+ * Perform a PUT request with a JSON body and return the parsed response body.
248
+ */
249
+ put<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<T>;
250
+ /**
251
+ * Perform a PATCH request with a JSON body and return the parsed response body.
252
+ */
253
+ patch<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<T>;
254
+ /**
255
+ * Perform a DELETE request and return the parsed response body (if any).
256
+ * Query parameters are serialized from `params`, omitting undefined/null values.
257
+ */
258
+ delete<T = void>(path: string, params?: Record<string, unknown> | object, opts?: RequestOptions, op?: OperationSchemas): Promise<T>;
259
+ /**
260
+ * Perform a GET request and return both the parsed body and response metadata.
261
+ */
262
+ getWithMetadata<T>(path: string, params?: Record<string, unknown> | object, opts?: RequestOptions, op?: OperationSchemas): Promise<{
263
+ data: WithRaw<T>;
264
+ response: ResponseMetadata;
265
+ }>;
266
+ /**
267
+ * Perform a POST request and return both the parsed body and response metadata.
268
+ */
269
+ postWithMetadata<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<{
270
+ data: WithRaw<T>;
271
+ response: ResponseMetadata;
272
+ }>;
273
+ /**
274
+ * Perform a PUT request and return both the parsed body and response metadata.
275
+ */
276
+ putWithMetadata<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<{
277
+ data: WithRaw<T>;
278
+ response: ResponseMetadata;
279
+ }>;
280
+ /**
281
+ * Perform a PATCH request and return both the parsed body and response metadata.
282
+ */
283
+ patchWithMetadata<T>(path: string, body?: unknown, opts?: RequestOptions, op?: OperationSchemas): Promise<{
284
+ data: WithRaw<T>;
285
+ response: ResponseMetadata;
286
+ }>;
287
+ /**
288
+ * Perform a DELETE request and return both the parsed body and response metadata.
289
+ * Query parameters are serialized from `params`, omitting undefined/null values.
290
+ */
291
+ deleteWithMetadata<T = void>(path: string, params?: Record<string, unknown> | object, opts?: RequestOptions, op?: OperationSchemas): Promise<{
292
+ data: T;
293
+ response: ResponseMetadata;
294
+ }>;
295
+ /**
296
+ * Auto-paginating iterator over a list endpoint.
297
+ *
298
+ * Returns a {@link PageIterator}: iterate it directly to receive individual
299
+ * items, or call `pages()` to receive whole {@link Page}s. Subsequent pages
300
+ * are fetched lazily via the next_page_cursor field.
301
+ *
302
+ * @param path - The API endpoint path.
303
+ * @param itemsField - The JSON field name containing the items array (e.g. "payments").
304
+ * @param params - Optional query parameters.
305
+ * @param opts - Optional per-request configuration. `opts.maxItems` caps the
306
+ * total number of items yielded; `opts.maxDuration` bounds the total
307
+ * wall-clock time across all page fetches and throws {@link PaxosTimeoutError}
308
+ * if exceeded.
309
+ * @param op - `op.responseSchema` is the list response envelope's schema name
310
+ * in the spec, used to decimal-convert the page (and, via its nested-schema
311
+ * refs, the items within it) for that schema only.
312
+ *
313
+ * @example
314
+ * ```typescript
315
+ * for await (const payment of client.paginate<Payment>("/payment/payments", "payments", { profile_id: "p_123" })) {
316
+ * console.log(payment.id);
317
+ * }
318
+ * ```
319
+ *
320
+ * Termination is guaranteed even if the server misbehaves: iteration stops
321
+ * on an absent cursor, an empty page (even if a cursor was still returned),
322
+ * or a cursor identical to the one just requested.
323
+ */
324
+ paginate<T>(path: string, itemsField: string, params?: Record<string, unknown> | object, opts?: RequestOptions, op?: OperationSchemas): PageIterator<T>;
325
+ /** Fresh HTTP-attempt cap, clipped to the remaining call and pagination deadlines. */
326
+ private effectiveRequestTimeout;
327
+ /** Log a debug message if the logger is configured. */
328
+ private logDebug;
329
+ /**
330
+ * Core HTTP execution method used by all service classes.
331
+ *
332
+ * Handles:
333
+ * - Bearer token injection
334
+ * - Telemetry headers
335
+ * - 401 token refresh (single retry)
336
+ * - Exponential backoff on 429/5xx
337
+ * - RFC 7807 error parsing
338
+ */
339
+ private request;
340
+ private requestWithinBudget;
341
+ private markRequestFailure;
342
+ private executeRequest;
343
+ }
344
+ export declare function omitEmptyCollections(value: unknown, schemaKey?: string, mapFieldsBySchema?: Readonly<Record<string, ReadonlySet<string>>>, nestedSchemaRefs?: Readonly<Record<string, Readonly<Record<string, string>>>>): unknown;
345
+ /**
346
+ * Serialize query parameters to a URL-encoded string.
347
+ * Arrays are serialized as repeated parameters: key=a&key=b.
348
+ * undefined/null values are omitted.
349
+ */
350
+ /**
351
+ * Interpolate path parameters into a URL template with encoding.
352
+ */
353
+ export declare function buildPath(template: string, params: Record<string, string>): string;