@lukadriel/wave-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 (185) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +2 -0
  4. package/README.md +523 -2
  5. package/dist/client/wave-client-options.d.ts +29 -0
  6. package/dist/client/wave-client-options.d.ts.map +1 -0
  7. package/dist/client/wave-client-options.js +58 -0
  8. package/dist/client/wave-client-options.js.map +1 -0
  9. package/dist/client/wave-client.d.ts +47 -0
  10. package/dist/client/wave-client.d.ts.map +1 -0
  11. package/dist/client/wave-client.js +66 -0
  12. package/dist/client/wave-client.js.map +1 -0
  13. package/dist/core/auth/authentication.d.ts +8 -0
  14. package/dist/core/auth/authentication.d.ts.map +1 -0
  15. package/dist/core/auth/authentication.js +10 -0
  16. package/dist/core/auth/authentication.js.map +1 -0
  17. package/dist/core/auth/request-signer.d.ts +26 -0
  18. package/dist/core/auth/request-signer.d.ts.map +1 -0
  19. package/dist/core/auth/request-signer.js +39 -0
  20. package/dist/core/auth/request-signer.js.map +1 -0
  21. package/dist/core/errors/error-parser.d.ts +25 -0
  22. package/dist/core/errors/error-parser.d.ts.map +1 -0
  23. package/dist/core/errors/error-parser.js +198 -0
  24. package/dist/core/errors/error-parser.js.map +1 -0
  25. package/dist/core/errors/redact.d.ts +11 -0
  26. package/dist/core/errors/redact.d.ts.map +1 -0
  27. package/dist/core/errors/redact.js +20 -0
  28. package/dist/core/errors/redact.js.map +1 -0
  29. package/dist/core/errors/wave-api-error.d.ts +116 -0
  30. package/dist/core/errors/wave-api-error.d.ts.map +1 -0
  31. package/dist/core/errors/wave-api-error.js +114 -0
  32. package/dist/core/errors/wave-api-error.js.map +1 -0
  33. package/dist/core/errors/wave-error.d.ts +27 -0
  34. package/dist/core/errors/wave-error.d.ts.map +1 -0
  35. package/dist/core/errors/wave-error.js +22 -0
  36. package/dist/core/errors/wave-error.js.map +1 -0
  37. package/dist/core/errors/wave-network-error.d.ts +24 -0
  38. package/dist/core/errors/wave-network-error.d.ts.map +1 -0
  39. package/dist/core/errors/wave-network-error.js +24 -0
  40. package/dist/core/errors/wave-network-error.js.map +1 -0
  41. package/dist/core/errors/wave-webhook-verification-error.d.ts +18 -0
  42. package/dist/core/errors/wave-webhook-verification-error.d.ts.map +1 -0
  43. package/dist/core/errors/wave-webhook-verification-error.js +17 -0
  44. package/dist/core/errors/wave-webhook-verification-error.js.map +1 -0
  45. package/dist/core/http/fetch-transport.d.ts +23 -0
  46. package/dist/core/http/fetch-transport.d.ts.map +1 -0
  47. package/dist/core/http/fetch-transport.js +34 -0
  48. package/dist/core/http/fetch-transport.js.map +1 -0
  49. package/dist/core/http/http-client.d.ts +57 -0
  50. package/dist/core/http/http-client.d.ts.map +1 -0
  51. package/dist/core/http/http-client.js +254 -0
  52. package/dist/core/http/http-client.js.map +1 -0
  53. package/dist/core/http/http-request.d.ts +35 -0
  54. package/dist/core/http/http-request.d.ts.map +1 -0
  55. package/dist/core/http/http-request.js +2 -0
  56. package/dist/core/http/http-request.js.map +1 -0
  57. package/dist/core/http/http-response.d.ts +26 -0
  58. package/dist/core/http/http-response.d.ts.map +1 -0
  59. package/dist/core/http/http-response.js +23 -0
  60. package/dist/core/http/http-response.js.map +1 -0
  61. package/dist/core/http/query.d.ts +14 -0
  62. package/dist/core/http/query.d.ts.map +1 -0
  63. package/dist/core/http/query.js +23 -0
  64. package/dist/core/http/query.js.map +1 -0
  65. package/dist/core/http/transport.d.ts +44 -0
  66. package/dist/core/http/transport.d.ts.map +1 -0
  67. package/dist/core/http/transport.js +2 -0
  68. package/dist/core/http/transport.js.map +1 -0
  69. package/dist/core/idempotency/idempotency.d.ts +16 -0
  70. package/dist/core/idempotency/idempotency.d.ts.map +1 -0
  71. package/dist/core/idempotency/idempotency.js +27 -0
  72. package/dist/core/idempotency/idempotency.js.map +1 -0
  73. package/dist/core/retry/backoff.d.ts +18 -0
  74. package/dist/core/retry/backoff.d.ts.map +1 -0
  75. package/dist/core/retry/backoff.js +46 -0
  76. package/dist/core/retry/backoff.js.map +1 -0
  77. package/dist/core/retry/retry-policy.d.ts +43 -0
  78. package/dist/core/retry/retry-policy.d.ts.map +1 -0
  79. package/dist/core/retry/retry-policy.js +90 -0
  80. package/dist/core/retry/retry-policy.js.map +1 -0
  81. package/dist/core/types/common.d.ts +59 -0
  82. package/dist/core/types/common.d.ts.map +1 -0
  83. package/dist/core/types/common.js +2 -0
  84. package/dist/core/types/common.js.map +1 -0
  85. package/dist/core/types/configuration.d.ts +82 -0
  86. package/dist/core/types/configuration.d.ts.map +1 -0
  87. package/dist/core/types/configuration.js +2 -0
  88. package/dist/core/types/configuration.js.map +1 -0
  89. package/dist/core/types/json.d.ts +15 -0
  90. package/dist/core/types/json.d.ts.map +1 -0
  91. package/dist/core/types/json.js +2 -0
  92. package/dist/core/types/json.js.map +1 -0
  93. package/dist/index.d.ts +39 -0
  94. package/dist/index.d.ts.map +1 -0
  95. package/dist/index.js +24 -0
  96. package/dist/index.js.map +1 -0
  97. package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts +82 -0
  98. package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts.map +1 -0
  99. package/dist/resources/aggregated-merchants/aggregated-merchant-types.js +2 -0
  100. package/dist/resources/aggregated-merchants/aggregated-merchant-types.js.map +1 -0
  101. package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts +67 -0
  102. package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts.map +1 -0
  103. package/dist/resources/aggregated-merchants/aggregated-merchants.js +111 -0
  104. package/dist/resources/aggregated-merchants/aggregated-merchants.js.map +1 -0
  105. package/dist/resources/balance/balance-types.d.ts +18 -0
  106. package/dist/resources/balance/balance-types.d.ts.map +1 -0
  107. package/dist/resources/balance/balance-types.js +2 -0
  108. package/dist/resources/balance/balance-types.js.map +1 -0
  109. package/dist/resources/balance/balance.d.ts +20 -0
  110. package/dist/resources/balance/balance.d.ts.map +1 -0
  111. package/dist/resources/balance/balance.js +28 -0
  112. package/dist/resources/balance/balance.js.map +1 -0
  113. package/dist/resources/checkout/checkout-types.d.ts +96 -0
  114. package/dist/resources/checkout/checkout-types.d.ts.map +1 -0
  115. package/dist/resources/checkout/checkout-types.js +2 -0
  116. package/dist/resources/checkout/checkout-types.js.map +1 -0
  117. package/dist/resources/checkout/checkout.d.ts +66 -0
  118. package/dist/resources/checkout/checkout.d.ts.map +1 -0
  119. package/dist/resources/checkout/checkout.js +95 -0
  120. package/dist/resources/checkout/checkout.js.map +1 -0
  121. package/dist/resources/payout-batches/payout-batches.d.ts +31 -0
  122. package/dist/resources/payout-batches/payout-batches.d.ts.map +1 -0
  123. package/dist/resources/payout-batches/payout-batches.js +36 -0
  124. package/dist/resources/payout-batches/payout-batches.js.map +1 -0
  125. package/dist/resources/payouts/payout-types.d.ts +158 -0
  126. package/dist/resources/payouts/payout-types.d.ts.map +1 -0
  127. package/dist/resources/payouts/payout-types.js +2 -0
  128. package/dist/resources/payouts/payout-types.js.map +1 -0
  129. package/dist/resources/payouts/payouts.d.ts +63 -0
  130. package/dist/resources/payouts/payouts.d.ts.map +1 -0
  131. package/dist/resources/payouts/payouts.js +80 -0
  132. package/dist/resources/payouts/payouts.js.map +1 -0
  133. package/dist/resources/reconciliation/reconciliation-types.d.ts +86 -0
  134. package/dist/resources/reconciliation/reconciliation-types.d.ts.map +1 -0
  135. package/dist/resources/reconciliation/reconciliation-types.js +2 -0
  136. package/dist/resources/reconciliation/reconciliation-types.js.map +1 -0
  137. package/dist/resources/reconciliation/reconciliation.d.ts +41 -0
  138. package/dist/resources/reconciliation/reconciliation.d.ts.map +1 -0
  139. package/dist/resources/reconciliation/reconciliation.js +81 -0
  140. package/dist/resources/reconciliation/reconciliation.js.map +1 -0
  141. package/dist/resources/webhooks/webhook-types.d.ts +159 -0
  142. package/dist/resources/webhooks/webhook-types.d.ts.map +1 -0
  143. package/dist/resources/webhooks/webhook-types.js +36 -0
  144. package/dist/resources/webhooks/webhook-types.js.map +1 -0
  145. package/dist/resources/webhooks/webhook-verifier.d.ts +104 -0
  146. package/dist/resources/webhooks/webhook-verifier.d.ts.map +1 -0
  147. package/dist/resources/webhooks/webhook-verifier.js +188 -0
  148. package/dist/resources/webhooks/webhook-verifier.js.map +1 -0
  149. package/package.json +70 -4
  150. package/src/client/wave-client-options.ts +91 -0
  151. package/src/client/wave-client.ts +70 -0
  152. package/src/core/auth/authentication.ts +9 -0
  153. package/src/core/auth/request-signer.ts +42 -0
  154. package/src/core/errors/error-parser.ts +258 -0
  155. package/src/core/errors/redact.ts +20 -0
  156. package/src/core/errors/wave-api-error.ts +148 -0
  157. package/src/core/errors/wave-error.ts +32 -0
  158. package/src/core/errors/wave-network-error.ts +24 -0
  159. package/src/core/errors/wave-webhook-verification-error.ts +28 -0
  160. package/src/core/http/fetch-transport.ts +48 -0
  161. package/src/core/http/http-client.ts +352 -0
  162. package/src/core/http/http-request.ts +37 -0
  163. package/src/core/http/http-response.ts +37 -0
  164. package/src/core/http/query.ts +31 -0
  165. package/src/core/http/transport.ts +45 -0
  166. package/src/core/idempotency/idempotency.ts +31 -0
  167. package/src/core/retry/backoff.ts +61 -0
  168. package/src/core/retry/retry-policy.ts +106 -0
  169. package/src/core/types/common.ts +65 -0
  170. package/src/core/types/configuration.ts +85 -0
  171. package/src/core/types/json.ts +16 -0
  172. package/src/index.ts +146 -0
  173. package/src/resources/aggregated-merchants/aggregated-merchant-types.ts +87 -0
  174. package/src/resources/aggregated-merchants/aggregated-merchants.ts +171 -0
  175. package/src/resources/balance/balance-types.ts +19 -0
  176. package/src/resources/balance/balance.ts +39 -0
  177. package/src/resources/checkout/checkout-types.ts +102 -0
  178. package/src/resources/checkout/checkout.ts +144 -0
  179. package/src/resources/payout-batches/payout-batches.ts +58 -0
  180. package/src/resources/payouts/payout-types.ts +171 -0
  181. package/src/resources/payouts/payouts.ts +120 -0
  182. package/src/resources/reconciliation/reconciliation-types.ts +102 -0
  183. package/src/resources/reconciliation/reconciliation.ts +116 -0
  184. package/src/resources/webhooks/webhook-types.ts +222 -0
  185. package/src/resources/webhooks/webhook-verifier.ts +297 -0
