@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.
- package/CHANGELOG.md +30 -0
- package/LICENSE +201 -0
- package/NOTICE +2 -0
- package/README.md +523 -2
- package/dist/client/wave-client-options.d.ts +29 -0
- package/dist/client/wave-client-options.d.ts.map +1 -0
- package/dist/client/wave-client-options.js +58 -0
- package/dist/client/wave-client-options.js.map +1 -0
- package/dist/client/wave-client.d.ts +47 -0
- package/dist/client/wave-client.d.ts.map +1 -0
- package/dist/client/wave-client.js +66 -0
- package/dist/client/wave-client.js.map +1 -0
- package/dist/core/auth/authentication.d.ts +8 -0
- package/dist/core/auth/authentication.d.ts.map +1 -0
- package/dist/core/auth/authentication.js +10 -0
- package/dist/core/auth/authentication.js.map +1 -0
- package/dist/core/auth/request-signer.d.ts +26 -0
- package/dist/core/auth/request-signer.d.ts.map +1 -0
- package/dist/core/auth/request-signer.js +39 -0
- package/dist/core/auth/request-signer.js.map +1 -0
- package/dist/core/errors/error-parser.d.ts +25 -0
- package/dist/core/errors/error-parser.d.ts.map +1 -0
- package/dist/core/errors/error-parser.js +198 -0
- package/dist/core/errors/error-parser.js.map +1 -0
- package/dist/core/errors/redact.d.ts +11 -0
- package/dist/core/errors/redact.d.ts.map +1 -0
- package/dist/core/errors/redact.js +20 -0
- package/dist/core/errors/redact.js.map +1 -0
- package/dist/core/errors/wave-api-error.d.ts +116 -0
- package/dist/core/errors/wave-api-error.d.ts.map +1 -0
- package/dist/core/errors/wave-api-error.js +114 -0
- package/dist/core/errors/wave-api-error.js.map +1 -0
- package/dist/core/errors/wave-error.d.ts +27 -0
- package/dist/core/errors/wave-error.d.ts.map +1 -0
- package/dist/core/errors/wave-error.js +22 -0
- package/dist/core/errors/wave-error.js.map +1 -0
- package/dist/core/errors/wave-network-error.d.ts +24 -0
- package/dist/core/errors/wave-network-error.d.ts.map +1 -0
- package/dist/core/errors/wave-network-error.js +24 -0
- package/dist/core/errors/wave-network-error.js.map +1 -0
- package/dist/core/errors/wave-webhook-verification-error.d.ts +18 -0
- package/dist/core/errors/wave-webhook-verification-error.d.ts.map +1 -0
- package/dist/core/errors/wave-webhook-verification-error.js +17 -0
- package/dist/core/errors/wave-webhook-verification-error.js.map +1 -0
- package/dist/core/http/fetch-transport.d.ts +23 -0
- package/dist/core/http/fetch-transport.d.ts.map +1 -0
- package/dist/core/http/fetch-transport.js +34 -0
- package/dist/core/http/fetch-transport.js.map +1 -0
- package/dist/core/http/http-client.d.ts +57 -0
- package/dist/core/http/http-client.d.ts.map +1 -0
- package/dist/core/http/http-client.js +254 -0
- package/dist/core/http/http-client.js.map +1 -0
- package/dist/core/http/http-request.d.ts +35 -0
- package/dist/core/http/http-request.d.ts.map +1 -0
- package/dist/core/http/http-request.js +2 -0
- package/dist/core/http/http-request.js.map +1 -0
- package/dist/core/http/http-response.d.ts +26 -0
- package/dist/core/http/http-response.d.ts.map +1 -0
- package/dist/core/http/http-response.js +23 -0
- package/dist/core/http/http-response.js.map +1 -0
- package/dist/core/http/query.d.ts +14 -0
- package/dist/core/http/query.d.ts.map +1 -0
- package/dist/core/http/query.js +23 -0
- package/dist/core/http/query.js.map +1 -0
- package/dist/core/http/transport.d.ts +44 -0
- package/dist/core/http/transport.d.ts.map +1 -0
- package/dist/core/http/transport.js +2 -0
- package/dist/core/http/transport.js.map +1 -0
- package/dist/core/idempotency/idempotency.d.ts +16 -0
- package/dist/core/idempotency/idempotency.d.ts.map +1 -0
- package/dist/core/idempotency/idempotency.js +27 -0
- package/dist/core/idempotency/idempotency.js.map +1 -0
- package/dist/core/retry/backoff.d.ts +18 -0
- package/dist/core/retry/backoff.d.ts.map +1 -0
- package/dist/core/retry/backoff.js +46 -0
- package/dist/core/retry/backoff.js.map +1 -0
- package/dist/core/retry/retry-policy.d.ts +43 -0
- package/dist/core/retry/retry-policy.d.ts.map +1 -0
- package/dist/core/retry/retry-policy.js +90 -0
- package/dist/core/retry/retry-policy.js.map +1 -0
- package/dist/core/types/common.d.ts +59 -0
- package/dist/core/types/common.d.ts.map +1 -0
- package/dist/core/types/common.js +2 -0
- package/dist/core/types/common.js.map +1 -0
- package/dist/core/types/configuration.d.ts +82 -0
- package/dist/core/types/configuration.d.ts.map +1 -0
- package/dist/core/types/configuration.js +2 -0
- package/dist/core/types/configuration.js.map +1 -0
- package/dist/core/types/json.d.ts +15 -0
- package/dist/core/types/json.d.ts.map +1 -0
- package/dist/core/types/json.js +2 -0
- package/dist/core/types/json.js.map +1 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts +82 -0
- package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts.map +1 -0
- package/dist/resources/aggregated-merchants/aggregated-merchant-types.js +2 -0
- package/dist/resources/aggregated-merchants/aggregated-merchant-types.js.map +1 -0
- package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts +67 -0
- package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts.map +1 -0
- package/dist/resources/aggregated-merchants/aggregated-merchants.js +111 -0
- package/dist/resources/aggregated-merchants/aggregated-merchants.js.map +1 -0
- package/dist/resources/balance/balance-types.d.ts +18 -0
- package/dist/resources/balance/balance-types.d.ts.map +1 -0
- package/dist/resources/balance/balance-types.js +2 -0
- package/dist/resources/balance/balance-types.js.map +1 -0
- package/dist/resources/balance/balance.d.ts +20 -0
- package/dist/resources/balance/balance.d.ts.map +1 -0
- package/dist/resources/balance/balance.js +28 -0
- package/dist/resources/balance/balance.js.map +1 -0
- package/dist/resources/checkout/checkout-types.d.ts +96 -0
- package/dist/resources/checkout/checkout-types.d.ts.map +1 -0
- package/dist/resources/checkout/checkout-types.js +2 -0
- package/dist/resources/checkout/checkout-types.js.map +1 -0
- package/dist/resources/checkout/checkout.d.ts +66 -0
- package/dist/resources/checkout/checkout.d.ts.map +1 -0
- package/dist/resources/checkout/checkout.js +95 -0
- package/dist/resources/checkout/checkout.js.map +1 -0
- package/dist/resources/payout-batches/payout-batches.d.ts +31 -0
- package/dist/resources/payout-batches/payout-batches.d.ts.map +1 -0
- package/dist/resources/payout-batches/payout-batches.js +36 -0
- package/dist/resources/payout-batches/payout-batches.js.map +1 -0
- package/dist/resources/payouts/payout-types.d.ts +158 -0
- package/dist/resources/payouts/payout-types.d.ts.map +1 -0
- package/dist/resources/payouts/payout-types.js +2 -0
- package/dist/resources/payouts/payout-types.js.map +1 -0
- package/dist/resources/payouts/payouts.d.ts +63 -0
- package/dist/resources/payouts/payouts.d.ts.map +1 -0
- package/dist/resources/payouts/payouts.js +80 -0
- package/dist/resources/payouts/payouts.js.map +1 -0
- package/dist/resources/reconciliation/reconciliation-types.d.ts +86 -0
- package/dist/resources/reconciliation/reconciliation-types.d.ts.map +1 -0
- package/dist/resources/reconciliation/reconciliation-types.js +2 -0
- package/dist/resources/reconciliation/reconciliation-types.js.map +1 -0
- package/dist/resources/reconciliation/reconciliation.d.ts +41 -0
- package/dist/resources/reconciliation/reconciliation.d.ts.map +1 -0
- package/dist/resources/reconciliation/reconciliation.js +81 -0
- package/dist/resources/reconciliation/reconciliation.js.map +1 -0
- package/dist/resources/webhooks/webhook-types.d.ts +159 -0
- package/dist/resources/webhooks/webhook-types.d.ts.map +1 -0
- package/dist/resources/webhooks/webhook-types.js +36 -0
- package/dist/resources/webhooks/webhook-types.js.map +1 -0
- package/dist/resources/webhooks/webhook-verifier.d.ts +104 -0
- package/dist/resources/webhooks/webhook-verifier.d.ts.map +1 -0
- package/dist/resources/webhooks/webhook-verifier.js +188 -0
- package/dist/resources/webhooks/webhook-verifier.js.map +1 -0
- package/package.json +70 -4
- package/src/client/wave-client-options.ts +91 -0
- package/src/client/wave-client.ts +70 -0
- package/src/core/auth/authentication.ts +9 -0
- package/src/core/auth/request-signer.ts +42 -0
- package/src/core/errors/error-parser.ts +258 -0
- package/src/core/errors/redact.ts +20 -0
- package/src/core/errors/wave-api-error.ts +148 -0
- package/src/core/errors/wave-error.ts +32 -0
- package/src/core/errors/wave-network-error.ts +24 -0
- package/src/core/errors/wave-webhook-verification-error.ts +28 -0
- package/src/core/http/fetch-transport.ts +48 -0
- package/src/core/http/http-client.ts +352 -0
- package/src/core/http/http-request.ts +37 -0
- package/src/core/http/http-response.ts +37 -0
- package/src/core/http/query.ts +31 -0
- package/src/core/http/transport.ts +45 -0
- package/src/core/idempotency/idempotency.ts +31 -0
- package/src/core/retry/backoff.ts +61 -0
- package/src/core/retry/retry-policy.ts +106 -0
- package/src/core/types/common.ts +65 -0
- package/src/core/types/configuration.ts +85 -0
- package/src/core/types/json.ts +16 -0
- package/src/index.ts +146 -0
- package/src/resources/aggregated-merchants/aggregated-merchant-types.ts +87 -0
- package/src/resources/aggregated-merchants/aggregated-merchants.ts +171 -0
- package/src/resources/balance/balance-types.ts +19 -0
- package/src/resources/balance/balance.ts +39 -0
- package/src/resources/checkout/checkout-types.ts +102 -0
- package/src/resources/checkout/checkout.ts +144 -0
- package/src/resources/payout-batches/payout-batches.ts +58 -0
- package/src/resources/payouts/payout-types.ts +171 -0
- package/src/resources/payouts/payouts.ts +120 -0
- package/src/resources/reconciliation/reconciliation-types.ts +102 -0
- package/src/resources/reconciliation/reconciliation.ts +116 -0
- package/src/resources/webhooks/webhook-types.ts +222 -0
- package/src/resources/webhooks/webhook-verifier.ts +297 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { WaveError } from './wave-error.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Reason a webhook request failed verification.
|
|
5
|
+
*/
|
|
6
|
+
export type WebhookVerificationFailureReason =
|
|
7
|
+
| 'missing-header'
|
|
8
|
+
| 'invalid-format'
|
|
9
|
+
| 'invalid-payload'
|
|
10
|
+
| 'no-matching-signature'
|
|
11
|
+
| 'timestamp-too-old';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Error raised when an incoming webhook cannot be verified as originating from Wave.
|
|
15
|
+
*/
|
|
16
|
+
export class WaveWebhookVerificationError extends WaveError {
|
|
17
|
+
/** Specific verification failure. */
|
|
18
|
+
readonly reason: WebhookVerificationFailureReason;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param reason - Specific verification failure.
|
|
22
|
+
* @param message - Human-readable description that never contains the webhook secret.
|
|
23
|
+
*/
|
|
24
|
+
constructor(reason: WebhookVerificationFailureReason, message: string) {
|
|
25
|
+
super(message, { code: `webhook-${reason}` });
|
|
26
|
+
this.reason = reason;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { TransportRequest, TransportResponse, WaveTransport } from './transport.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal fetch signature accepted by {@link FetchTransport}.
|
|
5
|
+
*
|
|
6
|
+
* Compatible with the global `fetch` in Node.js 22+ and Bun.
|
|
7
|
+
*/
|
|
8
|
+
export type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Default transport backed by the global Fetch API.
|
|
12
|
+
*
|
|
13
|
+
* The request body is transmitted verbatim so that the bytes signed by the SDK are the bytes sent
|
|
14
|
+
* over the network.
|
|
15
|
+
*/
|
|
16
|
+
export class FetchTransport implements WaveTransport {
|
|
17
|
+
readonly #fetch: FetchLike;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param fetchImplementation - Fetch implementation to use; defaults to `globalThis.fetch`.
|
|
21
|
+
*/
|
|
22
|
+
constructor(fetchImplementation: FetchLike = globalThis.fetch) {
|
|
23
|
+
this.#fetch = fetchImplementation;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @inheritdoc */
|
|
27
|
+
async send(request: TransportRequest): Promise<TransportResponse> {
|
|
28
|
+
const init: RequestInit = {
|
|
29
|
+
method: request.method,
|
|
30
|
+
headers: { ...request.headers },
|
|
31
|
+
signal: request.signal,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
if (request.body !== undefined) {
|
|
35
|
+
init.body = request.body;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const response = await this.#fetch(request.url, init);
|
|
39
|
+
const bodyText = await response.text();
|
|
40
|
+
|
|
41
|
+
const headers: Record<string, string> = {};
|
|
42
|
+
response.headers.forEach((value, key) => {
|
|
43
|
+
headers[key.toLowerCase()] = value;
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
return { status: response.status, headers, bodyText };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
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 type { WaveApiError } from '../errors/wave-api-error.js';
|
|
6
|
+
import { parseApiError } from '../errors/error-parser.js';
|
|
7
|
+
import {
|
|
8
|
+
WaveAbortError,
|
|
9
|
+
WaveNetworkError,
|
|
10
|
+
WaveTimeoutError,
|
|
11
|
+
} from '../errors/wave-network-error.js';
|
|
12
|
+
import { assertValidIdempotencyKey, generateIdempotencyKey } from '../idempotency/idempotency.js';
|
|
13
|
+
import { computeBackoffDelay, delay } from '../retry/backoff.js';
|
|
14
|
+
import { isRetryableStatus, resolveRetryOptions } from '../retry/retry-policy.js';
|
|
15
|
+
import type { RequestOptions, RetryOptions, WaveLogger } from '../types/configuration.js';
|
|
16
|
+
import type { HttpRequest, OperationDefinition } from './http-request.js';
|
|
17
|
+
import { hasEmptyBody, isJsonContentType } from './http-response.js';
|
|
18
|
+
import type { HttpResponse } from './http-response.js';
|
|
19
|
+
import { buildQueryString } from './query.js';
|
|
20
|
+
import type { TransportResponse, WaveTransport } from './transport.js';
|
|
21
|
+
|
|
22
|
+
/** Default Wave API base URL. */
|
|
23
|
+
export const DEFAULT_BASE_URL = 'https://api.wave.com';
|
|
24
|
+
|
|
25
|
+
/** Default request timeout in milliseconds. */
|
|
26
|
+
export const DEFAULT_TIMEOUT_MS = 30000;
|
|
27
|
+
|
|
28
|
+
const USER_AGENT = 'wave-sdk-typescript/0.1.0';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Resolved HTTP client configuration.
|
|
32
|
+
*/
|
|
33
|
+
export interface HttpClientConfig {
|
|
34
|
+
/** Normalized base URL without a trailing slash. */
|
|
35
|
+
readonly baseUrl: string;
|
|
36
|
+
/** Wave Business API key. */
|
|
37
|
+
readonly apiKey: string;
|
|
38
|
+
/** Optional signing secret. */
|
|
39
|
+
readonly signingSecret: string | undefined;
|
|
40
|
+
/** HTTP transport. */
|
|
41
|
+
readonly transport: WaveTransport;
|
|
42
|
+
/** Default request timeout in milliseconds. */
|
|
43
|
+
readonly timeoutMs: number;
|
|
44
|
+
/** Default retry policy, or `false` when disabled. */
|
|
45
|
+
readonly retry: RetryOptions | false;
|
|
46
|
+
/** Optional diagnostics logger. */
|
|
47
|
+
readonly logger: WaveLogger | undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface AttemptSignal {
|
|
51
|
+
readonly signal: AbortSignal;
|
|
52
|
+
readonly timedOut: () => boolean;
|
|
53
|
+
readonly dispose: () => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Shared request pipeline used by every API module.
|
|
58
|
+
*
|
|
59
|
+
* Responsibilities: URL and query construction, single body serialization, authentication, request
|
|
60
|
+
* signing, idempotency headers, timeouts, status validation, error mapping and safe retries.
|
|
61
|
+
*/
|
|
62
|
+
export class HttpClient {
|
|
63
|
+
readonly #config: HttpClientConfig;
|
|
64
|
+
readonly #signer: RequestSigner | undefined;
|
|
65
|
+
readonly #secrets: readonly string[];
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param config - Resolved client configuration.
|
|
69
|
+
*/
|
|
70
|
+
constructor(config: HttpClientConfig) {
|
|
71
|
+
this.#config = config;
|
|
72
|
+
this.#signer =
|
|
73
|
+
config.signingSecret === undefined ? undefined : new RequestSigner(config.signingSecret);
|
|
74
|
+
this.#secrets =
|
|
75
|
+
config.signingSecret === undefined ? [config.apiKey] : [config.apiKey, config.signingSecret];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Executes a request that returns a JSON response body.
|
|
80
|
+
*
|
|
81
|
+
* @typeParam T - Expected response type.
|
|
82
|
+
* @param operation - Retry-safety metadata.
|
|
83
|
+
* @param request - Request definition.
|
|
84
|
+
* @param options - Per-request overrides.
|
|
85
|
+
*/
|
|
86
|
+
async request<T>(
|
|
87
|
+
operation: OperationDefinition,
|
|
88
|
+
request: HttpRequest,
|
|
89
|
+
options: RequestOptions = {},
|
|
90
|
+
): Promise<T> {
|
|
91
|
+
const body = await this.#execute(operation, request, options);
|
|
92
|
+
if (body === undefined) {
|
|
93
|
+
throw new WaveError('Wave API returned an empty response body.', {
|
|
94
|
+
code: 'invalid-response-body',
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return body as T;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Executes a request whose documented response has no body.
|
|
102
|
+
*
|
|
103
|
+
* @param operation - Retry-safety metadata.
|
|
104
|
+
* @param request - Request definition.
|
|
105
|
+
* @param options - Per-request overrides.
|
|
106
|
+
*/
|
|
107
|
+
async requestVoid(
|
|
108
|
+
operation: OperationDefinition,
|
|
109
|
+
request: HttpRequest,
|
|
110
|
+
options: RequestOptions = {},
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
await this.#execute(operation, request, options);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async #execute(
|
|
116
|
+
operation: OperationDefinition,
|
|
117
|
+
request: HttpRequest,
|
|
118
|
+
options: RequestOptions,
|
|
119
|
+
): Promise<unknown> {
|
|
120
|
+
if (
|
|
121
|
+
options.timeoutMs !== undefined &&
|
|
122
|
+
(!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)
|
|
123
|
+
) {
|
|
124
|
+
throw new WaveConfigurationError('timeoutMs must be a positive finite number.');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const url = `${this.#config.baseUrl}${request.path}${buildQueryString(request.query)}`;
|
|
128
|
+
const serializedBody = request.body === undefined ? undefined : JSON.stringify(request.body);
|
|
129
|
+
const idempotencyKey = this.#resolveIdempotencyKey(
|
|
130
|
+
operation,
|
|
131
|
+
request.idempotencyKey,
|
|
132
|
+
options.idempotencyKey,
|
|
133
|
+
);
|
|
134
|
+
const retry =
|
|
135
|
+
operation.idempotent || options.retry !== undefined
|
|
136
|
+
? resolveRetryOptions(this.#config.retry, options.retry)
|
|
137
|
+
: false;
|
|
138
|
+
const maxAttempts = retry === false ? 1 : retry.maxRetries + 1;
|
|
139
|
+
const timeoutMs = options.timeoutMs ?? this.#config.timeoutMs;
|
|
140
|
+
|
|
141
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
142
|
+
const attemptNumber = attempt + 1;
|
|
143
|
+
const attemptSignal = createAttemptSignal(options.signal, timeoutMs);
|
|
144
|
+
const startedAt = Date.now();
|
|
145
|
+
|
|
146
|
+
this.#log('debug', 'wave.request', {
|
|
147
|
+
method: request.method,
|
|
148
|
+
path: request.path,
|
|
149
|
+
attempt: attemptNumber,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
let response: TransportResponse;
|
|
153
|
+
try {
|
|
154
|
+
response = await this.#config.transport.send({
|
|
155
|
+
url,
|
|
156
|
+
method: request.method,
|
|
157
|
+
headers: this.#buildHeaders(serializedBody, idempotencyKey),
|
|
158
|
+
...(serializedBody === undefined ? {} : { body: serializedBody }),
|
|
159
|
+
signal: attemptSignal.signal,
|
|
160
|
+
});
|
|
161
|
+
} catch (error) {
|
|
162
|
+
attemptSignal.dispose();
|
|
163
|
+
|
|
164
|
+
if (attemptSignal.timedOut()) {
|
|
165
|
+
throw new WaveTimeoutError(`Wave API request timed out after ${timeoutMs} ms.`, {
|
|
166
|
+
cause: error,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
if (options.signal?.aborted === true) {
|
|
170
|
+
throw new WaveAbortError('Wave API request was aborted by the caller.', { cause: error });
|
|
171
|
+
}
|
|
172
|
+
if (retry !== false && attempt < maxAttempts - 1) {
|
|
173
|
+
await this.#waitBeforeRetry(attempt, undefined, retry, options.signal, request);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
throw new WaveNetworkError('Could not reach the Wave API.', { cause: error });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
attemptSignal.dispose();
|
|
180
|
+
const durationMs = Date.now() - startedAt;
|
|
181
|
+
this.#log('debug', 'wave.response', {
|
|
182
|
+
method: request.method,
|
|
183
|
+
path: request.path,
|
|
184
|
+
status: response.status,
|
|
185
|
+
attempt: attemptNumber,
|
|
186
|
+
durationMs,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
if (response.status >= 200 && response.status < 300) {
|
|
190
|
+
return parseSuccessBody(response);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const apiError = parseApiError({
|
|
194
|
+
statusCode: response.status,
|
|
195
|
+
bodyText: response.bodyText,
|
|
196
|
+
headers: response.headers,
|
|
197
|
+
secrets: this.#secrets,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
if (retry !== false && isRetryableStatus(response.status) && attempt < maxAttempts - 1) {
|
|
201
|
+
await this.#waitBeforeRetry(attempt, apiError, retry, options.signal, request);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
throw apiError;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
#resolveIdempotencyKey(
|
|
210
|
+
operation: OperationDefinition,
|
|
211
|
+
requestKey: string | undefined,
|
|
212
|
+
optionKey: string | undefined,
|
|
213
|
+
): string | undefined {
|
|
214
|
+
const explicit = optionKey ?? requestKey;
|
|
215
|
+
if (explicit !== undefined) {
|
|
216
|
+
assertValidIdempotencyKey(explicit);
|
|
217
|
+
return explicit;
|
|
218
|
+
}
|
|
219
|
+
if (!operation.requiresIdempotencyKey) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return generateIdempotencyKey();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#buildHeaders(
|
|
226
|
+
serializedBody: string | undefined,
|
|
227
|
+
idempotencyKey: string | undefined,
|
|
228
|
+
): Record<string, string> {
|
|
229
|
+
const headers: Record<string, string> = {
|
|
230
|
+
Accept: 'application/json',
|
|
231
|
+
Authorization: buildAuthorizationHeader(this.#config.apiKey),
|
|
232
|
+
'User-Agent': USER_AGENT,
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
if (serializedBody !== undefined) {
|
|
236
|
+
headers['Content-Type'] = 'application/json';
|
|
237
|
+
}
|
|
238
|
+
if (idempotencyKey !== undefined) {
|
|
239
|
+
headers['Idempotency-Key'] = idempotencyKey;
|
|
240
|
+
}
|
|
241
|
+
if (this.#signer !== undefined) {
|
|
242
|
+
headers[SIGNATURE_HEADER] = this.#signer.sign(serializedBody ?? '');
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return headers;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async #waitBeforeRetry(
|
|
249
|
+
attempt: number,
|
|
250
|
+
error: WaveApiError | undefined,
|
|
251
|
+
retry: RetryOptions,
|
|
252
|
+
signal: AbortSignal | undefined,
|
|
253
|
+
request: HttpRequest,
|
|
254
|
+
): Promise<void> {
|
|
255
|
+
const retryAfterSeconds =
|
|
256
|
+
error instanceof WaveRateLimitError ? error.retryAfterSeconds : undefined;
|
|
257
|
+
const waitMs =
|
|
258
|
+
retryAfterSeconds === undefined
|
|
259
|
+
? computeBackoffDelay(attempt, retry)
|
|
260
|
+
: retryAfterSeconds * 1000;
|
|
261
|
+
|
|
262
|
+
this.#log('warn', 'wave.retry', {
|
|
263
|
+
method: request.method,
|
|
264
|
+
path: request.path,
|
|
265
|
+
attempt: attempt + 1,
|
|
266
|
+
status: error?.statusCode,
|
|
267
|
+
waitMs,
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
await delay(waitMs, signal);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
#log(level: 'debug' | 'warn', message: string, meta: Readonly<Record<string, unknown>>): void {
|
|
274
|
+
const logger = this.#config.logger;
|
|
275
|
+
if (logger === undefined) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
if (level === 'debug') {
|
|
280
|
+
logger.debug?.(message, meta);
|
|
281
|
+
} else {
|
|
282
|
+
logger.warn?.(message, meta);
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// Diagnostics must never break an API request.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function parseSuccessBody(response: TransportResponse): unknown {
|
|
291
|
+
const httpResponse: HttpResponse = {
|
|
292
|
+
status: response.status,
|
|
293
|
+
headers: response.headers,
|
|
294
|
+
bodyText: response.bodyText,
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
if (hasEmptyBody(httpResponse)) {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
if (!isJsonContentType(response.headers)) {
|
|
301
|
+
throw new WaveError(`Wave API returned a non-JSON response with HTTP ${response.status}.`, {
|
|
302
|
+
code: 'invalid-response-body',
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
try {
|
|
307
|
+
return JSON.parse(response.bodyText) as unknown;
|
|
308
|
+
} catch (cause) {
|
|
309
|
+
throw new WaveError(`Wave API returned invalid JSON with HTTP ${response.status}.`, {
|
|
310
|
+
code: 'invalid-response-body',
|
|
311
|
+
cause,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function createAttemptSignal(caller: AbortSignal | undefined, timeoutMs: number): AttemptSignal {
|
|
317
|
+
const controller = new AbortController();
|
|
318
|
+
let timedOut = false;
|
|
319
|
+
|
|
320
|
+
const timer = setTimeout(() => {
|
|
321
|
+
timedOut = true;
|
|
322
|
+
controller.abort();
|
|
323
|
+
}, timeoutMs);
|
|
324
|
+
timer.unref();
|
|
325
|
+
|
|
326
|
+
const onAbort = (): void => {
|
|
327
|
+
controller.abort();
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const abortIfCallerAlreadyAborted = (): void => {
|
|
331
|
+
if (caller?.aborted === true) {
|
|
332
|
+
controller.abort();
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
if (caller?.aborted === true) {
|
|
337
|
+
controller.abort();
|
|
338
|
+
} else {
|
|
339
|
+
caller?.addEventListener('abort', onAbort, { once: true });
|
|
340
|
+
// Re-check to close the race between the check above and listener registration.
|
|
341
|
+
abortIfCallerAlreadyAborted();
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return {
|
|
345
|
+
signal: controller.signal,
|
|
346
|
+
timedOut: () => timedOut,
|
|
347
|
+
dispose: () => {
|
|
348
|
+
clearTimeout(timer);
|
|
349
|
+
caller?.removeEventListener('abort', onAbort);
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { QueryParameterValue } from './query.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* HTTP methods used by the Wave Business APIs.
|
|
5
|
+
*/
|
|
6
|
+
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Retry-safety metadata for an API operation.
|
|
10
|
+
*/
|
|
11
|
+
export interface OperationDefinition {
|
|
12
|
+
/**
|
|
13
|
+
* Whether the operation can be retried without risking an unintended side effect.
|
|
14
|
+
*
|
|
15
|
+
* Wave documents some mutating endpoints as idempotent; GET requests are always idempotent.
|
|
16
|
+
* Operations that create a new resource without a documented idempotency mechanism are not.
|
|
17
|
+
*/
|
|
18
|
+
readonly idempotent: boolean;
|
|
19
|
+
/** Whether an `Idempotency-Key` header must be sent (documented for financial mutations). */
|
|
20
|
+
readonly requiresIdempotencyKey: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* An endpoint-relative HTTP request.
|
|
25
|
+
*/
|
|
26
|
+
export interface HttpRequest {
|
|
27
|
+
/** HTTP method. */
|
|
28
|
+
readonly method: HttpMethod;
|
|
29
|
+
/** Path relative to the configured base URL, starting with `/`. */
|
|
30
|
+
readonly path: string;
|
|
31
|
+
/** Query parameters; `undefined` and `null` values are omitted. */
|
|
32
|
+
readonly query?: Readonly<Record<string, QueryParameterValue>>;
|
|
33
|
+
/** JSON request body, serialized exactly once by the HTTP layer. */
|
|
34
|
+
readonly body?: unknown;
|
|
35
|
+
/** Caller-supplied idempotency key for this request. */
|
|
36
|
+
readonly idempotencyKey?: string;
|
|
37
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
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
|
+
/**
|
|
14
|
+
* Whether the response carries no payload.
|
|
15
|
+
*
|
|
16
|
+
* Wave documents empty responses for payout reversal, checkout refund/expire, transaction refund
|
|
17
|
+
* and aggregated merchant deletion.
|
|
18
|
+
*/
|
|
19
|
+
export function hasEmptyBody(response: HttpResponse): boolean {
|
|
20
|
+
return (
|
|
21
|
+
response.status === 204 || response.status === 205 || response.bodyText.trim().length === 0
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether the response body should be treated as JSON.
|
|
27
|
+
*
|
|
28
|
+
* A missing content type is accepted because some intermediaries strip it; an explicit non-JSON
|
|
29
|
+
* content type is not.
|
|
30
|
+
*/
|
|
31
|
+
export function isJsonContentType(headers: Readonly<Record<string, string>>): boolean {
|
|
32
|
+
const contentType = headers['content-type'];
|
|
33
|
+
if (contentType === undefined) {
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
return contentType.toLowerCase().includes('application/json');
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
/**
|
|
7
|
+
* Builds a query string from documented parameters.
|
|
8
|
+
*
|
|
9
|
+
* Values keep their API-defined representation; booleans are serialized as `true` / `false`.
|
|
10
|
+
*
|
|
11
|
+
* @param query - Parameters to serialize.
|
|
12
|
+
* @returns The query string including the leading `?`, or an empty string when no value is set.
|
|
13
|
+
*/
|
|
14
|
+
export function buildQueryString(
|
|
15
|
+
query: Readonly<Record<string, QueryParameterValue>> | undefined,
|
|
16
|
+
): string {
|
|
17
|
+
if (query === undefined) {
|
|
18
|
+
return '';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const params = new URLSearchParams();
|
|
22
|
+
for (const [key, value] of Object.entries(query)) {
|
|
23
|
+
if (value === undefined || value === null) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
params.append(key, String(value));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const serialized = params.toString();
|
|
30
|
+
return serialized.length > 0 ? `?${serialized}` : '';
|
|
31
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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
|
+
/**
|
|
21
|
+
* A raw transport response.
|
|
22
|
+
*/
|
|
23
|
+
export interface TransportResponse {
|
|
24
|
+
/** HTTP status code. */
|
|
25
|
+
readonly status: number;
|
|
26
|
+
/** Response headers with lowercase names. */
|
|
27
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
28
|
+
/** Response body decoded as UTF-8 text. */
|
|
29
|
+
readonly bodyText: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Pluggable HTTP transport used by the SDK.
|
|
34
|
+
*
|
|
35
|
+
* The default implementation uses the global `fetch` API. Implement this interface to integrate a
|
|
36
|
+
* custom HTTP stack; the SDK still applies authentication, signing, idempotency and retries.
|
|
37
|
+
*/
|
|
38
|
+
export interface WaveTransport {
|
|
39
|
+
/**
|
|
40
|
+
* Sends a prepared request and resolves with the raw response.
|
|
41
|
+
*
|
|
42
|
+
* Implementations must reject on network failures and must honour the provided abort signal.
|
|
43
|
+
*/
|
|
44
|
+
send(request: TransportRequest): Promise<TransportResponse>;
|
|
45
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { WaveConfigurationError } from '../errors/wave-error.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Maximum idempotency key length documented by Wave.
|
|
6
|
+
*/
|
|
7
|
+
export const MAX_IDEMPOTENCY_KEY_LENGTH = 255;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Generates a random v4 UUID suitable as an idempotency key.
|
|
11
|
+
*/
|
|
12
|
+
export function generateIdempotencyKey(): string {
|
|
13
|
+
return randomUUID();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Validates a caller-supplied idempotency key before any request is sent.
|
|
18
|
+
*
|
|
19
|
+
* @param key - Candidate key.
|
|
20
|
+
* @throws WaveConfigurationError when the key is empty or longer than 255 characters.
|
|
21
|
+
*/
|
|
22
|
+
export function assertValidIdempotencyKey(key: string): void {
|
|
23
|
+
if (key.length === 0) {
|
|
24
|
+
throw new WaveConfigurationError('Idempotency key must be a non-empty string.');
|
|
25
|
+
}
|
|
26
|
+
if (key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
|
|
27
|
+
throw new WaveConfigurationError(
|
|
28
|
+
`Idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters long.`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { WaveAbortError } from '../errors/wave-network-error.js';
|
|
2
|
+
import type { RetryOptions } from '../types/configuration.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Computes the delay before a retry using exponential backoff with optional full jitter.
|
|
6
|
+
*
|
|
7
|
+
* @param attempt - Zero-based retry index (0 for the first retry).
|
|
8
|
+
* @param options - Retry configuration.
|
|
9
|
+
* @param random - Random source in `[0, 1)`; injectable for deterministic tests.
|
|
10
|
+
* @returns Delay in milliseconds, never above `maxDelayMs`.
|
|
11
|
+
*/
|
|
12
|
+
export function computeBackoffDelay(
|
|
13
|
+
attempt: number,
|
|
14
|
+
options: RetryOptions,
|
|
15
|
+
random: () => number = Math.random,
|
|
16
|
+
): number {
|
|
17
|
+
const exponential = options.baseDelayMs * 2 ** Math.max(0, attempt);
|
|
18
|
+
const capped = Math.min(options.maxDelayMs, exponential);
|
|
19
|
+
return Math.round(options.jitter ? random() * capped : capped);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Waits for a delay, rejecting immediately if the caller aborts.
|
|
24
|
+
*
|
|
25
|
+
* @param delayMs - Time to wait in milliseconds.
|
|
26
|
+
* @param signal - Caller abort signal.
|
|
27
|
+
*/
|
|
28
|
+
export function delay(delayMs: number, signal: AbortSignal | undefined): Promise<void> {
|
|
29
|
+
if (signal?.aborted === true) {
|
|
30
|
+
return Promise.reject(
|
|
31
|
+
new WaveAbortError('Wave API request was aborted by the caller.', { cause: signal.reason }),
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (delayMs <= 0) {
|
|
36
|
+
return Promise.resolve();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return new Promise<void>((resolve, reject) => {
|
|
40
|
+
const cleanup = (): void => {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
signal?.removeEventListener('abort', onAbort);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const onAbort = (): void => {
|
|
46
|
+
cleanup();
|
|
47
|
+
reject(
|
|
48
|
+
new WaveAbortError('Wave API request was aborted by the caller.', {
|
|
49
|
+
cause: signal?.reason,
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const timer = setTimeout(() => {
|
|
55
|
+
cleanup();
|
|
56
|
+
resolve();
|
|
57
|
+
}, delayMs);
|
|
58
|
+
|
|
59
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
60
|
+
});
|
|
61
|
+
}
|