@tickwise/sdk 0.0.0-stage → 0.1.1

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 (72) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +203 -2
  3. package/dist/cjs/api-promise.d.ts +22 -0
  4. package/dist/cjs/api-promise.js +43 -0
  5. package/dist/cjs/client.d.ts +64 -0
  6. package/dist/cjs/client.js +123 -0
  7. package/dist/cjs/csv.d.ts +37 -0
  8. package/dist/cjs/csv.js +69 -0
  9. package/dist/cjs/errors.d.ts +133 -0
  10. package/dist/cjs/errors.js +242 -0
  11. package/dist/cjs/generated/openapi.d.ts +1949 -0
  12. package/dist/cjs/generated/openapi.js +6 -0
  13. package/dist/cjs/index.d.ts +11 -0
  14. package/dist/cjs/index.js +33 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/resources/base.d.ts +21 -0
  17. package/dist/cjs/resources/base.js +81 -0
  18. package/dist/cjs/resources/hooks.d.ts +26 -0
  19. package/dist/cjs/resources/hooks.js +46 -0
  20. package/dist/cjs/resources/meta.d.ts +23 -0
  21. package/dist/cjs/resources/meta.js +35 -0
  22. package/dist/cjs/resources/pools.d.ts +21 -0
  23. package/dist/cjs/resources/pools.js +40 -0
  24. package/dist/cjs/resources/positions.d.ts +59 -0
  25. package/dist/cjs/resources/positions.js +187 -0
  26. package/dist/cjs/resources/tokens.d.ts +19 -0
  27. package/dist/cjs/resources/tokens.js +28 -0
  28. package/dist/cjs/resources/wallets.d.ts +11 -0
  29. package/dist/cjs/resources/wallets.js +14 -0
  30. package/dist/cjs/routes.d.ts +84 -0
  31. package/dist/cjs/routes.js +45 -0
  32. package/dist/cjs/transport.d.ts +92 -0
  33. package/dist/cjs/transport.js +314 -0
  34. package/dist/cjs/types.d.ts +112 -0
  35. package/dist/cjs/types.js +2 -0
  36. package/dist/cjs/version.d.ts +2 -0
  37. package/dist/cjs/version.js +5 -0
  38. package/dist/esm/api-promise.d.ts +22 -0
  39. package/dist/esm/api-promise.js +39 -0
  40. package/dist/esm/client.d.ts +64 -0
  41. package/dist/esm/client.js +119 -0
  42. package/dist/esm/csv.d.ts +37 -0
  43. package/dist/esm/csv.js +64 -0
  44. package/dist/esm/errors.d.ts +133 -0
  45. package/dist/esm/errors.js +221 -0
  46. package/dist/esm/generated/openapi.d.ts +1949 -0
  47. package/dist/esm/generated/openapi.js +5 -0
  48. package/dist/esm/index.d.ts +11 -0
  49. package/dist/esm/index.js +8 -0
  50. package/dist/esm/resources/base.d.ts +21 -0
  51. package/dist/esm/resources/base.js +73 -0
  52. package/dist/esm/resources/hooks.d.ts +26 -0
  53. package/dist/esm/resources/hooks.js +42 -0
  54. package/dist/esm/resources/meta.d.ts +23 -0
  55. package/dist/esm/resources/meta.js +30 -0
  56. package/dist/esm/resources/pools.d.ts +21 -0
  57. package/dist/esm/resources/pools.js +36 -0
  58. package/dist/esm/resources/positions.d.ts +59 -0
  59. package/dist/esm/resources/positions.js +183 -0
  60. package/dist/esm/resources/tokens.d.ts +19 -0
  61. package/dist/esm/resources/tokens.js +24 -0
  62. package/dist/esm/resources/wallets.d.ts +11 -0
  63. package/dist/esm/resources/wallets.js +10 -0
  64. package/dist/esm/routes.d.ts +84 -0
  65. package/dist/esm/routes.js +41 -0
  66. package/dist/esm/transport.d.ts +92 -0
  67. package/dist/esm/transport.js +303 -0
  68. package/dist/esm/types.d.ts +112 -0
  69. package/dist/esm/types.js +1 -0
  70. package/dist/esm/version.d.ts +2 -0
  71. package/dist/esm/version.js +2 -0
  72. package/package.json +64 -4
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Tokens = void 0;
4
+ const base_js_1 = require("./base.js");
5
+ class Tokens extends base_js_1.Resource {
6
+ /**
7
+ * `GET /v1/tokens/{chainId}/{address}`: one token's USD price and where it came from, what the API knows about
8
+ * it, its risk flags, and a page of the pools holding it. The chain's native token is the zero address.
9
+ */
10
+ get(chainId, address, query, options) {
11
+ return this.call('tokens.detail', { chainId, address }, (0, base_js_1.toQuery)(query), options);
12
+ }
13
+ /**
14
+ * `GET /v1/tokens/search`: find tokens by symbol, name or address (`q`, 1 to 100 characters), best match first,
15
+ * on one chain (`chainId`) or every chain. `limit` 1 to 20, default 5. One flat charge per answer; a `partial`
16
+ * answer (some chains not searchable yet, listed in `pendingChains`) is not charged.
17
+ */
18
+ search(query, options) {
19
+ return this.call('tokens.search', undefined, (0, base_js_1.toQuery)(query), options);
20
+ }
21
+ /** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
22
+ iteratePools(chainId, address, query, options) {
23
+ const [req, paging] = (0, base_js_1.splitOptions)(options);
24
+ const pages = (0, base_js_1.pageIterator)(query, (page) => this.get(chainId, address, { ...query, page }, req), (p) => p.pagination.hasMore, (p) => p.pools.length, paging.maxPages === undefined ? {} : { maxPages: paging.maxPages });
25
+ return (0, base_js_1.rowIterator)(pages, (p) => p.pools, paging);
26
+ }
27
+ }
28
+ exports.Tokens = Tokens;
@@ -0,0 +1,11 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import type { RequestOptions } from '../transport.js';
3
+ import type { WalletSummary, WalletSummaryQuery } from '../types.js';
4
+ import { Resource } from './base.js';
5
+ export declare class Wallets extends Resource {
6
+ /**
7
+ * `GET /v1/wallets/{address}`: one wallet's positions summed across every chain (or one `chainId`): value,
8
+ * uncollected fees, PnL and counts, in total and per chain. A wallet with no positions is zeros, not a 404.
9
+ */
10
+ summary(address: string, query?: WalletSummaryQuery, options?: RequestOptions): APIPromise<WalletSummary>;
11
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Wallets = void 0;
4
+ const base_js_1 = require("./base.js");
5
+ class Wallets extends base_js_1.Resource {
6
+ /**
7
+ * `GET /v1/wallets/{address}`: one wallet's positions summed across every chain (or one `chainId`): value,
8
+ * uncollected fees, PnL and counts, in total and per chain. A wallet with no positions is zeros, not a 404.
9
+ */
10
+ summary(address, query, options) {
11
+ return this.call('wallets.summary', { address }, (0, base_js_1.toQuery)(query), options);
12
+ }
13
+ }
14
+ exports.Wallets = Wallets;
@@ -0,0 +1,84 @@
1
+ import type { paths } from './generated/openapi.js';
2
+ export interface Route {
3
+ /** The OpenAPI path template. */
4
+ readonly path: keyof paths;
5
+ /** Metered routes need the key and cost units; free routes never send it. */
6
+ readonly metered: boolean;
7
+ }
8
+ /**
9
+ * Every `/v1` operation the SDK calls, keyed by the spec's `operationId`. `test/route-coverage.spec.ts` holds this
10
+ * to `openapi.json` both ways, so a route added to the API without an SDK method fails the build.
11
+ */
12
+ export declare const ROUTES: {
13
+ readonly 'positions.list': {
14
+ readonly path: "/v1/positions";
15
+ readonly metered: true;
16
+ };
17
+ readonly 'positions.batch': {
18
+ readonly path: "/v1/positions/batch";
19
+ readonly metered: true;
20
+ };
21
+ readonly 'positions.detail': {
22
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}";
23
+ readonly metered: true;
24
+ };
25
+ readonly 'positions.transactions': {
26
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}/transactions";
27
+ readonly metered: true;
28
+ };
29
+ readonly 'positions.charts': {
30
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}/charts";
31
+ readonly metered: true;
32
+ };
33
+ readonly 'pools.list': {
34
+ readonly path: "/v1/pools";
35
+ readonly metered: true;
36
+ };
37
+ readonly 'pools.detail': {
38
+ readonly path: "/v1/pools/{chainId}/{protocol}/{poolId}";
39
+ readonly metered: true;
40
+ };
41
+ readonly 'pools.charts': {
42
+ readonly path: "/v1/pools/{chainId}/{protocol}/{poolId}/charts";
43
+ readonly metered: true;
44
+ };
45
+ readonly 'tokens.detail': {
46
+ readonly path: "/v1/tokens/{chainId}/{address}";
47
+ readonly metered: true;
48
+ };
49
+ readonly 'tokens.search': {
50
+ readonly path: "/v1/tokens/search";
51
+ readonly metered: true;
52
+ };
53
+ readonly 'wallets.summary': {
54
+ readonly path: "/v1/wallets/{address}";
55
+ readonly metered: true;
56
+ };
57
+ readonly 'hooks.list': {
58
+ readonly path: "/v1/hooks";
59
+ readonly metered: true;
60
+ };
61
+ readonly chains: {
62
+ readonly path: "/v1/chains";
63
+ readonly metered: false;
64
+ };
65
+ readonly protocols: {
66
+ readonly path: "/v1/protocols";
67
+ readonly metered: false;
68
+ };
69
+ readonly plans: {
70
+ readonly path: "/v1/plans";
71
+ readonly metered: false;
72
+ };
73
+ readonly 'pricing.units': {
74
+ readonly path: "/v1/pricing/units";
75
+ readonly metered: false;
76
+ };
77
+ readonly stats: {
78
+ readonly path: "/v1/stats";
79
+ readonly metered: false;
80
+ };
81
+ };
82
+ export type OperationId = keyof typeof ROUTES;
83
+ /** Fills a path template: `{name}` → the encoded value. */
84
+ export declare function fillPath(op: OperationId, params?: Readonly<Record<string, string | number | bigint>>): string;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROUTES = void 0;
4
+ exports.fillPath = fillPath;
5
+ /**
6
+ * Every `/v1` operation the SDK calls, keyed by the spec's `operationId`. `test/route-coverage.spec.ts` holds this
7
+ * to `openapi.json` both ways, so a route added to the API without an SDK method fails the build.
8
+ */
9
+ exports.ROUTES = {
10
+ 'positions.list': { path: '/v1/positions', metered: true },
11
+ 'positions.batch': { path: '/v1/positions/batch', metered: true },
12
+ 'positions.detail': { path: '/v1/positions/{chainId}/{protocol}/{positionId}', metered: true },
13
+ 'positions.transactions': { path: '/v1/positions/{chainId}/{protocol}/{positionId}/transactions', metered: true },
14
+ 'positions.charts': { path: '/v1/positions/{chainId}/{protocol}/{positionId}/charts', metered: true },
15
+ 'pools.list': { path: '/v1/pools', metered: true },
16
+ 'pools.detail': { path: '/v1/pools/{chainId}/{protocol}/{poolId}', metered: true },
17
+ 'pools.charts': { path: '/v1/pools/{chainId}/{protocol}/{poolId}/charts', metered: true },
18
+ 'tokens.detail': { path: '/v1/tokens/{chainId}/{address}', metered: true },
19
+ 'tokens.search': { path: '/v1/tokens/search', metered: true },
20
+ 'wallets.summary': { path: '/v1/wallets/{address}', metered: true },
21
+ 'hooks.list': { path: '/v1/hooks', metered: true },
22
+ chains: { path: '/v1/chains', metered: false },
23
+ protocols: { path: '/v1/protocols', metered: false },
24
+ plans: { path: '/v1/plans', metered: false },
25
+ 'pricing.units': { path: '/v1/pricing/units', metered: false },
26
+ stats: { path: '/v1/stats', metered: false },
27
+ };
28
+ /** Fills a path template: `{name}` → the encoded value. */
29
+ function fillPath(op, params = {}) {
30
+ return exports.ROUTES[op].path.replace(/\{([A-Za-z0-9_]+)\}/g, (_, name) => {
31
+ const v = params[name];
32
+ if (v === undefined || v === null || String(v) === '') {
33
+ throw new TypeError(`${op}: missing path parameter \`${name}\``);
34
+ }
35
+ // A number past 2^53 has already lost digits: sending it would ask for another id.
36
+ if (typeof v === 'number' && !Number.isSafeInteger(v)) {
37
+ throw new TypeError(`${op}: \`${name}\` ${v} is not a safe integer; pass a large id as a string or a bigint`);
38
+ }
39
+ // encodeURIComponent leaves `.` and `..` alone and URL parsing collapses them, which would call another route.
40
+ if (String(v) === '.' || String(v) === '..') {
41
+ throw new TypeError(`${op}: \`${name}\` cannot be \`${String(v)}\``);
42
+ }
43
+ return encodeURIComponent(String(v));
44
+ });
45
+ }
@@ -0,0 +1,92 @@
1
+ export declare const DEFAULT_BASE_URL = "https://api.tickwise.xyz";
2
+ export declare const DEFAULT_KEY_HEADER = "KC-APIKey";
3
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
4
+ export declare const DEFAULT_MAX_RETRIES = 2;
5
+ export declare const DEFAULT_MAX_RETRY_AFTER_SEC = 60;
6
+ export type QueryScalar = string | number | boolean | bigint;
7
+ export type QueryValue = QueryScalar | readonly (string | number | bigint)[] | null | undefined;
8
+ export type Query = Readonly<Record<string, QueryValue>>;
9
+ /** Per-call options, the last argument of every method. */
10
+ export interface RequestOptions {
11
+ /** Cancels the call, including a retry wait. The platform's `AbortError` (or the signal's reason) is thrown. */
12
+ signal?: AbortSignal | undefined;
13
+ /** Overrides the client's `timeoutMs` for this call (per attempt). */
14
+ timeoutMs?: number | undefined;
15
+ /** Overrides the client's `maxRetries` for this call. */
16
+ maxRetries?: number | undefined;
17
+ }
18
+ export interface LimitInfo {
19
+ limit: number;
20
+ remaining: number;
21
+ /** Seconds until it resets. */
22
+ resetSec: number;
23
+ }
24
+ /** What `.withMeta()` returns beside the data. */
25
+ export interface ResponseMeta {
26
+ status: number;
27
+ /** The request URL. It never contains the key (the key travels in a header). */
28
+ url: string;
29
+ /** How many retries it took (0 when the first attempt succeeded). */
30
+ retries: number;
31
+ headers: Headers;
32
+ /** `private, max-age=15`, or `no-store` on an answer flagged partial / stale. */
33
+ cacheControl: string | undefined;
34
+ /** The 60-second burst limit of this key (metered routes only). */
35
+ rateLimit: LimitInfo | undefined;
36
+ /** The monthly unit quota of the account (metered routes only). */
37
+ quota: LimitInfo | undefined;
38
+ /** Units this call was charged after refunds. Sent by the positions batch only, which is priced per position. */
39
+ unitsCharged: number | undefined;
40
+ }
41
+ export interface TransportConfig {
42
+ apiKey: string | undefined;
43
+ baseUrl: string;
44
+ keyHeader: string;
45
+ timeoutMs: number;
46
+ maxRetries: number;
47
+ maxRetryAfterSec: number;
48
+ maxBodyBytes: number | undefined;
49
+ fetch: typeof fetch;
50
+ /** Tests only: the jitter source. */
51
+ random?: () => number;
52
+ }
53
+ export interface RawRequest {
54
+ /** Path with its parameters already filled in, e.g. `/v1/pools/1/uniswap-v4/0xabc`. */
55
+ path: string;
56
+ query?: Query | undefined;
57
+ /** Metered routes send the key; free routes never do. */
58
+ metered: boolean;
59
+ accept: 'json' | 'csv';
60
+ }
61
+ export interface RawResponse {
62
+ /** Parsed JSON, or the text for a CSV request. */
63
+ body: unknown;
64
+ meta: ResponseMeta;
65
+ }
66
+ /** A finite number not below 0 (above 0 unless `allowZero`), else a TypeError naming the option. */
67
+ export declare function checkNumber(name: string, v: number, allowZero: boolean): number;
68
+ export declare function isBrowser(): boolean;
69
+ export declare function buildUrl(baseUrl: string, path: string, query?: Query): string;
70
+ /** A path segment, encoded. */
71
+ export declare function seg(v: string | number | bigint): string;
72
+ export declare function metaOf(status: number, url: string, retries: number, headers: Headers): ResponseMeta;
73
+ /**
74
+ * Whether a failed attempt is retried.
75
+ *
76
+ * A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
77
+ * before any charge), a 503 (the API credits it back), and a connection that was never opened. A timeout, a
78
+ * connection lost mid-request, a 502 and a 504 are NOT retried on a metered route: the API may have served, and
79
+ * charged, the first attempt. A 502 comes from the gateway, not the API, so the API's refund of its own 5xx never
80
+ * ran (a process stopped by a deploy after the charge answers 502), and a retry could be billed twice.
81
+ * A free route costs nothing, so those are retried there too.
82
+ * Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
83
+ */
84
+ export declare function isRetryable(e: unknown, metered: boolean): boolean;
85
+ /** True only when every code found says the connection was never opened. No code (e.g. a browser) is false. */
86
+ export declare function connectFailed(e: unknown): boolean;
87
+ export declare class Transport {
88
+ #private;
89
+ constructor(config: TransportConfig);
90
+ get baseUrl(): string;
91
+ request(req: RawRequest, opts?: RequestOptions): Promise<RawResponse>;
92
+ }
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = exports.DEFAULT_MAX_RETRY_AFTER_SEC = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_KEY_HEADER = exports.DEFAULT_BASE_URL = void 0;
4
+ exports.checkNumber = checkNumber;
5
+ exports.isBrowser = isBrowser;
6
+ exports.buildUrl = buildUrl;
7
+ exports.seg = seg;
8
+ exports.metaOf = metaOf;
9
+ exports.isRetryable = isRetryable;
10
+ exports.connectFailed = connectFailed;
11
+ const errors_js_1 = require("./errors.js");
12
+ const version_js_1 = require("./version.js");
13
+ exports.DEFAULT_BASE_URL = 'https://api.tickwise.xyz';
14
+ exports.DEFAULT_KEY_HEADER = 'KC-APIKey';
15
+ exports.DEFAULT_TIMEOUT_MS = 30_000;
16
+ exports.DEFAULT_MAX_RETRIES = 2;
17
+ exports.DEFAULT_MAX_RETRY_AFTER_SEC = 60;
18
+ const BACKOFF_BASE_MS = 500;
19
+ const BACKOFF_CAP_MS = 8_000;
20
+ /** A finite number not below 0 (above 0 unless `allowZero`), else a TypeError naming the option. */
21
+ function checkNumber(name, v, allowZero) {
22
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || (!allowZero && v === 0)) {
23
+ throw new TypeError(`Tickwise: \`${name}\` must be a ${allowZero ? 'non-negative' : 'positive'} finite number`);
24
+ }
25
+ return v;
26
+ }
27
+ function isBrowser() {
28
+ const g = globalThis;
29
+ return typeof g.window !== 'undefined' && typeof g.document !== 'undefined';
30
+ }
31
+ function buildUrl(baseUrl, path, query = {}) {
32
+ const qs = new URLSearchParams();
33
+ for (const [k, v] of Object.entries(query)) {
34
+ if (v === undefined || v === null)
35
+ continue;
36
+ if (Array.isArray(v)) {
37
+ if (v.length > 0)
38
+ qs.append(k, v.map(String).join(','));
39
+ }
40
+ else {
41
+ qs.append(k, String(v));
42
+ }
43
+ }
44
+ const s = qs.toString();
45
+ return `${baseUrl.replace(/\/+$/, '')}${path}${s ? `?${s}` : ''}`;
46
+ }
47
+ /** A path segment, encoded. */
48
+ function seg(v) {
49
+ return encodeURIComponent(String(v));
50
+ }
51
+ function intHeader(h, name) {
52
+ const v = h.get(name);
53
+ if (v === null || v.trim() === '')
54
+ return undefined;
55
+ const n = Number(v.trim());
56
+ return Number.isFinite(n) ? n : undefined;
57
+ }
58
+ function limitInfo(h, prefix) {
59
+ const limit = intHeader(h, `${prefix}-Limit`);
60
+ const remaining = intHeader(h, `${prefix}-Remaining`);
61
+ const resetSec = intHeader(h, `${prefix}-Reset`);
62
+ if (limit === undefined || remaining === undefined || resetSec === undefined)
63
+ return undefined;
64
+ return { limit, remaining, resetSec };
65
+ }
66
+ function metaOf(status, url, retries, headers) {
67
+ return {
68
+ status,
69
+ url,
70
+ retries,
71
+ headers,
72
+ cacheControl: headers.get('cache-control') ?? undefined,
73
+ rateLimit: limitInfo(headers, 'X-RateLimit'),
74
+ quota: limitInfo(headers, 'X-Quota'),
75
+ unitsCharged: intHeader(headers, 'X-Units-Charged'),
76
+ };
77
+ }
78
+ function abortReason(signal) {
79
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
80
+ }
81
+ function sleep(ms, signal) {
82
+ return new Promise((resolve, reject) => {
83
+ if (signal?.aborted) {
84
+ reject(abortReason(signal));
85
+ return;
86
+ }
87
+ const onAbort = () => {
88
+ clearTimeout(timer);
89
+ reject(abortReason(signal));
90
+ };
91
+ const timer = setTimeout(() => {
92
+ signal?.removeEventListener('abort', onAbort);
93
+ resolve();
94
+ }, ms);
95
+ signal?.addEventListener('abort', onAbort, { once: true });
96
+ });
97
+ }
98
+ /** The body as text, or null when it passes `max` bytes (a declared length over the cap is refused unread). */
99
+ async function readText(res, max) {
100
+ if (max === undefined)
101
+ return res.text();
102
+ const declared = Number(res.headers.get('content-length'));
103
+ if (Number.isFinite(declared) && declared > max) {
104
+ await res.body?.cancel().catch(() => { });
105
+ return null;
106
+ }
107
+ if (!res.body)
108
+ return '';
109
+ const reader = res.body.getReader();
110
+ const decoder = new TextDecoder();
111
+ let bytes = 0;
112
+ let text = '';
113
+ for (;;) {
114
+ const { done, value } = await reader.read();
115
+ if (done)
116
+ break;
117
+ bytes += value.byteLength;
118
+ if (bytes > max) {
119
+ await reader.cancel().catch(() => { });
120
+ return null;
121
+ }
122
+ text += decoder.decode(value, { stream: true });
123
+ }
124
+ return text + decoder.decode();
125
+ }
126
+ /**
127
+ * Whether a failed attempt is retried.
128
+ *
129
+ * A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
130
+ * before any charge), a 503 (the API credits it back), and a connection that was never opened. A timeout, a
131
+ * connection lost mid-request, a 502 and a 504 are NOT retried on a metered route: the API may have served, and
132
+ * charged, the first attempt. A 502 comes from the gateway, not the API, so the API's refund of its own 5xx never
133
+ * ran (a process stopped by a deploy after the charge answers 502), and a retry could be billed twice.
134
+ * A free route costs nothing, so those are retried there too.
135
+ * Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
136
+ */
137
+ function isRetryable(e, metered) {
138
+ if (e instanceof errors_js_1.RateLimitError || e instanceof errors_js_1.ServiceUnavailableError)
139
+ return true;
140
+ if (e instanceof errors_js_1.ConnectionError)
141
+ return !metered || e.connectFailed;
142
+ if (e instanceof errors_js_1.TimeoutError)
143
+ return !metered;
144
+ return e instanceof errors_js_1.APIError && (e.status === 502 || e.status === 504) && !metered;
145
+ }
146
+ /** Error codes that mean no connection was made, so nothing reached the API (Node / undici names). */
147
+ const CONNECT_FAILED_CODES = new Set([
148
+ 'ECONNREFUSED',
149
+ 'ENOTFOUND',
150
+ 'EAI_AGAIN',
151
+ 'ENETUNREACH',
152
+ 'ENETDOWN',
153
+ 'EHOSTUNREACH',
154
+ 'EHOSTDOWN',
155
+ 'UND_ERR_CONNECT_TIMEOUT',
156
+ ]);
157
+ /** Every `code` on the error, its `cause` chain and an `AggregateError`'s `errors` (happy-eyeballs connects). */
158
+ function errorCodes(e, out = [], depth = 0) {
159
+ if (depth > 5 || e === null || typeof e !== 'object')
160
+ return out;
161
+ const o = e;
162
+ if (typeof o.code === 'string')
163
+ out.push(o.code);
164
+ errorCodes(o.cause, out, depth + 1);
165
+ if (Array.isArray(o.errors))
166
+ for (const x of o.errors)
167
+ errorCodes(x, out, depth + 1);
168
+ return out;
169
+ }
170
+ /** True only when every code found says the connection was never opened. No code (e.g. a browser) is false. */
171
+ function connectFailed(e) {
172
+ const codes = errorCodes(e);
173
+ return codes.length > 0 && codes.every((c) => CONNECT_FAILED_CODES.has(c));
174
+ }
175
+ /**
176
+ * One attempt's signal: the caller's abort plus the timeout. Built on `AbortController` and `setTimeout` rather than
177
+ * `AbortSignal.timeout` / `AbortSignal.any`, which some browsers and edge runtimes lack; `done()` clears the timer.
178
+ */
179
+ function attemptSignal(timeoutMs, caller) {
180
+ const ac = new AbortController();
181
+ let timedOut = false;
182
+ const onAbort = () => ac.abort(caller?.reason);
183
+ const timer = setTimeout(() => {
184
+ timedOut = true;
185
+ ac.abort(new DOMException('The operation timed out', 'TimeoutError'));
186
+ }, timeoutMs);
187
+ caller?.addEventListener('abort', onAbort, { once: true });
188
+ return {
189
+ signal: ac.signal,
190
+ timedOut: () => timedOut,
191
+ done: () => {
192
+ clearTimeout(timer);
193
+ caller?.removeEventListener('abort', onAbort);
194
+ },
195
+ };
196
+ }
197
+ function parseJson(text) {
198
+ try {
199
+ return { ok: true, value: JSON.parse(text) };
200
+ }
201
+ catch {
202
+ return { ok: false };
203
+ }
204
+ }
205
+ class Transport {
206
+ #config;
207
+ #userAgent;
208
+ constructor(config) {
209
+ this.#config = config;
210
+ // Browsers forbid or ignore `User-Agent`, and a custom header would force a CORS preflight.
211
+ this.#userAgent = isBrowser() ? undefined : `tickwise-sdk/${version_js_1.VERSION}`;
212
+ }
213
+ get baseUrl() {
214
+ return this.#config.baseUrl;
215
+ }
216
+ async request(req, opts = {}) {
217
+ const cfg = this.#config;
218
+ const url = buildUrl(cfg.baseUrl, req.path, req.query);
219
+ const maxRetries = opts.maxRetries === undefined ? cfg.maxRetries : Math.floor(checkNumber('maxRetries', opts.maxRetries, true));
220
+ const timeoutMs = opts.timeoutMs === undefined ? cfg.timeoutMs : checkNumber('timeoutMs', opts.timeoutMs, false);
221
+ const headers = { Accept: req.accept === 'csv' ? 'text/csv' : 'application/json' };
222
+ if (req.metered && cfg.apiKey)
223
+ headers[cfg.keyHeader] = cfg.apiKey;
224
+ if (this.#userAgent)
225
+ headers['User-Agent'] = this.#userAgent;
226
+ for (let attempt = 0;; attempt++) {
227
+ if (opts.signal?.aborted)
228
+ throw abortReason(opts.signal);
229
+ let error;
230
+ try {
231
+ return await this.#attempt(url, headers, req, attempt, timeoutMs, opts.signal);
232
+ }
233
+ catch (e) {
234
+ if (opts.signal?.aborted)
235
+ throw abortReason(opts.signal);
236
+ if (!(e instanceof errors_js_1.TickwiseError))
237
+ throw e;
238
+ error = e;
239
+ }
240
+ if (attempt >= maxRetries || !isRetryable(error, req.metered))
241
+ throw error;
242
+ let wait;
243
+ if (error.retryAfterSec !== undefined) {
244
+ // A wait longer than the caller allows is handed back rather than slept through.
245
+ if (error.retryAfterSec > cfg.maxRetryAfterSec)
246
+ throw error;
247
+ wait = error.retryAfterSec * 1000;
248
+ }
249
+ else {
250
+ const cap = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
251
+ wait = Math.round((cfg.random ?? Math.random)() * cap);
252
+ }
253
+ await sleep(wait, opts.signal);
254
+ }
255
+ }
256
+ async #attempt(url, headers, req, attempt, timeoutMs, caller) {
257
+ const { signal, timedOut, done } = attemptSignal(timeoutMs, caller);
258
+ try {
259
+ // Redirects are not followed: fetch drops `Authorization` on a cross-host redirect but not a custom header, so
260
+ // following one would hand the key to wherever it points. The API does not redirect.
261
+ const res = await this.#config.fetch(url, { method: 'GET', headers, signal, redirect: 'manual' });
262
+ if (res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400)) {
263
+ await res.body?.cancel().catch(() => { });
264
+ throw new errors_js_1.APIError('redirect', `The API answered with a redirect (${res.status || 'opaque'}); it was not followed`, {
265
+ status: res.status || undefined,
266
+ headers: res.headers,
267
+ url,
268
+ });
269
+ }
270
+ const text = await readText(res, this.#config.maxBodyBytes);
271
+ // An error answer over the cap still gets its own class (and `Retry-After`), so a 429 / 503 is still retried.
272
+ if (text === null && (res.status < 200 || res.status >= 300))
273
+ throw (0, errors_js_1.errorFromResponse)(res.status, res.headers, undefined, url);
274
+ if (text === null) {
275
+ throw new errors_js_1.APIError('api_error', `The response is larger than maxBodyBytes (${this.#config.maxBodyBytes})`, {
276
+ status: res.status,
277
+ headers: res.headers,
278
+ url,
279
+ });
280
+ }
281
+ const parsed = parseJson(text);
282
+ const body = parsed.ok ? parsed.value : text;
283
+ if (res.status < 200 || res.status >= 300)
284
+ throw (0, errors_js_1.errorFromResponse)(res.status, res.headers, body, url);
285
+ const meta = metaOf(res.status, url, attempt, res.headers);
286
+ if (req.accept === 'csv')
287
+ return { body: text, meta };
288
+ if (!parsed.ok) {
289
+ throw new errors_js_1.APIError('api_error', 'The API answered with a body that is not JSON', {
290
+ status: res.status,
291
+ body: text.slice(0, 500),
292
+ headers: res.headers,
293
+ url,
294
+ });
295
+ }
296
+ return { body, meta };
297
+ }
298
+ catch (e) {
299
+ if (e instanceof errors_js_1.TickwiseError)
300
+ throw e;
301
+ if (caller?.aborted)
302
+ throw abortReason(caller);
303
+ if (timedOut()) {
304
+ throw new errors_js_1.TimeoutError(`The Tickwise API did not answer within ${timeoutMs} ms`, { url, cause: e });
305
+ }
306
+ const why = e instanceof Error ? e.message : String(e);
307
+ throw new errors_js_1.ConnectionError(`Could not reach the Tickwise API: ${why}`, { url, cause: e, connectFailed: connectFailed(e) });
308
+ }
309
+ finally {
310
+ done();
311
+ }
312
+ }
313
+ }
314
+ exports.Transport = Transport;