@@ -0,0 +1,254 @@
1
+ import { buildAuthorizationHeader } from '../auth/authentication.js';
2
+ import { RequestSigner, SIGNATURE_HEADER } from '../auth/request-signer.js';
3
+ import { WaveError, WaveConfigurationError } from '../errors/wave-error.js';
4
+ import { WaveRateLimitError } from '../errors/wave-api-error.js';
5
+ import { parseApiError } from '../errors/error-parser.js';
6
+ import { WaveAbortError, WaveNetworkError, WaveTimeoutError, } from '../errors/wave-network-error.js';
7
+ import { assertValidIdempotencyKey, generateIdempotencyKey } from '../idempotency/idempotency.js';
8
+ import { computeBackoffDelay, delay } from '../retry/backoff.js';
9
+ import { isRetryableStatus, resolveRetryOptions } from '../retry/retry-policy.js';
10
+ import { hasEmptyBody, isJsonContentType } from './http-response.js';
11
+ import { buildQueryString } from './query.js';
12
+ /** Default Wave API base URL. */
13
+ export const DEFAULT_BASE_URL = 'https://api.wave.com';
14
+ /** Default request timeout in milliseconds. */
15
+ export const DEFAULT_TIMEOUT_MS = 30000;
16
+ const USER_AGENT = 'wave-sdk-typescript/0.1.0';
17
+ /**
18
+ * Shared request pipeline used by every API module.
19
+ *
20
+ * Responsibilities: URL and query construction, single body serialization, authentication, request
21
+ * signing, idempotency headers, timeouts, status validation, error mapping and safe retries.
22
+ */
23
+ export class HttpClient {
24
+ #config;
25
+ #signer;
26
+ #secrets;
27
+ /**
28
+ * @param config - Resolved client configuration.
29
+ */
30
+ constructor(config) {
31
+ this.#config = config;
32
+ this.#signer =
33
+ config.signingSecret === undefined ? undefined : new RequestSigner(config.signingSecret);
34
+ this.#secrets =
35
+ config.signingSecret === undefined ? [config.apiKey] : [config.apiKey, config.signingSecret];
36
+ }
37
+ /**
38
+ * Executes a request that returns a JSON response body.
39
+ *
40
+ * @typeParam T - Expected response type.
41
+ * @param operation - Retry-safety metadata.
42
+ * @param request - Request definition.
43
+ * @param options - Per-request overrides.
44
+ */
45
+ async request(operation, request, options = {}) {
46
+ const body = await this.#execute(operation, request, options);
47
+ if (body === undefined) {
48
+ throw new WaveError('Wave API returned an empty response body.', {
49
+ code: 'invalid-response-body',
50
+ });
51
+ }
52
+ return body;
53
+ }
54
+ /**
55
+ * Executes a request whose documented response has no body.
56
+ *
57
+ * @param operation - Retry-safety metadata.
58
+ * @param request - Request definition.
59
+ * @param options - Per-request overrides.
60
+ */
61
+ async requestVoid(operation, request, options = {}) {
62
+ await this.#execute(operation, request, options);
63
+ }
64
+ async #execute(operation, request, options) {
65
+ if (options.timeoutMs !== undefined &&
66
+ (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) {
67
+ throw new WaveConfigurationError('timeoutMs must be a positive finite number.');
68
+ }
69
+ const url = `${this.#config.baseUrl}${request.path}${buildQueryString(request.query)}`;
70
+ const serializedBody = request.body === undefined ? undefined : JSON.stringify(request.body);
71
+ const idempotencyKey = this.#resolveIdempotencyKey(operation, request.idempotencyKey, options.idempotencyKey);
72
+ const retry = operation.idempotent || options.retry !== undefined
73
+ ? resolveRetryOptions(this.#config.retry, options.retry)
74
+ : false;
75
+ const maxAttempts = retry === false ? 1 : retry.maxRetries + 1;
76
+ const timeoutMs = options.timeoutMs ?? this.#config.timeoutMs;
77
+ for (let attempt = 0;; attempt += 1) {
78
+ const attemptNumber = attempt + 1;
79
+ const attemptSignal = createAttemptSignal(options.signal, timeoutMs);
80
+ const startedAt = Date.now();
81
+ this.#log('debug', 'wave.request', {
82
+ method: request.method,
83
+ path: request.path,
84
+ attempt: attemptNumber,
85
+ });
86
+ let response;
87
+ try {
88
+ response = await this.#config.transport.send({
89
+ url,
90
+ method: request.method,
91
+ headers: this.#buildHeaders(serializedBody, idempotencyKey),
92
+ ...(serializedBody === undefined ? {} : { body: serializedBody }),
93
+ signal: attemptSignal.signal,
94
+ });
95
+ }
96
+ catch (error) {
97
+ attemptSignal.dispose();
98
+ if (attemptSignal.timedOut()) {
99
+ throw new WaveTimeoutError(`Wave API request timed out after ${timeoutMs} ms.`, {
100
+ cause: error,
101
+ });
102
+ }
103
+ if (options.signal?.aborted === true) {
104
+ throw new WaveAbortError('Wave API request was aborted by the caller.', { cause: error });
105
+ }
106
+ if (retry !== false && attempt < maxAttempts - 1) {
107
+ await this.#waitBeforeRetry(attempt, undefined, retry, options.signal, request);
108
+ continue;
109
+ }
110
+ throw new WaveNetworkError('Could not reach the Wave API.', { cause: error });
111
+ }
112
+ attemptSignal.dispose();
113
+ const durationMs = Date.now() - startedAt;
114
+ this.#log('debug', 'wave.response', {
115
+ method: request.method,
116
+ path: request.path,
117
+ status: response.status,
118
+ attempt: attemptNumber,
119
+ durationMs,
120
+ });
121
+ if (response.status >= 200 && response.status < 300) {
122
+ return parseSuccessBody(response);
123
+ }
124
+ const apiError = parseApiError({
125
+ statusCode: response.status,
126
+ bodyText: response.bodyText,
127
+ headers: response.headers,
128
+ secrets: this.#secrets,
129
+ });
130
+ if (retry !== false && isRetryableStatus(response.status) && attempt < maxAttempts - 1) {
131
+ await this.#waitBeforeRetry(attempt, apiError, retry, options.signal, request);
132
+ continue;
133
+ }
134
+ throw apiError;
135
+ }
136
+ }
137
+ #resolveIdempotencyKey(operation, requestKey, optionKey) {
138
+ const explicit = optionKey ?? requestKey;
139
+ if (explicit !== undefined) {
140
+ assertValidIdempotencyKey(explicit);
141
+ return explicit;
142
+ }
143
+ if (!operation.requiresIdempotencyKey) {
144
+ return undefined;
145
+ }
146
+ return generateIdempotencyKey();
147
+ }
148
+ #buildHeaders(serializedBody, idempotencyKey) {
149
+ const headers = {
150
+ Accept: 'application/json',
151
+ Authorization: buildAuthorizationHeader(this.#config.apiKey),
152
+ 'User-Agent': USER_AGENT,
153
+ };
154
+ if (serializedBody !== undefined) {
155
+ headers['Content-Type'] = 'application/json';
156
+ }
157
+ if (idempotencyKey !== undefined) {
158
+ headers['Idempotency-Key'] = idempotencyKey;
159
+ }
160
+ if (this.#signer !== undefined) {
161
+ headers[SIGNATURE_HEADER] = this.#signer.sign(serializedBody ?? '');
162
+ }
163
+ return headers;
164
+ }
165
+ async #waitBeforeRetry(attempt, error, retry, signal, request) {
166
+ const retryAfterSeconds = error instanceof WaveRateLimitError ? error.retryAfterSeconds : undefined;
167
+ const waitMs = retryAfterSeconds === undefined
168
+ ? computeBackoffDelay(attempt, retry)
169
+ : retryAfterSeconds * 1000;
170
+ this.#log('warn', 'wave.retry', {
171
+ method: request.method,
172
+ path: request.path,
173
+ attempt: attempt + 1,
174
+ status: error?.statusCode,
175
+ waitMs,
176
+ });
177
+ await delay(waitMs, signal);
178
+ }
179
+ #log(level, message, meta) {
180
+ const logger = this.#config.logger;
181
+ if (logger === undefined) {
182
+ return;
183
+ }
184
+ try {
185
+ if (level === 'debug') {
186
+ logger.debug?.(message, meta);
187
+ }
188
+ else {
189
+ logger.warn?.(message, meta);
190
+ }
191
+ }
192
+ catch {
193
+ // Diagnostics must never break an API request.
194
+ }
195
+ }
196
+ }
197
+ function parseSuccessBody(response) {
198
+ const httpResponse = {
199
+ status: response.status,
200
+ headers: response.headers,
201
+ bodyText: response.bodyText,
202
+ };
203
+ if (hasEmptyBody(httpResponse)) {
204
+ return undefined;
205
+ }
206
+ if (!isJsonContentType(response.headers)) {
207
+ throw new WaveError(`Wave API returned a non-JSON response with HTTP ${response.status}.`, {
208
+ code: 'invalid-response-body',
209
+ });
210
+ }
211
+ try {
212
+ return JSON.parse(response.bodyText);
213
+ }
214
+ catch (cause) {
215
+ throw new WaveError(`Wave API returned invalid JSON with HTTP ${response.status}.`, {
216
+ code: 'invalid-response-body',
217
+ cause,
218
+ });
219
+ }
220
+ }
221
+ function createAttemptSignal(caller, timeoutMs) {
222
+ const controller = new AbortController();
223
+ let timedOut = false;
224
+ const timer = setTimeout(() => {
225
+ timedOut = true;
226
+ controller.abort();
227
+ }, timeoutMs);
228
+ timer.unref();
229
+ const onAbort = () => {
230
+ controller.abort();
231
+ };
232
+ const abortIfCallerAlreadyAborted = () => {
233
+ if (caller?.aborted === true) {
234
+ controller.abort();
235
+ }
236
+ };
237
+ if (caller?.aborted === true) {
238
+ controller.abort();
239
+ }
240
+ else {
241
+ caller?.addEventListener('abort', onAbort, { once: true });
242
+ // Re-check to close the race between the check above and listener registration.
243
+ abortIfCallerAlreadyAborted();
244
+ }
245
+ return {
246
+ signal: controller.signal,
247
+ timedOut: () => timedOut,
248
+ dispose: () => {
249
+ clearTimeout(timer);
250
+ caller?.removeEventListener('abort', onAbort);
251
+ },
252
+ };
253
+ }
254
+ //# sourceMappingURL=http-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-client.js","sourceRoot":"","sources":["../../../src/core/http/http-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAGlF,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAErE,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAG9C,iCAAiC;AACjC,MAAM,CAAC,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAEvD,+CAA+C;AAC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G,EAAE;YACZ,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAChD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { buildAuthorizationHeader } from '../auth/authentication.js';\nimport { RequestSigner, SIGNATURE_HEADER } from '../auth/request-signer.js';\nimport { WaveError, WaveConfigurationError } from '../errors/wave-error.js';\nimport { WaveRateLimitError } from '../errors/wave-api-error.js';\nimport type { WaveApiError } from '../errors/wave-api-error.js';\nimport { parseApiError } from '../errors/error-parser.js';\nimport {\n WaveAbortError,\n WaveNetworkError,\n WaveTimeoutError,\n} from '../errors/wave-network-error.js';\nimport { assertValidIdempotencyKey, generateIdempotencyKey } from '../idempotency/idempotency.js';\nimport { computeBackoffDelay, delay } from '../retry/backoff.js';\nimport { isRetryableStatus, resolveRetryOptions } from '../retry/retry-policy.js';\nimport type { RequestOptions, RetryOptions, WaveLogger } from '../types/configuration.js';\nimport type { HttpRequest, OperationDefinition } from './http-request.js';\nimport { hasEmptyBody, isJsonContentType } from './http-response.js';\nimport type { HttpResponse } from './http-response.js';\nimport { buildQueryString } from './query.js';\nimport type { TransportResponse, WaveTransport } from './transport.js';\n\n/** Default Wave API base URL. */\nexport const DEFAULT_BASE_URL = 'https://api.wave.com';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 30000;\n\nconst USER_AGENT = 'wave-sdk-typescript/0.1.0';\n\n/**\n * Resolved HTTP client configuration.\n */\nexport interface HttpClientConfig {\n /** Normalized base URL without a trailing slash. */\n readonly baseUrl: string;\n /** Wave Business API key. */\n readonly apiKey: string;\n /** Optional signing secret. */\n readonly signingSecret: string | undefined;\n /** HTTP transport. */\n readonly transport: WaveTransport;\n /** Default request timeout in milliseconds. */\n readonly timeoutMs: number;\n /** Default retry policy, or `false` when disabled. */\n readonly retry: RetryOptions | false;\n /** Optional diagnostics logger. */\n readonly logger: WaveLogger | undefined;\n}\n\ninterface AttemptSignal {\n readonly signal: AbortSignal;\n readonly timedOut: () => boolean;\n readonly dispose: () => void;\n}\n\n/**\n * Shared request pipeline used by every API module.\n *\n * Responsibilities: URL and query construction, single body serialization, authentication, request\n * signing, idempotency headers, timeouts, status validation, error mapping and safe retries.\n */\nexport class HttpClient {\n readonly #config: HttpClientConfig;\n readonly #signer: RequestSigner | undefined;\n readonly #secrets: readonly string[];\n\n /**\n * @param config - Resolved client configuration.\n */\n constructor(config: HttpClientConfig) {\n this.#config = config;\n this.#signer =\n config.signingSecret === undefined ? undefined : new RequestSigner(config.signingSecret);\n this.#secrets =\n config.signingSecret === undefined ? [config.apiKey] : [config.apiKey, config.signingSecret];\n }\n\n /**\n * Executes a request that returns a JSON response body.\n *\n * @typeParam T - Expected response type.\n * @param operation - Retry-safety metadata.\n * @param request - Request definition.\n * @param options - Per-request overrides.\n */\n async request<T>(\n operation: OperationDefinition,\n request: HttpRequest,\n options: RequestOptions = {},\n ): Promise<T> {\n const body = await this.#execute(operation, request, options);\n if (body === undefined) {\n throw new WaveError('Wave API returned an empty response body.', {\n code: 'invalid-response-body',\n });\n }\n return body as T;\n }\n\n /**\n * Executes a request whose documented response has no body.\n *\n * @param operation - Retry-safety metadata.\n * @param request - Request definition.\n * @param options - Per-request overrides.\n */\n async requestVoid(\n operation: OperationDefinition,\n request: HttpRequest,\n options: RequestOptions = {},\n ): Promise<void> {\n await this.#execute(operation, request, options);\n }\n\n async #execute(\n operation: OperationDefinition,\n request: HttpRequest,\n options: RequestOptions,\n ): Promise<unknown> {\n if (\n options.timeoutMs !== undefined &&\n (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)\n ) {\n throw new WaveConfigurationError('timeoutMs must be a positive finite number.');\n }\n\n const url = `${this.#config.baseUrl}${request.path}${buildQueryString(request.query)}`;\n const serializedBody = request.body === undefined ? undefined : JSON.stringify(request.body);\n const idempotencyKey = this.#resolveIdempotencyKey(\n operation,\n request.idempotencyKey,\n options.idempotencyKey,\n );\n const retry =\n operation.idempotent || options.retry !== undefined\n ? resolveRetryOptions(this.#config.retry, options.retry)\n : false;\n const maxAttempts = retry === false ? 1 : retry.maxRetries + 1;\n const timeoutMs = options.timeoutMs ?? this.#config.timeoutMs;\n\n for (let attempt = 0; ; attempt += 1) {\n const attemptNumber = attempt + 1;\n const attemptSignal = createAttemptSignal(options.signal, timeoutMs);\n const startedAt = Date.now();\n\n this.#log('debug', 'wave.request', {\n method: request.method,\n path: request.path,\n attempt: attemptNumber,\n });\n\n let response: TransportResponse;\n try {\n response = await this.#config.transport.send({\n url,\n method: request.method,\n headers: this.#buildHeaders(serializedBody, idempotencyKey),\n ...(serializedBody === undefined ? {} : { body: serializedBody }),\n signal: attemptSignal.signal,\n });\n } catch (error) {\n attemptSignal.dispose();\n\n if (attemptSignal.timedOut()) {\n throw new WaveTimeoutError(`Wave API request timed out after ${timeoutMs} ms.`, {\n cause: error,\n });\n }\n if (options.signal?.aborted === true) {\n throw new WaveAbortError('Wave API request was aborted by the caller.', { cause: error });\n }\n if (retry !== false && attempt < maxAttempts - 1) {\n await this.#waitBeforeRetry(attempt, undefined, retry, options.signal, request);\n continue;\n }\n throw new WaveNetworkError('Could not reach the Wave API.', { cause: error });\n }\n\n attemptSignal.dispose();\n const durationMs = Date.now() - startedAt;\n this.#log('debug', 'wave.response', {\n method: request.method,\n path: request.path,\n status: response.status,\n attempt: attemptNumber,\n durationMs,\n });\n\n if (response.status >= 200 && response.status < 300) {\n return parseSuccessBody(response);\n }\n\n const apiError = parseApiError({\n statusCode: response.status,\n bodyText: response.bodyText,\n headers: response.headers,\n secrets: this.#secrets,\n });\n\n if (retry !== false && isRetryableStatus(response.status) && attempt < maxAttempts - 1) {\n await this.#waitBeforeRetry(attempt, apiError, retry, options.signal, request);\n continue;\n }\n\n throw apiError;\n }\n }\n\n #resolveIdempotencyKey(\n operation: OperationDefinition,\n requestKey: string | undefined,\n optionKey: string | undefined,\n ): string | undefined {\n const explicit = optionKey ?? requestKey;\n if (explicit !== undefined) {\n assertValidIdempotencyKey(explicit);\n return explicit;\n }\n if (!operation.requiresIdempotencyKey) {\n return undefined;\n }\n return generateIdempotencyKey();\n }\n\n #buildHeaders(\n serializedBody: string | undefined,\n idempotencyKey: string | undefined,\n ): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n Authorization: buildAuthorizationHeader(this.#config.apiKey),\n 'User-Agent': USER_AGENT,\n };\n\n if (serializedBody !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n if (idempotencyKey !== undefined) {\n headers['Idempotency-Key'] = idempotencyKey;\n }\n if (this.#signer !== undefined) {\n headers[SIGNATURE_HEADER] = this.#signer.sign(serializedBody ?? '');\n }\n\n return headers;\n }\n\n async #waitBeforeRetry(\n attempt: number,\n error: WaveApiError | undefined,\n retry: RetryOptions,\n signal: AbortSignal | undefined,\n request: HttpRequest,\n ): Promise<void> {\n const retryAfterSeconds =\n error instanceof WaveRateLimitError ? error.retryAfterSeconds : undefined;\n const waitMs =\n retryAfterSeconds === undefined\n ? computeBackoffDelay(attempt, retry)\n : retryAfterSeconds * 1000;\n\n this.#log('warn', 'wave.retry', {\n method: request.method,\n path: request.path,\n attempt: attempt + 1,\n status: error?.statusCode,\n waitMs,\n });\n\n await delay(waitMs, signal);\n }\n\n #log(level: 'debug' | 'warn', message: string, meta: Readonly<Record<string, unknown>>): void {\n const logger = this.#config.logger;\n if (logger === undefined) {\n return;\n }\n try {\n if (level === 'debug') {\n logger.debug?.(message, meta);\n } else {\n logger.warn?.(message, meta);\n }\n } catch {\n // Diagnostics must never break an API request.\n }\n }\n}\n\nfunction parseSuccessBody(response: TransportResponse): unknown {\n const httpResponse: HttpResponse = {\n status: response.status,\n headers: response.headers,\n bodyText: response.bodyText,\n };\n\n if (hasEmptyBody(httpResponse)) {\n return undefined;\n }\n if (!isJsonContentType(response.headers)) {\n throw new WaveError(`Wave API returned a non-JSON response with HTTP ${response.status}.`, {\n code: 'invalid-response-body',\n });\n }\n\n try {\n return JSON.parse(response.bodyText) as unknown;\n } catch (cause) {\n throw new WaveError(`Wave API returned invalid JSON with HTTP ${response.status}.`, {\n code: 'invalid-response-body',\n cause,\n });\n }\n}\n\nfunction createAttemptSignal(caller: AbortSignal | undefined, timeoutMs: number): AttemptSignal {\n const controller = new AbortController();\n let timedOut = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n timer.unref();\n\n const onAbort = (): void => {\n controller.abort();\n };\n\n const abortIfCallerAlreadyAborted = (): void => {\n if (caller?.aborted === true) {\n controller.abort();\n }\n };\n\n if (caller?.aborted === true) {\n controller.abort();\n } else {\n caller?.addEventListener('abort', onAbort, { once: true });\n // Re-check to close the race between the check above and listener registration.\n abortIfCallerAlreadyAborted();\n }\n\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n dispose: () => {\n clearTimeout(timer);\n caller?.removeEventListener('abort', onAbort);\n },\n };\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import type { QueryParameterValue } from './query.js';
2
+ /**
3
+ * HTTP methods used by the Wave Business APIs.
4
+ */
5
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
6
+ /**
7
+ * Retry-safety metadata for an API operation.
8
+ */
9
+ export interface OperationDefinition {
10
+ /**
11
+ * Whether the operation can be retried without risking an unintended side effect.
12
+ *
13
+ * Wave documents some mutating endpoints as idempotent; GET requests are always idempotent.
14
+ * Operations that create a new resource without a documented idempotency mechanism are not.
15
+ */
16
+ readonly idempotent: boolean;
17
+ /** Whether an `Idempotency-Key` header must be sent (documented for financial mutations). */
18
+ readonly requiresIdempotencyKey: boolean;
19
+ }
20
+ /**
21
+ * An endpoint-relative HTTP request.
22
+ */
23
+ export interface HttpRequest {
24
+ /** HTTP method. */
25
+ readonly method: HttpMethod;
26
+ /** Path relative to the configured base URL, starting with `/`. */
27
+ readonly path: string;
28
+ /** Query parameters; `undefined` and `null` values are omitted. */
29
+ readonly query?: Readonly<Record<string, QueryParameterValue>>;
30
+ /** JSON request body, serialized exactly once by the HTTP layer. */
31
+ readonly body?: unknown;
32
+ /** Caller-supplied idempotency key for this request. */
33
+ readonly idempotencyKey?: string;
34
+ }
35
+ //# sourceMappingURL=http-request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-request.d.ts","sourceRoot":"","sources":["../../../src/core/http/http-request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAE3D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;;OAKG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,6FAA6F;IAC7F,QAAQ,CAAC,sBAAsB,EAAE,OAAO,CAAC;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,mBAAmB;IACnB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,mEAAmE;IACnE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mEAAmE;IACnE,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;IAC/D,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,wDAAwD;IACxD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CAClC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=http-request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-request.js","sourceRoot":"","sources":["../../../src/core/http/http-request.ts"],"names":[],"mappings":"","sourcesContent":["import type { QueryParameterValue } from './query.js';\n\n/**\n * HTTP methods used by the Wave Business APIs.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/**\n * Retry-safety metadata for an API operation.\n */\nexport interface OperationDefinition {\n /**\n * Whether the operation can be retried without risking an unintended side effect.\n *\n * Wave documents some mutating endpoints as idempotent; GET requests are always idempotent.\n * Operations that create a new resource without a documented idempotency mechanism are not.\n */\n readonly idempotent: boolean;\n /** Whether an `Idempotency-Key` header must be sent (documented for financial mutations). */\n readonly requiresIdempotencyKey: boolean;\n}\n\n/**\n * An endpoint-relative HTTP request.\n */\nexport interface HttpRequest {\n /** HTTP method. */\n readonly method: HttpMethod;\n /** Path relative to the configured base URL, starting with `/`. */\n readonly path: string;\n /** Query parameters; `undefined` and `null` values are omitted. */\n readonly query?: Readonly<Record<string, QueryParameterValue>>;\n /** JSON request body, serialized exactly once by the HTTP layer. */\n readonly body?: unknown;\n /** Caller-supplied idempotency key for this request. */\n readonly idempotencyKey?: string;\n}\n"]}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A raw HTTP response returned by the transport.
3
+ */
4
+ export interface HttpResponse {
5
+ /** HTTP status code. */
6
+ readonly status: number;
7
+ /** Response headers with lowercase names. */
8
+ readonly headers: Readonly<Record<string, string>>;
9
+ /** Response body decoded as UTF-8 text. */
10
+ readonly bodyText: string;
11
+ }
12
+ /**
13
+ * Whether the response carries no payload.
14
+ *
15
+ * Wave documents empty responses for payout reversal, checkout refund/expire, transaction refund
16
+ * and aggregated merchant deletion.
17
+ */
18
+ export declare function hasEmptyBody(response: HttpResponse): boolean;
19
+ /**
20
+ * Whether the response body should be treated as JSON.
21
+ *
22
+ * A missing content type is accepted because some intermediaries strip it; an explicit non-JSON
23
+ * content type is not.
24
+ */
25
+ export declare function isJsonContentType(headers: Readonly<Record<string, string>>): boolean;
26
+ //# sourceMappingURL=http-response.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-response.d.ts","sourceRoot":"","sources":["../../../src/core/http/http-response.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,wBAAwB;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,6CAA6C;IAC7C,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,2CAA2C;IAC3C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAI5D;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,OAAO,CAMpF"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Whether the response carries no payload.
3
+ *
4
+ * Wave documents empty responses for payout reversal, checkout refund/expire, transaction refund
5
+ * and aggregated merchant deletion.
6
+ */
7
+ export function hasEmptyBody(response) {
8
+ return (response.status === 204 || response.status === 205 || response.bodyText.trim().length === 0);
9
+ }
10
+ /**
11
+ * Whether the response body should be treated as JSON.
12
+ *
13
+ * A missing content type is accepted because some intermediaries strip it; an explicit non-JSON
14
+ * content type is not.
15
+ */
16
+ export function isJsonContentType(headers) {
17
+ const contentType = headers['content-type'];
18
+ if (contentType === undefined) {
19
+ return true;
20
+ }
21
+ return contentType.toLowerCase().includes('application/json');
22
+ }
23
+ //# sourceMappingURL=http-response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-response.js","sourceRoot":"","sources":["../../../src/core/http/http-response.ts"],"names":[],"mappings":"AAYA;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,QAAsB;IACjD,OAAO,CACL,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,CAC5F,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAyC;IACzE,MAAM,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAC5C,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,WAAW,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * A raw HTTP response returned by the transport.\n */\nexport interface HttpResponse {\n /** HTTP status code. */\n readonly status: number;\n /** Response headers with lowercase names. */\n readonly headers: Readonly<Record<string, string>>;\n /** Response body decoded as UTF-8 text. */\n readonly bodyText: string;\n}\n\n/**\n * Whether the response carries no payload.\n *\n * Wave documents empty responses for payout reversal, checkout refund/expire, transaction refund\n * and aggregated merchant deletion.\n */\nexport function hasEmptyBody(response: HttpResponse): boolean {\n return (\n response.status === 204 || response.status === 205 || response.bodyText.trim().length === 0\n );\n}\n\n/**\n * Whether the response body should be treated as JSON.\n *\n * A missing content type is accepted because some intermediaries strip it; an explicit non-JSON\n * content type is not.\n */\nexport function isJsonContentType(headers: Readonly<Record<string, string>>): boolean {\n const contentType = headers['content-type'];\n if (contentType === undefined) {\n return true;\n }\n return contentType.toLowerCase().includes('application/json');\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A value accepted in a query string. `undefined` and `null` values are omitted.
3
+ */
4
+ export type QueryParameterValue = string | number | boolean | null | undefined;
5
+ /**
6
+ * Builds a query string from documented parameters.
7
+ *
8
+ * Values keep their API-defined representation; booleans are serialized as `true` / `false`.
9
+ *
10
+ * @param query - Parameters to serialize.
11
+ * @returns The query string including the leading `?`, or an empty string when no value is set.
12
+ */
13
+ export declare function buildQueryString(query: Readonly<Record<string, QueryParameterValue>> | undefined): string;
14
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/core/http/query.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;AAE/E;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,GAAG,SAAS,GAC/D,MAAM,CAeR"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Builds a query string from documented parameters.
3
+ *
4
+ * Values keep their API-defined representation; booleans are serialized as `true` / `false`.
5
+ *
6
+ * @param query - Parameters to serialize.
7
+ * @returns The query string including the leading `?`, or an empty string when no value is set.
8
+ */
9
+ export function buildQueryString(query) {
10
+ if (query === undefined) {
11
+ return '';
12
+ }
13
+ const params = new URLSearchParams();
14
+ for (const [key, value] of Object.entries(query)) {
15
+ if (value === undefined || value === null) {
16
+ continue;
17
+ }
18
+ params.append(key, String(value));
19
+ }
20
+ const serialized = params.toString();
21
+ return serialized.length > 0 ? `?${serialized}` : '';
22
+ }
23
+ //# sourceMappingURL=query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.js","sourceRoot":"","sources":["../../../src/core/http/query.ts"],"names":[],"mappings":"AAKA;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAC9B,KAAgE;IAEhE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IACrC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YAC1C,SAAS;QACX,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IACrC,OAAO,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACvD,CAAC","sourcesContent":["/**\n * A value accepted in a query string. `undefined` and `null` values are omitted.\n */\nexport type QueryParameterValue = string | number | boolean | null | undefined;\n\n/**\n * Builds a query string from documented parameters.\n *\n * Values keep their API-defined representation; booleans are serialized as `true` / `false`.\n *\n * @param query - Parameters to serialize.\n * @returns The query string including the leading `?`, or an empty string when no value is set.\n */\nexport function buildQueryString(\n query: Readonly<Record<string, QueryParameterValue>> | undefined,\n): string {\n if (query === undefined) {\n return '';\n }\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n params.append(key, String(value));\n }\n\n const serialized = params.toString();\n return serialized.length > 0 ? `?${serialized}` : '';\n}\n"]}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A fully prepared transport request.
3
+ *
4
+ * The body is the exact serialized string that was signed, so custom transports must transmit it
5
+ * without re-serializing.
6
+ */
7
+ export interface TransportRequest {
8
+ /** Absolute request URL, including any query string. */
9
+ readonly url: string;
10
+ /** HTTP method, for example `GET` or `POST`. */
11
+ readonly method: string;
12
+ /** Request headers, including authentication, idempotency and signature headers. */
13
+ readonly headers: Readonly<Record<string, string>>;
14
+ /** Exact serialized request body, omitted for bodyless requests. */
15
+ readonly body?: string;
16
+ /** Signal that aborts when the caller cancels or the request times out. */
17
+ readonly signal: AbortSignal;
18
+ }
19
+ /**
20
+ * A raw transport response.
21
+ */
22
+ export interface TransportResponse {
23
+ /** HTTP status code. */
24
+ readonly status: number;
25
+ /** Response headers with lowercase names. */
26
+ readonly headers: Readonly<Record<string, string>>;
27
+ /** Response body decoded as UTF-8 text. */
28
+ readonly bodyText: string;
29
+ }
30
+ /**
31
+ * Pluggable HTTP transport used by the SDK.
32
+ *
33
+ * The default implementation uses the global `fetch` API. Implement this interface to integrate a
34
+ * custom HTTP stack; the SDK still applies authentication, signing, idempotency and retries.
35
+ */
36
+ export interface WaveTransport {
37
+ /**
38
+ * Sends a prepared request and resolves with the raw response.
39
+ *
40
+ * Implementations must reject on network failures and must honour the provided abort signal.
41
+ */
42
+ send(request: TransportRequest): Promise<TransportResponse>;
43
+ }
44
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/core/http/transport.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oFAAoF;IACpF,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,wBAAwB;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,6CAA6C;IAC7C,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,2CAA2C;IAC3C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CAC7D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/core/http/transport.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * A fully prepared transport request.\n *\n * The body is the exact serialized string that was signed, so custom transports must transmit it\n * without re-serializing.\n */\nexport interface TransportRequest {\n /** Absolute request URL, including any query string. */\n readonly url: string;\n /** HTTP method, for example `GET` or `POST`. */\n readonly method: string;\n /** Request headers, including authentication, idempotency and signature headers. */\n readonly headers: Readonly<Record<string, string>>;\n /** Exact serialized request body, omitted for bodyless requests. */\n readonly body?: string;\n /** Signal that aborts when the caller cancels or the request times out. */\n readonly signal: AbortSignal;\n}\n\n/**\n * A raw transport response.\n */\nexport interface TransportResponse {\n /** HTTP status code. */\n readonly status: number;\n /** Response headers with lowercase names. */\n readonly headers: Readonly<Record<string, string>>;\n /** Response body decoded as UTF-8 text. */\n readonly bodyText: string;\n}\n\n/**\n * Pluggable HTTP transport used by the SDK.\n *\n * The default implementation uses the global `fetch` API. Implement this interface to integrate a\n * custom HTTP stack; the SDK still applies authentication, signing, idempotency and retries.\n */\nexport interface WaveTransport {\n /**\n * Sends a prepared request and resolves with the raw response.\n *\n * Implementations must reject on network failures and must honour the provided abort signal.\n */\n send(request: TransportRequest): Promise<TransportResponse>;\n}\n"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Maximum idempotency key length documented by Wave.
3
+ */
4
+ export declare const MAX_IDEMPOTENCY_KEY_LENGTH = 255;
5
+ /**
6
+ * Generates a random v4 UUID suitable as an idempotency key.
7
+ */
8
+ export declare function generateIdempotencyKey(): string;
9
+ /**
10
+ * Validates a caller-supplied idempotency key before any request is sent.
11
+ *
12
+ * @param key - Candidate key.
13
+ * @throws WaveConfigurationError when the key is empty or longer than 255 characters.
14
+ */
15
+ export declare function assertValidIdempotencyKey(key: string): void;
16
+ //# sourceMappingURL=idempotency.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.d.ts","sourceRoot":"","sources":["../../../src/core/idempotency/idempotency.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAE9C;;GAEG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAE/C;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAS3D"}
@@ -0,0 +1,27 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { WaveConfigurationError } from '../errors/wave-error.js';
3
+ /**
4
+ * Maximum idempotency key length documented by Wave.
5
+ */
6
+ export const MAX_IDEMPOTENCY_KEY_LENGTH = 255;
7
+ /**
8
+ * Generates a random v4 UUID suitable as an idempotency key.
9
+ */
10
+ export function generateIdempotencyKey() {
11
+ return randomUUID();
12
+ }
13
+ /**
14
+ * Validates a caller-supplied idempotency key before any request is sent.
15
+ *
16
+ * @param key - Candidate key.
17
+ * @throws WaveConfigurationError when the key is empty or longer than 255 characters.
18
+ */
19
+ export function assertValidIdempotencyKey(key) {
20
+ if (key.length === 0) {
21
+ throw new WaveConfigurationError('Idempotency key must be a non-empty string.');
22
+ }
23
+ if (key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
24
+ throw new WaveConfigurationError(`Idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters long.`);
25
+ }
26
+ }
27
+ //# sourceMappingURL=idempotency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.js","sourceRoot":"","sources":["../../../src/core/idempotency/idempotency.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAEjE;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAE9C;;GAEG;AACH,MAAM,UAAU,sBAAsB;IACpC,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,GAAW;IACnD,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrB,MAAM,IAAI,sBAAsB,CAAC,6CAA6C,CAAC,CAAC;IAClF,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,GAAG,0BAA0B,EAAE,CAAC;QAC5C,MAAM,IAAI,sBAAsB,CAC9B,mCAAmC,0BAA0B,mBAAmB,CACjF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { WaveConfigurationError } from '../errors/wave-error.js';\n\n/**\n * Maximum idempotency key length documented by Wave.\n */\nexport const MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n\n/**\n * Generates a random v4 UUID suitable as an idempotency key.\n */\nexport function generateIdempotencyKey(): string {\n return randomUUID();\n}\n\n/**\n * Validates a caller-supplied idempotency key before any request is sent.\n *\n * @param key - Candidate key.\n * @throws WaveConfigurationError when the key is empty or longer than 255 characters.\n */\nexport function assertValidIdempotencyKey(key: string): void {\n if (key.length === 0) {\n throw new WaveConfigurationError('Idempotency key must be a non-empty string.');\n }\n if (key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new WaveConfigurationError(\n `Idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters long.`,\n );\n }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { RetryOptions } from '../types/configuration.js';
2
+ /**
3
+ * Computes the delay before a retry using exponential backoff with optional full jitter.
4
+ *
5
+ * @param attempt - Zero-based retry index (0 for the first retry).
6
+ * @param options - Retry configuration.
7
+ * @param random - Random source in `[0, 1)`; injectable for deterministic tests.
8
+ * @returns Delay in milliseconds, never above `maxDelayMs`.
9
+ */
10
+ export declare function computeBackoffDelay(attempt: number, options: RetryOptions, random?: () => number): number;
11
+ /**
12
+ * Waits for a delay, rejecting immediately if the caller aborts.
13
+ *
14
+ * @param delayMs - Time to wait in milliseconds.
15
+ * @param signal - Caller abort signal.
16
+ */
17
+ export declare function delay(delayMs: number, signal: AbortSignal | undefined): Promise<void>;
18
+ //# sourceMappingURL=backoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.d.ts","sourceRoot":"","sources":["../../../src/core/retry/backoff.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAE9D;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,YAAY,EACrB,MAAM,GAAE,MAAM,MAAoB,GACjC,MAAM,CAIR;AAED;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAiCrF"}
@@ -0,0 +1,46 @@
1
+ import { WaveAbortError } from '../errors/wave-network-error.js';
2
+ /**
3
+ * Computes the delay before a retry using exponential backoff with optional full jitter.
4
+ *
5
+ * @param attempt - Zero-based retry index (0 for the first retry).
6
+ * @param options - Retry configuration.
7
+ * @param random - Random source in `[0, 1)`; injectable for deterministic tests.
8
+ * @returns Delay in milliseconds, never above `maxDelayMs`.
9
+ */
10
+ export function computeBackoffDelay(attempt, options, random = Math.random) {
11
+ const exponential = options.baseDelayMs * 2 ** Math.max(0, attempt);
12
+ const capped = Math.min(options.maxDelayMs, exponential);
13
+ return Math.round(options.jitter ? random() * capped : capped);
14
+ }
15
+ /**
16
+ * Waits for a delay, rejecting immediately if the caller aborts.
17
+ *
18
+ * @param delayMs - Time to wait in milliseconds.
19
+ * @param signal - Caller abort signal.
20
+ */
21
+ export function delay(delayMs, signal) {
22
+ if (signal?.aborted === true) {
23
+ return Promise.reject(new WaveAbortError('Wave API request was aborted by the caller.', { cause: signal.reason }));
24
+ }
25
+ if (delayMs <= 0) {
26
+ return Promise.resolve();
27
+ }
28
+ return new Promise((resolve, reject) => {
29
+ const cleanup = () => {
30
+ clearTimeout(timer);
31
+ signal?.removeEventListener('abort', onAbort);
32
+ };
33
+ const onAbort = () => {
34
+ cleanup();
35
+ reject(new WaveAbortError('Wave API request was aborted by the caller.', {
36
+ cause: signal?.reason,
37
+ }));
38
+ };
39
+ const timer = setTimeout(() => {
40
+ cleanup();
41
+ resolve();
42
+ }, delayMs);
43
+ signal?.addEventListener('abort', onAbort, { once: true });
44
+ });
45
+ }
46
+ //# sourceMappingURL=backoff.js.map