@lgriffin/esi.ts 8.0.0 → 9.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 (153) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/LICENSE +26 -26
  3. package/README.md +988 -967
  4. package/dist/EsiClient.d.ts +4 -0
  5. package/dist/EsiClient.d.ts.map +1 -1
  6. package/dist/clients/AccessListsClient.d.ts +11 -1
  7. package/dist/clients/AccessListsClient.d.ts.map +1 -1
  8. package/dist/clients/CorporationProjectsClient.d.ts +44 -0
  9. package/dist/clients/CorporationProjectsClient.d.ts.map +1 -0
  10. package/dist/clients/MercenaryClient.d.ts +6 -2
  11. package/dist/clients/MercenaryClient.d.ts.map +1 -1
  12. package/dist/clients/MetaClient.d.ts +25 -0
  13. package/dist/clients/MetaClient.d.ts.map +1 -1
  14. package/dist/clients/MilitaryCampaignsClient.d.ts +53 -0
  15. package/dist/clients/MilitaryCampaignsClient.d.ts.map +1 -0
  16. package/dist/clients/SkyhooksClient.d.ts +6 -2
  17. package/dist/clients/SkyhooksClient.d.ts.map +1 -1
  18. package/dist/config/jest/globalSetup.d.ts.map +1 -1
  19. package/dist/config/jest/globalTeardown.d.ts.map +1 -1
  20. package/dist/core/ClientRegistry.d.ts +5 -3
  21. package/dist/core/ClientRegistry.d.ts.map +1 -1
  22. package/dist/core/configureApiClient.d.ts.map +1 -1
  23. package/dist/core/constants.d.ts +2 -2
  24. package/dist/core/endpoints/accessListEndpoints.d.ts +34 -11
  25. package/dist/core/endpoints/accessListEndpoints.d.ts.map +1 -1
  26. package/dist/core/endpoints/corporationProjectEndpoints.d.ts +50 -0
  27. package/dist/core/endpoints/corporationProjectEndpoints.d.ts.map +1 -0
  28. package/dist/core/endpoints/industryEndpoints.d.ts +3 -3
  29. package/dist/core/endpoints/mercenaryEndpoints.d.ts +6 -4
  30. package/dist/core/endpoints/mercenaryEndpoints.d.ts.map +1 -1
  31. package/dist/core/endpoints/metaEndpoints.d.ts +36 -0
  32. package/dist/core/endpoints/metaEndpoints.d.ts.map +1 -1
  33. package/dist/core/endpoints/militaryCampaignEndpoints.d.ts +87 -0
  34. package/dist/core/endpoints/militaryCampaignEndpoints.d.ts.map +1 -0
  35. package/dist/core/endpoints/skyhookEndpoints.d.ts +7 -5
  36. package/dist/core/endpoints/skyhookEndpoints.d.ts.map +1 -1
  37. package/dist/core/pagination/CursorPaginationHandler.d.ts +9 -4
  38. package/dist/core/pagination/CursorPaginationHandler.d.ts.map +1 -1
  39. package/dist/core/pagination/PaginationHandler.d.ts +6 -5
  40. package/dist/core/pagination/PaginationHandler.d.ts.map +1 -1
  41. package/dist/core/requestPipeline/cachePolicy.d.ts +1 -0
  42. package/dist/core/requestPipeline/cachePolicy.d.ts.map +1 -1
  43. package/dist/core/requestPipeline/paginationOrchestration.d.ts.map +1 -1
  44. package/dist/core/requestPipeline/statusHandling.d.ts.map +1 -1
  45. package/dist/core/util/error.d.ts +2 -0
  46. package/dist/core/util/error.d.ts.map +1 -1
  47. package/dist/errors.d.ts +4 -0
  48. package/dist/errors.d.ts.map +1 -0
  49. package/dist/errors.js +196 -0
  50. package/dist/errors.js.map +1 -0
  51. package/dist/errors.mjs +146 -0
  52. package/dist/errors.mjs.map +1 -0
  53. package/dist/index.d.ts +3 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +1862 -1463
  56. package/dist/index.js.map +1 -1
  57. package/dist/index.mjs +1859 -1463
  58. package/dist/index.mjs.map +1 -1
  59. package/dist/schemas/corporation-projects.d.ts +17 -0
  60. package/dist/schemas/corporation-projects.d.ts.map +1 -0
  61. package/dist/schemas/index.d.ts +3 -0
  62. package/dist/schemas/index.d.ts.map +1 -1
  63. package/dist/schemas/index.js +2177 -0
  64. package/dist/schemas/index.js.map +1 -0
  65. package/dist/schemas/index.mjs +1993 -0
  66. package/dist/schemas/index.mjs.map +1 -0
  67. package/dist/schemas/meta.d.ts +25 -0
  68. package/dist/schemas/meta.d.ts.map +1 -0
  69. package/dist/schemas/military-campaigns.d.ts +26 -0
  70. package/dist/schemas/military-campaigns.d.ts.map +1 -0
  71. package/dist/testing/index.d.ts +2 -0
  72. package/dist/testing/index.d.ts.map +1 -0
  73. package/dist/testing/index.js +935 -0
  74. package/dist/testing/index.js.map +1 -0
  75. package/dist/testing/index.mjs +898 -0
  76. package/dist/testing/index.mjs.map +1 -0
  77. package/dist/types/api-responses.d.ts +3 -0
  78. package/dist/types/api-responses.d.ts.map +1 -1
  79. package/dist/types/corporation-projects.d.ts +6 -0
  80. package/dist/types/corporation-projects.d.ts.map +1 -0
  81. package/dist/types/generated/esi-spec.generated.d.ts +3 -3
  82. package/dist/types/generated/esi-spec.generated.d.ts.map +1 -1
  83. package/dist/types/meta.d.ts +8 -0
  84. package/dist/types/meta.d.ts.map +1 -0
  85. package/dist/types/military-campaigns.d.ts +6 -0
  86. package/dist/types/military-campaigns.d.ts.map +1 -0
  87. package/package.json +257 -235
  88. package/dist/schemas/generated/alliance.generated.d.ts +0 -15
  89. package/dist/schemas/generated/alliance.generated.d.ts.map +0 -1
  90. package/dist/schemas/generated/assets.generated.d.ts +0 -272
  91. package/dist/schemas/generated/assets.generated.d.ts.map +0 -1
  92. package/dist/schemas/generated/calendar.generated.d.ts +0 -41
  93. package/dist/schemas/generated/calendar.generated.d.ts.map +0 -1
  94. package/dist/schemas/generated/character.generated.d.ts +0 -670
  95. package/dist/schemas/generated/character.generated.d.ts.map +0 -1
  96. package/dist/schemas/generated/clones.generated.d.ts +0 -23
  97. package/dist/schemas/generated/clones.generated.d.ts.map +0 -1
  98. package/dist/schemas/generated/contacts.generated.d.ts +0 -50
  99. package/dist/schemas/generated/contacts.generated.d.ts.map +0 -1
  100. package/dist/schemas/generated/contracts.generated.d.ts +0 -162
  101. package/dist/schemas/generated/contracts.generated.d.ts.map +0 -1
  102. package/dist/schemas/generated/corporation-projects.generated.d.ts +0 -89
  103. package/dist/schemas/generated/corporation-projects.generated.d.ts.map +0 -1
  104. package/dist/schemas/generated/corporation.generated.d.ts +0 -1515
  105. package/dist/schemas/generated/corporation.generated.d.ts.map +0 -1
  106. package/dist/schemas/generated/dogma.generated.d.ts +0 -57
  107. package/dist/schemas/generated/dogma.generated.d.ts.map +0 -1
  108. package/dist/schemas/generated/faction-warfare.generated.d.ts +0 -155
  109. package/dist/schemas/generated/faction-warfare.generated.d.ts.map +0 -1
  110. package/dist/schemas/generated/fittings.generated.d.ts +0 -57
  111. package/dist/schemas/generated/fittings.generated.d.ts.map +0 -1
  112. package/dist/schemas/generated/fleets.generated.d.ts +0 -45
  113. package/dist/schemas/generated/fleets.generated.d.ts.map +0 -1
  114. package/dist/schemas/generated/freelance-jobs.generated.d.ts +0 -173
  115. package/dist/schemas/generated/freelance-jobs.generated.d.ts.map +0 -1
  116. package/dist/schemas/generated/incursions.generated.d.ts +0 -16
  117. package/dist/schemas/generated/incursions.generated.d.ts.map +0 -1
  118. package/dist/schemas/generated/index.d.ts +0 -33
  119. package/dist/schemas/generated/index.d.ts.map +0 -1
  120. package/dist/schemas/generated/industry.generated.d.ts +0 -117
  121. package/dist/schemas/generated/industry.generated.d.ts.map +0 -1
  122. package/dist/schemas/generated/insurance.generated.d.ts +0 -10
  123. package/dist/schemas/generated/insurance.generated.d.ts.map +0 -1
  124. package/dist/schemas/generated/killmails.generated.d.ts +0 -55
  125. package/dist/schemas/generated/killmails.generated.d.ts.map +0 -1
  126. package/dist/schemas/generated/location.generated.d.ts +0 -18
  127. package/dist/schemas/generated/location.generated.d.ts.map +0 -1
  128. package/dist/schemas/generated/loyalty.generated.d.ts +0 -18
  129. package/dist/schemas/generated/loyalty.generated.d.ts.map +0 -1
  130. package/dist/schemas/generated/mail.generated.d.ts +0 -68
  131. package/dist/schemas/generated/mail.generated.d.ts.map +0 -1
  132. package/dist/schemas/generated/market.generated.d.ts +0 -201
  133. package/dist/schemas/generated/market.generated.d.ts.map +0 -1
  134. package/dist/schemas/generated/meta.generated.d.ts +0 -26
  135. package/dist/schemas/generated/meta.generated.d.ts.map +0 -1
  136. package/dist/schemas/generated/planetary-interaction.generated.d.ts +0 -90
  137. package/dist/schemas/generated/planetary-interaction.generated.d.ts.map +0 -1
  138. package/dist/schemas/generated/routes.generated.d.ts +0 -5
  139. package/dist/schemas/generated/routes.generated.d.ts.map +0 -1
  140. package/dist/schemas/generated/search.generated.d.ts +0 -15
  141. package/dist/schemas/generated/search.generated.d.ts.map +0 -1
  142. package/dist/schemas/generated/skills.generated.d.ts +0 -32
  143. package/dist/schemas/generated/skills.generated.d.ts.map +0 -1
  144. package/dist/schemas/generated/sovereignty.generated.d.ts +0 -37
  145. package/dist/schemas/generated/sovereignty.generated.d.ts.map +0 -1
  146. package/dist/schemas/generated/status.generated.d.ts +0 -8
  147. package/dist/schemas/generated/status.generated.d.ts.map +0 -1
  148. package/dist/schemas/generated/universe.generated.d.ts +0 -394
  149. package/dist/schemas/generated/universe.generated.d.ts.map +0 -1
  150. package/dist/schemas/generated/wallet.generated.d.ts +0 -411
  151. package/dist/schemas/generated/wallet.generated.d.ts.map +0 -1
  152. package/dist/schemas/generated/wars.generated.d.ts +0 -31
  153. package/dist/schemas/generated/wars.generated.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,967 +1,988 @@
1
- # ESI.ts
2
-
3
- [![npm version](https://badge.fury.io/js/%40lgriffin%2Fesi.ts.svg)](https://badge.fury.io/js/%40lgriffin%2Fesi.ts)
4
- [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-6.0%2B-blue)](https://www.typescriptlang.org/)
6
- [![CI/CD Pipeline](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml/badge.svg)](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml)
7
- [![PR Validation](https://github.com/lgriffin/ESI.ts/actions/workflows/pr-validation.yml/badge.svg)](https://github.com/lgriffin/ESI.ts/actions/workflows/pr-validation.yml)
8
- [![Coverage](https://img.shields.io/badge/coverage-90%25%2B-brightgreen)](https://github.com/lgriffin/ESI.ts)
9
- [![npm downloads](https://img.shields.io/npm/dm/%40lgriffin/esi.ts)](https://www.npmjs.com/package/@lgriffin/esi.ts)
10
-
11
- A production-grade TypeScript client for the [EVE Online ESI API](https://esi.evetech.net/), built on the **OpenAPI 3.1 spec**, with runtime validation, intelligent caching, and full endpoint coverage.
12
-
13
- **v8.0.0** — Architecture overhaul: unified client construction (all three client surfaces now get identical middleware defaults via `configureApiClient()`), decomposed request pipeline (`requestPipeline/` modules), 57 new streaming methods across 16 domain clients, opt-in request body validation, injectable `IRetryStrategy`, configurable circuit breaker keying, and typed `createClient()` return types.
14
-
15
- **208 endpoint definitions — 194 from the public ESI OpenAPI spec, plus 14 for newer EVE features (Equinox sovereignty, orbital skyhooks, mercenary dens, access lists, freelance jobs). All 206 exercisable endpoints validated against live Tranquility on 2026-07-08.**
16
-
17
- ## Why ESI.ts vs. OpenAPI-Generated Clients?
18
-
19
- Tools like `openapi-typescript` or `openapi-generator` can produce a typed client from the ESI OpenAPI spec in minutes. They're a reasonable starting point — but they stop at type generation. ESI.ts is a purpose-built SDK that handles the problems you hit _after_ the types compile.
20
-
21
- ### What generators give you
22
-
23
- - TypeScript interfaces from the OpenAPI spec
24
- - Basic request/response typing
25
- - A thin HTTP wrapper
26
-
27
- ### What ESI.ts gives you on top of that
28
-
29
- | Capability | openapi-typescript | ESI.ts |
30
- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
31
- | **Runtime response validation** | None — types are erased at compile time. If CCP changes a field, you get silent data corruption. | Every GET response is validated at runtime via [Zod](https://zod.dev/) schemas — all 173 GET endpoints have schemas. Schema mismatches throw `EsiValidationError` immediately. |
32
- | **Intelligent caching** | None — you build your own. | Three-tier: spec-aware TTL (zero HTTP calls within ESI's `x-cached-seconds` window), ETag conditional GETs, stale-on-error fallback on 5xx. Write operations auto-invalidate related GET caches. |
33
- | **Rate limiting** | None — you build your own. | 36 per-group token buckets extracted from the ESI spec at build time. Market requests can't starve wallet requests. Optional per-user bucketing for multi-character apps. |
34
- | **Pagination** | Manual — you write the page loop. | Automatic offset pagination, cursor-based pagination (Equinox-era endpoints), and streaming `AsyncGenerator` pagination for memory-efficient processing of large datasets. |
35
- | **Retry & resilience** | None. | Exponential backoff with jitter, circuit breaker (closed/open/half-open), automatic 401 token refresh with concurrent coalescing. |
36
- | **Wire format correctness** | Generates from spec, but ESI's spec has inconsistencies (query params documented as body, missing required fields). | Every endpoint tested against live ESI. Wire format bugs (query params vs. body, field naming) are caught and fixed — see the contacts and UI endpoint fixes in v6.1.0. |
37
- | **Batch operations** | None. | `batch()` with bounded concurrency for GET fan-out, `batchPost()` with auto-chunking for large POST payloads. |
38
- | **Domain knowledge** | None — generic HTTP client. | 35 domain clients with typed methods, JSDoc documentation, and input validation (e.g., fleet wing/squad names are capped at 10 characters before hitting the API). |
39
- | **Streaming pagination** | None. | 21 domain clients with 73+ `stream*` methods via `AsyncGenerator` — process large datasets page-by-page without loading everything into memory. |
40
- | **Testing** | Whatever you write. | 95+ test suites, 3,800+ tests across 9 tiers including property-based fuzzing (fast-check), mutation testing (Stryker), deep contract tests against live OpenAPI spec, and consumer type tests (tsd). 43 runnable example scripts. |
41
-
42
- ### The real problem with generated clients
43
-
44
- The ESI OpenAPI spec is not a perfect source of truth. During live endpoint validation against the OpenAPI 3.1 spec, we discovered:
45
-
46
- - `addContacts`, `editContacts`, and 4 UI endpoints document parameters as request body when ESI actually expects query parameters
47
- - `deleteCharacterContacts` expects comma-separated contact IDs as a query param, not a JSON body
48
- - Fleet wing/squad names have a 10-character limit not documented in the spec
49
- - The `updateMailMetadata` endpoint uses the field name `read`, not `is_read`
50
-
51
- A generated client faithfully reproduces these spec bugs. ESI.ts fixes them.
52
-
53
- ## Installation
54
-
55
- ```bash
56
- npm install @lgriffin/esi.ts
57
- ```
58
-
59
- ### Building from Source
60
-
61
- ```bash
62
- git clone https://github.com/lgriffin/ESI.ts.git
63
- cd ESI.ts
64
- npm install # installs dependencies and compiles (via the prepare script)
65
- ```
66
-
67
- If you've already installed and just need to recompile:
68
-
69
- ```bash
70
- npm run build
71
- ```
72
-
73
- Verify everything works:
74
-
75
- ```bash
76
- npm run example:status # quick smoke test — checks ESI is reachable
77
- npm test # run the full test suite (95+ suites, 3,800+ tests)
78
- ```
79
-
80
- ## Quick Start
81
-
82
- ```typescript
83
- import { EsiClient } from '@lgriffin/esi.ts';
84
-
85
- const client = new EsiClient();
86
-
87
- // Public data — no auth required
88
- const alliances = await client.alliance.getAlliances();
89
- const character = await client.characters.getCharacterPublicInfo(1689391488);
90
- const system = await client.universe.getSystemById(30000142);
91
- const prices = await client.market.getMarketPrices();
92
-
93
- // Authenticated data — token read from ESI_ACCESS_TOKEN env var
94
- const authedClient = new EsiClient();
95
- const assets = await authedClient.assets.getCharacterAssets(characterId);
96
- const wallet = await authedClient.wallet.getCharacterWallet(characterId);
97
-
98
- // Clean up when done
99
- await client.shutdown();
100
- ```
101
-
102
- ## Configuration
103
-
104
- ```typescript
105
- const client = new EsiClient({
106
- clientId: 'my-app', // User-Agent identifier (default: 'esi-client')
107
- accessToken: 'your-token', // EVE SSO token for authenticated endpoints
108
- baseUrl: 'https://esi.evetech.net', // ESI base URL (default)
109
- onTokenRefresh: async () => newToken, // Auto-refresh on 401 (optional)
110
- language: 'en', // Accept-Language header: en, de, fr, ja, ru, zh, ko, es (default: none)
111
- timeout: 30000, // Request timeout in ms (default: 30000)
112
- retryConfig: {
113
- maxRetries: 3, // Max retry attempts for transient errors (default: 0)
114
- baseDelayMs: 1000, // Initial backoff delay (default: 1000)
115
- maxDelayMs: 30000, // Maximum backoff delay (default: 30000)
116
- retryMutations: false, // Retry POST/PUT/DELETE (default: false, GET only)
117
- },
118
- enableETagCache: true, // ETag caching (default: true)
119
- etagCacheConfig: {
120
- maxEntries: 1000, // Max cached responses (default: 1000)
121
- defaultTtl: 300000, // Fallback TTL in ms (default: 5 min)
122
- cleanupInterval: 60000, // Expired entry cleanup interval (default: 1 min)
123
- },
124
- validateResponse: true, // Runtime Zod validation of ESI responses (default: true)
125
- validateRequest: false, // Opt-in request body Zod validation for POST/PUT/DELETE (default: false)
126
- retryStrategy: customRetryStrategy, // Injectable IRetryStrategy (default: built-in exponential backoff)
127
- circuitBreakerConfig: {
128
- keyStrategy: 'resolved', // CB keying: 'resolved' (per-URL) or 'template' (per-route) (default: 'resolved')
129
- cleanupIntervalMs: 300000, // Automatic stale circuit cleanup interval (default: 5 min)
130
- },
131
- });
132
- ```
133
-
134
- Retry is disabled by default (`maxRetries: 0`). When enabled, transient errors (502, 503, 504, timeout, rate limit) are retried with exponential backoff and jitter. The circuit breaker is respected — requests are not retried when the circuit is open.
135
-
136
- The access token can be updated at runtime:
137
-
138
- ```typescript
139
- client.setAccessToken('new-token');
140
- ```
141
-
142
- ## Authentication
143
-
144
- Many ESI endpoints require an EVE SSO access token. There are three ways to provide one:
145
-
146
- ### 1. Environment variable (recommended)
147
-
148
- Set `ESI_ACCESS_TOKEN` in your environment or a `.env` file. The client reads it automatically — no token in source code.
149
-
150
- ```bash
151
- # Copy the example and fill in your token
152
- cp .env.example .env
153
- ```
154
-
155
- ```env
156
- ESI_ACCESS_TOKEN=your-eve-sso-access-token
157
- ESI_CLIENT_ID=my-app-name
158
- ```
159
-
160
- If you use a `.env` loader like [dotenv](https://www.npmjs.com/package/dotenv), load it before creating the client:
161
-
162
- ```typescript
163
- import 'dotenv/config';
164
- import { EsiClient } from '@lgriffin/esi.ts';
165
-
166
- const client = new EsiClient();
167
- // Token is picked up from process.env.ESI_ACCESS_TOKEN
168
- ```
169
-
170
- ### 2. Constructor parameter
171
-
172
- Pass the token directly (useful for apps that manage tokens themselves):
173
-
174
- ```typescript
175
- const client = new EsiClient({ accessToken: token });
176
- ```
177
-
178
- ### 3. Runtime update
179
-
180
- Set or refresh the token after construction:
181
-
182
- ```typescript
183
- client.setAccessToken(newToken);
184
- ```
185
-
186
- ### Getting an EVE SSO token
187
-
188
- 1. Register an application at [EVE Developers](https://developers.eveonline.com/)
189
- 2. Set a callback URL and select the ESI scopes your app needs
190
- 3. Implement the [OAuth2 flow](https://docs.esi.evetech.net/docs/sso/) to obtain an access token
191
- 4. Access tokens expire — use the refresh token to get new ones
192
-
193
- ### Automatic Token Refresh
194
-
195
- EVE SSO access tokens expire after 20 minutes. Instead of manually tracking expiry, you can provide a refresh callback — the client will automatically call it on 401, update the token, and retry the request:
196
-
197
- ```typescript
198
- const client = new EsiClient({
199
- accessToken: initialToken,
200
- onTokenRefresh: async () => {
201
- const response = await fetch('https://login.eveonline.com/v2/oauth/token', {
202
- method: 'POST',
203
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
204
- body: new URLSearchParams({
205
- grant_type: 'refresh_token',
206
- refresh_token: myRefreshToken,
207
- client_id: myClientId,
208
- }),
209
- });
210
- const { access_token } = await response.json();
211
- return access_token;
212
- },
213
- });
214
-
215
- // Requests now auto-refresh on 401 — no manual token management needed
216
- const location = await client.location.getCharacterLocation(characterId);
217
- ```
218
-
219
- The token provider can also be set or changed at runtime:
220
-
221
- ```typescript
222
- client.setTokenProvider(myRefreshFunction);
223
- client.setTokenProvider(undefined); // disable auto-refresh
224
- ```
225
-
226
- Key behaviors:
227
-
228
- - Only retries **once** per request — if the refreshed token also gets a 401, the error is thrown
229
- - **Concurrent coalescing** — if multiple requests hit 401 simultaneously, only one refresh call is made
230
- - If the refresh callback throws (e.g., refresh token revoked), a `TOKEN_REFRESH_FAILED` error is raised
231
- - Without a token provider, 401 errors throw immediately as before
232
-
233
- ### Environment variables reference
234
-
235
- | Variable | Description | Default |
236
- | ------------------ | -------------------------------------------- | ------------------------- |
237
- | `ESI_ACCESS_TOKEN` | EVE SSO access token | none |
238
- | `ESI_CLIENT_ID` | User-Agent identifier | `esi-client` |
239
- | `ESI_BASE_URL` | ESI API base URL | `https://esi.evetech.net` |
240
- | `ESI_LOG_LEVEL` | Log level (`error`, `warn`, `info`, `debug`) | `warn` |
241
-
242
- ## Available APIs
243
-
244
- All clients are accessed as properties on the `EsiClient` instance. Authenticated endpoints require an access token.
245
-
246
- | Client | Property | Auth | Examples |
247
- | -------------- | ---------------------- | ---- | -------------------------------------------------------------------------------- |
248
- | Alliance | `client.alliance` | Some | `getAlliances()`, `getAllianceById(id)` |
249
- | Assets | `client.assets` | Yes | `getCharacterAssets(id)` |
250
- | Calendar | `client.calendar` | Yes | `getCalendarEvents(id)` |
251
- | Characters | `client.characters` | Some | `getCharacterPublicInfo(id)`, `getCharacterPortrait(id)` |
252
- | Clones | `client.clones` | Yes | `getCharacterClones(id)` |
253
- | Contacts | `client.contacts` | Yes | `getCharacterContacts(id)`, `postCharacterContacts(id, standing, contactIds)` |
254
- | Contracts | `client.contracts` | Yes | `getCharacterContracts(id)` |
255
- | Corporations | `client.corporations` | Some | `getCorporationInfo(id)`, `getCorporationMembers(id)` |
256
- | Dogma | `client.dogma` | No | `getDogmaAttributes()`, `getDynamicItemInfo(typeId, itemId)` |
257
- | Factions | `client.factions` | Some | `getFactionWarStats()` |
258
- | Fittings | `client.fittings` | Yes | `getFittings(id)`, `createFitting(id, body)` |
259
- | Fleets | `client.fleets` | Yes | `getFleetInformation(id)`, `getFleetMembers(id)` |
260
- | Incursions | `client.incursions` | No | `getIncursions()` |
261
- | Industry | `client.industry` | Some | `getCharacterIndustryJobs(id)` |
262
- | Insurance | `client.insurance` | No | `getInsurancePrices()` |
263
- | Killmails | `client.killmails` | Some | `getKillmail(id, hash)` |
264
- | Location | `client.location` | Yes | `getCharacterLocation(id)` |
265
- | Loyalty | `client.loyalty` | Yes | `getCharacterLoyaltyPoints(id)` |
266
- | Mail | `client.mail` | Yes | `getCharacterMail(id)`, `sendMail(id, body)` |
267
- | Market | `client.market` | Some | `getMarketPrices()`, `getMarketOrders(regionId)` |
268
- | PI | `client.pi` | Yes | `getCharacterPlanets(id)` |
269
- | Route | `client.route` | No | `getRoute(origin, destination)` |
270
- | Search | `client.search` | Some | `search(characterId, query)` |
271
- | Skills | `client.skills` | Yes | `getCharacterSkills(id)` |
272
- | Sovereignty | `client.sovereignty` | No | `getSovereigntySystems()`, `getSovereigntyMap()` |
273
- | Skyhooks | `client.skyhooks` | No | `getSovereigntyHubs()`, `getRaidableSkyhooks()` |
274
- | Mercenary | `client.mercenary` | No | `getMercenaryDens()`, `getMercenaryTacticalOperations()` |
275
- | Access Lists | `client.accessLists` | Yes | `getAccessList(id)` |
276
- | Status | `client.status` | No | `getStatus()` |
277
- | UI | `client.ui` | Yes | `setAutopilotWaypoint(destId, addToBeginning, clear)`, `openNewMailWindow(body)` |
278
- | Universe | `client.universe` | Some | `getSystemById(id)`, `getTypeById(id)` |
279
- | Wallet | `client.wallet` | Yes | `getCharacterWallet(id)` |
280
- | Wars | `client.wars` | No | `getWars()`, `getWarById(id)` |
281
- | Freelance Jobs | `client.freelanceJobs` | Some | `getFreelanceJobs()`, `getFreelanceJobById(id)` |
282
- | Meta | `client.meta` | No | `getOpenApiJson()`, `getOpenApiYaml()` |
283
-
284
- ## Runtime Response Validation
285
-
286
- ESI.ts validates API responses at runtime using [Zod](https://zod.dev/) schemas. All GET endpoints have schemas — these are the endpoints that return data your application consumes, where a silent shape change from CCP would cause bugs. POST/PUT/DELETE mutations typically return `204 No Content` (no body to validate) or simple confirmation values, so schemas are omitted where there is nothing meaningful to validate.
287
-
288
- Validation is **on by default**. Extra fields from ESI are preserved via `z.looseObject()` passthrough mode, so new fields added by CCP won't break your application — they flow through to your code untouched.
289
-
290
- ```typescript
291
- import {
292
- EsiClient,
293
- EsiValidationError,
294
- isValidationError,
295
- schemas,
296
- } from '@lgriffin/esi.ts';
297
-
298
- const client = new EsiClient();
299
-
300
- // Validation happens automatically on every request
301
- const character = await client.characters.getCharacterPublicInfo(12345);
302
-
303
- // Disable validation globally if needed
304
- const rawClient = new EsiClient({ validateResponse: false });
305
-
306
- // Use schemas directly for your own validation
307
- const result = schemas.CharacterInfoSchema.safeParse(someData);
308
- if (result.success) {
309
- console.log(result.data.name);
310
- }
311
- ```
312
-
313
- ### Request Body Validation
314
-
315
- For POST/PUT/DELETE endpoints, opt-in request body validation ensures outgoing payloads match the endpoint's `requestSchema` before the request is sent:
316
-
317
- ```typescript
318
- // Opt-in request body validation for POST/PUT/DELETE
319
- const client = new EsiClient({ validateRequest: true });
320
-
321
- // Throws EsiValidationError if the request body doesn't match the endpoint's requestSchema
322
- await client.mail.sendMail(characterId, {
323
- recipients: [{ recipient_id: 12345, recipient_type: 'character' }],
324
- subject: 'Hello',
325
- body: 'Message body',
326
- });
327
- ```
328
-
329
- See [guides/RUNTIME-VALIDATION.md](guides/RUNTIME-VALIDATION.md) for the full guide on schemas, error handling, and extending schemas.
330
-
331
- ## Caching
332
-
333
- ETag caching is enabled by default. The client automatically:
334
-
335
- 1. Stores ETag and response data on GET requests
336
- 2. Sends `If-None-Match` on subsequent requests
337
- 3. Returns cached data on `304 Not Modified`
338
- 4. Parses `Cache-Control: max-age` from ESI for per-endpoint TTL
339
- 5. Serves stale cached data when ESI returns 5xx errors
340
- 6. Invalidates related GET caches when POST/PUT/DELETE requests are made
341
-
342
- ```typescript
343
- // Cache stats
344
- const stats = client.getCacheStats();
345
- console.log(`${stats.totalEntries}/${stats.maxEntries} entries cached`);
346
-
347
- // Manual cache operations
348
- client.clearCache();
349
- client.updateCacheConfig({ maxEntries: 2000 });
350
-
351
- // Disable caching entirely
352
- const uncachedClient = new EsiClient({ enableETagCache: false });
353
- ```
354
-
355
- ### Spec-Aware Cache TTLs
356
-
357
- The library reads `x-cache-age` from the ESI OpenAPI spec (126 of 195 endpoints). Within the TTL window, repeated GET requests return cached data with **zero HTTP calls** — not even a conditional GET.
358
-
359
- This layers on top of ETag caching in three tiers:
360
-
361
- 1. **Spec TTL** — data can't have changed yet, return cached data immediately
362
- 2. **ETag conditional GET** — data might have changed, send `If-None-Match` to check
363
- 3. **Full request** — no cache entry, fetch fresh data
364
-
365
- ```typescript
366
- const client = new EsiClient();
367
-
368
- // First call — fetches from ESI
369
- const alliances = await client.alliance.getAlliances();
370
-
371
- // Second call within the next 3600s — returns cached data, zero HTTP calls
372
- const same = await client.alliance.getAlliances();
373
- ```
374
-
375
- ## Batch Requests
376
-
377
- Fetch data for multiple IDs with bounded concurrency using `batch()`, or chunk large POST payloads with `batchPost()`:
378
-
379
- ```typescript
380
- import { EsiClient } from '@lgriffin/esi.ts';
381
-
382
- const client = new EsiClient();
383
-
384
- // Fetch 500 type details with at most 10 concurrent requests
385
- const result = await client.batch(
386
- typeIds,
387
- (id) => client.universe.getTypeById(id),
388
- {
389
- concurrency: 10,
390
- onProgress: (done, total) => console.log(`${done}/${total}`),
391
- },
392
- );
393
-
394
- // result.results: Map<number, T> — successful responses
395
- // result.errors: Map<number, Error> — failed requests
396
- console.log(`${result.results.size} succeeded, ${result.errors.size} failed`);
397
- ```
398
-
399
- For POST endpoints that accept arrays (e.g., `postUniverseNames` with a 1000-ID limit), `batchPost` auto-chunks and concatenates:
400
-
401
- ```typescript
402
- const allNames = await client.batchPost(
403
- largeIdArray,
404
- (chunk) => client.universe.postUniverseNames(chunk),
405
- 1000, // chunk size
406
- );
407
- ```
408
-
409
- ## Streaming Pagination
410
-
411
- For large paginated endpoints (market orders, contracts, assets), streaming yields one page at a time via `AsyncGenerator` instead of eagerly fetching all pages into memory:
412
-
413
- ```typescript
414
- import { EsiClient } from '@lgriffin/esi.ts';
415
-
416
- const client = new EsiClient();
417
-
418
- // Stream all market orders in The Forge, page by page
419
- for await (const page of client.market.streamMarketOrders(10000002)) {
420
- console.log(
421
- `Page ${page.page}/${page.totalPages}: ${page.data.length} orders`,
422
- );
423
-
424
- // Process each order as it arrives
425
- for (const order of page.data) {
426
- if (order.is_buy_order && order.price > 1_000_000) {
427
- console.log(`High-value buy: ${order.type_id} @ ${order.price} ISK`);
428
- }
429
- }
430
-
431
- // Early termination — stops fetching remaining pages
432
- if (page.page >= 3) break;
433
- }
434
- ```
435
-
436
- 21 domain clients expose 73+ streaming methods. `BaseEsiClient.streamEndpoint()` is also public as an escape hatch for any paginated endpoint not yet wrapped with a convenience method.
437
-
438
- Available streaming methods (representative selection):
439
-
440
- - **MarketClient** — `streamMarketOrders`, `streamMarketTypes`, `streamCharacterOrderHistory`, `streamCorporationOrders`, `streamCorporationOrderHistory`, `streamMarketOrdersInStructure`
441
- - **CorporationsClient** — `streamCorporationMembers`, `streamCorporationStructures`, `streamCorporationBlueprints`, + 14 more
442
- - **CharacterClient** — `streamCharacterBlueprints`, `streamCharacterNotifications`, `streamCharacterStandings`, + 5 more
443
- - **ContractsClient** — `streamPublicContracts`, `streamCharacterContracts`, `streamCorporationContracts`
444
- - **WalletClient** — `streamCharacterWalletJournal`, `streamCorporationWalletJournal`, `streamCharacterWalletTransactions`
445
- - **IndustryClient** — `streamCorporationIndustryJobs`, `streamCorporationMiningObservers`, + 6 more
446
- - **ContactsClient** — `streamAllianceContacts`, `streamCharacterContacts`, `streamCorporationContacts`, + 3 more
447
- - **AssetsClient** — `streamCharacterAssets`, `streamCorporationAssets`
448
- - **KillmailsClient** — `streamCharacterRecentKillmails`, `streamCorporationRecentKillmails`
449
- - **MailClient** — `streamCharacterMail`, `streamCharacterMailLabels`
450
- - **FleetsClient** — `streamFleetMembers`, `streamFleetWings`
451
- - **CalendarClient** — `streamCalendarEvents`
452
- - **FittingsClient** — `streamCharacterFittings`
453
- - **SkillsClient** — `streamCharacterSkillQueue`
454
- - **LoyaltyClient** — `streamCorporationLoyaltyStoreOffers`
455
- - **BookmarksClient** — `streamCharacterBookmarks`, `streamCorporationBookmarks`
456
- - **ClonesClient** — `streamCharacterImplants`
457
- - **PIClient** — `streamCharacterPlanets`
458
- - **WarsClient** — `streamWars`
459
- - **FactionWarfareClient** — `streamFactionWarfareStats`
460
- - **AllianceClient** — `streamAllianceCorporations`
461
-
462
- Try it: `npm run example:streaming`
463
-
464
- ## Cursor-based Pagination
465
-
466
- Newer ESI routes (Freelance Jobs, and future routes) use cursor-based pagination with opaque `before`/`after` tokens in the response body. See the [ESI blog post](https://developers.eveonline.com/blog/changing-pagination-turning-a-new-page) for background.
467
-
468
- ```typescript
469
- import { EsiClient, fetchAllCursorPages } from '@lgriffin/esi.ts';
470
-
471
- const client = new EsiClient();
472
-
473
- // Fetch first page — returns { cursor: { before, after }, freelance_jobs: [...] }
474
- const page = await client.freelanceJobs.getFreelanceJobs();
475
- console.log(page.freelance_jobs); // job records
476
- console.log(page.cursor.after); // opaque token for next page
477
-
478
- // Fetch next page using the cursor
479
- const nextPage = await client.freelanceJobs.getFreelanceJobs(
480
- undefined,
481
- page.cursor.after,
482
- );
483
-
484
- // Auto-fetch all pages in one call
485
- const allJobs = await fetchAllCursorPages(
486
- (before, after) => client.freelanceJobs.getFreelanceJobs(before, after),
487
- (response) => response.freelance_jobs,
488
- (response) => response.cursor,
489
- );
490
-
491
- // Authenticated endpoints — character/corporation freelance jobs
492
- const authedClient = new EsiClient({ accessToken: 'your-token' });
493
- const myJobs =
494
- await authedClient.freelanceJobs.getCharacterFreelanceJobs(characterId);
495
- const corpJobs =
496
- await authedClient.freelanceJobs.getCorporationFreelanceJobs(corporationId);
497
- ```
498
-
499
- **Polling for changes** — cursor tokens persist across sessions, so you can save the last `after` token and poll later to get only records that changed:
500
-
501
- ```typescript
502
- // After initial scan, save the final cursor
503
- let savedCursor = lastPage.cursor.after;
504
-
505
- // Later: check for updates (hours, days, or weeks later)
506
- const updates = await client.freelanceJobs.getFreelanceJobs(
507
- undefined,
508
- savedCursor,
509
- );
510
- if (updates.freelance_jobs.length > 0) {
511
- // Process changed records — duplicates are expected for modified records
512
- savedCursor = updates.cursor.after;
513
- }
514
- ```
515
-
516
- Key points:
517
-
518
- - Cursor tokens are **opaque strings** — never parse or validate them
519
- - An **empty result array** signals the end of the dataset (not a short page)
520
- - **Duplicates across pages** are expected when records are modified between requests
521
- - Existing offset-based routes (`getMarketOrders`, etc.) are unchanged
522
-
523
- ## Generated Types
524
-
525
- The library includes TypeScript interfaces generated directly from the ESI OpenAPI 3.1 spec, available as the `EsiSpec` namespace. These are guaranteed to match the live spec and complement the hand-written types:
526
-
527
- ```typescript
528
- import { EsiSpec } from '@lgriffin/esi.ts';
529
-
530
- // Generated type — uses OpenAPI schema names (v7.0.0+)
531
- const order: EsiSpec.MarketsRegionIdOrdersGet = {
532
- order_id: 123,
533
- type_id: 34,
534
- price: 5.5,
535
- volume_remain: 1000,
536
- volume_total: 5000,
537
- is_buy_order: false,
538
- // ...
539
- };
540
- ```
541
-
542
- To regenerate types from the latest ESI spec:
543
-
544
- ```bash
545
- npm run generate:types # fetches OpenAPI spec, generates 161 interfaces + cache TTL map + rate limit groups + scope map
546
- npm run validate:esi # reports type drift between hand-written and generated types
547
- ```
548
-
549
- ## ESI Scopes
550
-
551
- The library includes a generated scope-to-endpoint mapping extracted from the ESI OpenAPI spec. Use it to check which OAuth scopes an endpoint requires before making a request:
552
-
553
- ```typescript
554
- import { esiEndpointScopes, EsiScope } from '@lgriffin/esi.ts';
555
-
556
- // Look up scopes for a specific endpoint
557
- const walletScopes = esiEndpointScopes['GET:characters/{character_id}/wallet'];
558
- // → ['esi-wallet.read_character_wallet.v1']
559
-
560
- // Check if an endpoint requires auth
561
- const isPublic = !esiEndpointScopes['GET:universe/types/{type_id}'];
562
- // → true (public endpoint, no scopes needed)
563
-
564
- // Type-safe scope values
565
- const scope: EsiScope = 'esi-assets.read_assets.v1';
566
- ```
567
-
568
- ## Error Handling
569
-
570
- API errors throw `EsiError` with `statusCode`, `message`, and `url` properties:
571
-
572
- ```typescript
573
- import {
574
- EsiError,
575
- TimeoutError,
576
- EsiValidationError,
577
- isTimeout,
578
- isRetryable,
579
- isValidationError,
580
- } from '@lgriffin/esi.ts';
581
-
582
- try {
583
- const alliance = await client.alliance.getAllianceById(99999999);
584
- console.log('Alliance:', alliance.name);
585
- } catch (err) {
586
- if (isValidationError(err)) {
587
- console.log('Response validation failed:', err.validationError);
588
- } else if (isTimeout(err)) {
589
- console.log(`Request timed out after ${err.timeoutMs}ms`);
590
- } else if (err instanceof EsiError) {
591
- console.log(`ESI error ${err.statusCode}: ${err.message}`);
592
- console.log(`Retryable: ${err.retryable}`);
593
- }
594
- }
595
- ```
596
-
597
- - **204 No Content** — returns `undefined` (valid for DELETE/POST actions)
598
- - **304 Not Modified** — handled internally, returns cached data
599
- - **4xx/5xx** — throws `EsiError`
600
- - **5xx with cache** — returns stale cached data instead of throwing
601
- - **Timeout** — throws `TimeoutError` (extends `EsiError` with `statusCode: 0` and `timeoutMs`)
602
- - **Retryable errors** — `EsiError.retryable` returns `true` for 502, 503, 504, 420, 429, and timeouts
603
- - **Validation errors** — throws `EsiValidationError` (extends `EsiError`) when response data doesn't match the expected Zod schema
604
-
605
- ## Response Metadata
606
-
607
- Use `withMetadata()` to get response headers, cache status, rate limit info, and timing alongside the data:
608
-
609
- ```typescript
610
- const metaClient = client.alliance.withMetadata();
611
- const result = await metaClient.getAllianceById(99000001);
612
-
613
- console.log(result.data.name); // "Goonswarm Federation"
614
- console.log(result.meta.fromCache); // true if served from cache
615
- console.log(result.meta.cacheHitType); // 'spec-ttl' | 'etag-304' | 'stale-on-error'
616
- console.log(result.meta.responseTimeMs); // milliseconds
617
- console.log(result.meta.rateLimit); // { remaining, limit, used, group }
618
- console.log(result.meta.requestId); // ESI request ID for debugging
619
- ```
620
-
621
- The `meta` object includes:
622
-
623
- | Field | Type | Description |
624
- | ---------------- | ------------------------ | ------------------------------------------------- |
625
- | `headers` | `Record<string, string>` | Raw response headers |
626
- | `fromCache` | `boolean` | Whether data was served from cache |
627
- | `stale` | `boolean` | Whether cached data is stale (5xx fallback) |
628
- | `cacheHitType` | `string?` | `'spec-ttl'`, `'etag-304'`, or `'stale-on-error'` |
629
- | `rateLimit` | `RateLimitMeta?` | Rate limit status from ESI headers |
630
- | `responseTimeMs` | `number?` | Request duration in milliseconds |
631
- | `requestId` | `string?` | ESI request ID |
632
- | `warning` | `object?` | ESI deprecation warning |
633
-
634
- ## Rate Limiting
635
-
636
- ESI.ts automatically manages rate limiting using ESI's per-group token bucket system. The 36 rate limit groups from the ESI OpenAPI spec are extracted at build time, so each group (e.g., `market-order`, `char-notification`) gets its own independent bucket. A burst of market requests won't starve unrelated endpoints.
637
-
638
- Rate limiting works out of the box with no configuration. For multi-character applications, enable per-user bucketing:
639
-
640
- ```typescript
641
- import { EsiClient } from '@lgriffin/esi.ts';
642
-
643
- const client = new EsiClient({
644
- rateLimiterConfig: {
645
- userKeyExtractor: (headers) => headers['authorization'] ?? 'anon',
646
- },
647
- });
648
- ```
649
-
650
- Monitor rate limit status per group:
651
-
652
- ```typescript
653
- const limiter = client.getRateLimiter();
654
-
655
- // Worst-case across all groups (backward-compatible)
656
- const status = limiter.getStatus();
657
- console.log(status.remaining, status.limit, status.group);
658
-
659
- // Specific group
660
- const marketStatus = limiter.getGroupStatus('market-order');
661
- console.log(marketStatus?.remaining); // tokens remaining in this group
662
-
663
- // All active groups
664
- const all = limiter.getAllGroupStatuses();
665
- for (const [group, info] of all) {
666
- console.log(`${group}: ${info.remaining}/${info.limit}`);
667
- }
668
-
669
- // Check if a specific group is blocked
670
- console.log(limiter.isBlocked('char-notification')); // true if 429'd
671
- ```
672
-
673
- ## Lightweight Clients
674
-
675
- All three client creation patterns (`EsiClient`, `CustomEsiClient`, `EsiApiFactory`) now get identical middleware defaults (cache, request deduplication, rate limiter) thanks to `configureApiClient()`. Previously `CustomEsiClient` and `EsiApiFactory` only configured the rate limiter.
676
-
677
- If you only need a subset of APIs, use `CustomEsiClient` or `EsiClientBuilder` to load only what you need:
678
-
679
- ```typescript
680
- import { EsiClientBuilder } from '@lgriffin/esi.ts';
681
-
682
- const client = new EsiClientBuilder()
683
- .addClients(['market', 'universe', 'characters'])
684
- .withClientId('my-trading-bot')
685
- .withAccessToken('your-token')
686
- .build();
687
-
688
- const prices = await client.market?.getMarketPrices();
689
- const system = await client.universe?.getSystemById(30000142);
690
- ```
691
-
692
- Or create standalone single-API clients:
693
-
694
- ```typescript
695
- import { EsiApiFactory } from '@lgriffin/esi.ts';
696
-
697
- const marketClient = EsiApiFactory.createMarketClient({
698
- clientId: 'price-checker',
699
- });
700
- const prices = await marketClient.getMarketPrices();
701
- ```
702
-
703
- ## Endpoint Coverage
704
-
705
- All 208 endpoint definitions have been validated against live Tranquility using the **OpenAPI 3.1 spec** — 194 from the public ESI spec plus 14 for newer EVE features. 206 endpoints are exercisable (2 mercenary den endpoints await CCP deployment). Full output is captured in [`openapi.output.md`](openapi.output.md).
706
-
707
- | Category | Endpoints | Method |
708
- | --------------------------- | --------- | -------------------------------------------------- |
709
- | Public GETs | 78 | 43 runnable example scripts with captured output |
710
- | Authenticated GETs | 72 | Example scripts + live testing with EVE SSO tokens |
711
- | Contacts (POST/PUT/DELETE) | 3 | Live create/edit/delete lifecycle |
712
- | Fittings (POST/DELETE) | 2 | Live create/delete lifecycle |
713
- | Mail (POST/PUT/DELETE) | 5 | Live send/label/metadata/delete lifecycle |
714
- | UI (POST) | 5 | Live testing with EVE client running |
715
- | Calendar (PUT) | 1 | Live RSVP to event |
716
- | Fleet (GET/POST/PUT/DELETE) | 14 | Live fleet with fleet commander + squad members |
717
- | Assets POST | 3 | Live asset location/name queries |
718
- | CSPA (POST) | 1 | Live charge cost calculation |
719
- | Dogma dynamic (GET) | 1 | Live mutaplasmid (Abyssal) item query |
720
- | Universe POST helpers | 3 | Live name resolution and affiliation |
721
- | Freelance Jobs (GET) | 4 | Live queries (graceful 404 for no active jobs) |
722
-
723
- ## Examples
724
-
725
- 43 runnable examples are in the `examples/` directory.
726
-
727
- ### Public Endpoints (no auth needed)
728
-
729
- ```bash
730
- npm run example:status # Server status — quickest smoke test
731
- npm run example:character # Character public info, portrait, corporation
732
- npm run example:universe # Solar system, constellation, region, station
733
- npm run example:market # Average prices + Tritanium price history
734
- npm run example:alliance # Alliance info + member corporations
735
- npm run example:route # Jita-to-Amarr route with system names
736
- npm run example:wars # Recent wars with aggressor/defender details
737
- npm run example:sovereignty # Nullsec sovereignty map + active campaigns
738
- npm run example:industry # Industry facilities, cost indices, insurance
739
- npm run example:incursions # Active incursions + faction warfare stats
740
- npm run example:dogma # Item type details + dogma attributes
741
- npm run example:contracts # Public region contracts + auction bids/items
742
- npm run example:rate-limiting # Rate limiter & pagination demonstration
743
- npm run example:cursor-pagination # Freelance Jobs with cursor pagination
744
- npm run example:streaming # Streaming pagination for large datasets
745
- npm run example:token-refresh # Automatic token refresh on 401
746
- npm run example:universe-encyclopedia # Ancestries, bloodlines, races, celestials
747
- npm run example:dogma-meta-sov # Dogma effects, sovereignty, meta endpoint
748
- npm run example:faction-details # Faction warfare leaderboards and stats
749
- ```
750
-
751
- ### Authenticated Endpoints (require ESI_ACCESS_TOKEN)
752
-
753
- ```bash
754
- npm run example # Full character profile assembly
755
- npm run example:wallet # Wallet balance, journal, transactions
756
- npm run example:skills # Trained skills, queue, attributes
757
- npm run example:assets # Asset inventory with bulk name lookup
758
- npm run example:killmails # Recent killmails + full details
759
- npm run example:fleet # Fleet info, members, wing/squad structure
760
- npm run example:mail # Inbox headers, labels, mailing lists
761
- npm run example:location # Current system, online status, ship
762
- npm run example:fittings # Saved fittings + clone state + implants
763
- npm run example:contacts # Contact list with standings + labels
764
- npm run example:character-details # Blueprints, roles, standings, medals
765
- npm run example:corporation-details # Corp members, divisions, structures
766
- npm run example:calendar-search # Calendar events + character search
767
- npm run example:loyalty-pi # Loyalty points + planetary interaction
768
- npm run example:industry-mining # Industry jobs + mining ledger
769
- npm run example:market-orders # Character/corp market orders
770
- npm run example:corp-contracts-wallet # Corp contracts, contacts, wallets
771
- ```
772
-
773
- ### Write Operations (require specific scopes + caution)
774
-
775
- ```bash
776
- npm run example:write-ops # Contacts, fittings, mail, UI lifecycle tests
777
- npm run example:universe-posts # Name resolution + character affiliation (public)
778
- npm run example:freelance-jobs # Freelance job queries
779
- ```
780
-
781
- ### Parallel Requests
782
-
783
- ```typescript
784
- const [character, portrait, corp] = await Promise.all([
785
- client.characters.getCharacterPublicInfo(characterId),
786
- client.characters.getCharacterPortrait(characterId),
787
- client.corporations.getCorporationInfo(corporationId),
788
- ]);
789
-
790
- console.log(`${character.name} [${corp.ticker}]`);
791
- ```
792
-
793
- ### Market Analysis
794
-
795
- ```typescript
796
- const [orders, history] = await Promise.all([
797
- client.market.getMarketOrders(regionId),
798
- client.market.getMarketHistory(regionId, typeId),
799
- ]);
800
-
801
- const buyOrders = orders.filter((o) => o.is_buy_order);
802
- const sellOrders = orders.filter((o) => !o.is_buy_order);
803
-
804
- console.log(`Best buy: ${Math.max(...buyOrders.map((o) => o.price))}`);
805
- console.log(`Best sell: ${Math.min(...sellOrders.map((o) => o.price))}`);
806
- ```
807
-
808
- ## Resource Management
809
-
810
- Always call `shutdown()` when you're done to clean up cache timers:
811
-
812
- ```typescript
813
- const client = new EsiClient();
814
- try {
815
- const status = await client.status.getStatus();
816
- console.log(status.server_version);
817
- } finally {
818
- await client.shutdown();
819
- }
820
- ```
821
-
822
- ## Testing
823
-
824
- ESI.ts has a comprehensive multi-tier testing strategy with 95+ suites and 3,800+ tests:
825
-
826
- | Tier | Tests | Purpose |
827
- | -------------------------- | ---------------- | ------------------------------------------------------------------ |
828
- | **TDD unit tests** | 81 files | Every client method, endpoint path, query param, and body format |
829
- | **BDD scenario tests** | 40 feature files | Behavioral specifications in Gherkin (Given/When/Then) |
830
- | **Mocked integration** | Full suite | Cross-layer request flow with jest-fetch-mock |
831
- | **Live smoke tests** | 43 examples | Every endpoint against live Tranquility |
832
- | **ESI spec contract** | 15 tests | Endpoint definitions validated against live OpenAPI spec |
833
- | **Deep contract tests** | 8 categories | Path params, query params, body, auth, schemas, pagination vs spec |
834
- | **Property-based fuzzing** | 601 tests | fast-check fuzzing of validation, URL construction, Zod schemas |
835
- | **Mutation testing** | Stryker | Validates test suite kills code mutants |
836
- | **Type-level tests** | tsd | Consumer API type correctness via tsd |
837
- | **Gated auth tests** | 33 tests | Authenticated endpoints with real tokens |
838
- | **Construction parity** | Per-surface | Verifies all client surfaces get identical middleware defaults |
839
- | **Spec-alignment** | Type assertions | Ensures hand-written types align with generated OpenAPI types |
840
-
841
- ```bash
842
- npm test # Unit + BDD tests (95+ suites, 3,800+ tests)
843
- npm run coverage # Tests with coverage report (thresholds enforced)
844
- npm run bdd # BDD scenario tests only
845
- npm run contract # Contract tests (skipped without ESI_LIVE_TESTS=true)
846
- npm run fuzz # Property-based fuzz tests (601 tests)
847
- npm run mutation # Mutation testing (Stryker)
848
- npm run benchmark # Performance benchmark tests
849
- npm run test:types # tsd consumer type tests
850
- ```
851
-
852
- Coverage thresholds are enforced in CI: branches 80%, functions 75%, lines 90%, statements 90%.
853
-
854
- See [guides/TESTING.md](guides/TESTING.md) for the full testing guide, and [guides/ARCHITECTURE.md](guides/ARCHITECTURE.md) for architecture diagrams.
855
-
856
- ## Development
857
-
858
- ### Prerequisites
859
-
860
- - Node.js 18+
861
- - npm
862
-
863
- ### Code Quality Tools
864
-
865
- The project uses a comprehensive suite of static analysis and code quality tools:
866
-
867
- | Tool | Purpose | Command |
868
- | ------------------------------------------------------------------------------------ | ------------------------------------------------------- | ------------------------------ |
869
- | [ESLint](https://eslint.org/) | Linting with TypeScript, security, and code smell rules | `npm run lint` |
870
- | [Prettier](https://prettier.io/) | Code formatting | `npm run format:check` |
871
- | [knip](https://knip.dev/) | Dead code and unused export detection | `npm run knip` |
872
- | [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security) | Security anti-pattern detection | Integrated into `npm run lint` |
873
- | [eslint-plugin-sonarjs](https://github.com/SonarSource/eslint-plugin-sonarjs) | Cognitive complexity and code smell detection | Integrated into `npm run lint` |
874
- | [husky](https://typicode.github.io/husky/) | Git pre-commit hooks | Automatic on commit |
875
- | [lint-staged](https://github.com/lint-staged/lint-staged) | Run linters on staged files only | Automatic on commit |
876
- | [Redocly CLI](https://redocly.com/docs/cli/) | OpenAPI spec validation and linting | `npm run validate:spec` |
877
-
878
- ### Available Scripts
879
-
880
- ```bash
881
- # Development
882
- npm run build # Compile TypeScript
883
- npm run lint # Run ESLint
884
- npm run lint:fix # Run ESLint with auto-fix
885
- npm run format # Format code with Prettier
886
- npm run format:check # Check formatting without modifying
887
-
888
- # Testing
889
- npm test # Unit tests (95+ suites, 3,800+ tests)
890
- npm run test:all # Unit + BDD + integration + fuzz + type tests
891
- npm run coverage # Tests with coverage report (thresholds enforced)
892
- npm run bdd # BDD scenario tests
893
- npm run contract:live # Deep contract tests against live ESI spec
894
- npm run fuzz # Property-based fuzz tests (fast-check)
895
- npm run mutation # Mutation testing (Stryker)
896
- npm run benchmark # Performance benchmark tests
897
- npm run test:types # Consumer type tests (tsd)
898
- npm run mock:esi # Start Prism mock ESI server on port 4010
899
-
900
- # Static Analysis
901
- npm run knip # Detect dead code and unused exports
902
- npm run validate:esi # Validate endpoints against live ESI OpenAPI spec
903
- npm run validate:spec # Lint ESI OpenAPI spec with Redocly (structural + best practices)
904
- npm run validate:auth-scopes # Auth/scope cross-validation
905
- npm run schema:drift # Schema drift detection (hand-written vs OpenAPI spec)
906
- npm run validate # Run all checks: lint, format, build, coverage, knip
907
- npm run generate:types # Regenerate TypeScript interfaces from ESI OpenAPI spec
908
- npm run generate:okf # Generate OKF knowledge bundle from ESI OpenAPI spec
909
-
910
- # Documentation
911
- npm run docs # Generate TypeDoc API documentation
912
- npm run docs:serve # Serve docs locally on port 8080
913
- ```
914
-
915
- ### ESI Endpoint Validation
916
-
917
- To verify that the codebase endpoint definitions match the live ESI OpenAPI spec:
918
-
919
- ```bash
920
- npm run validate:esi
921
- ```
922
-
923
- This fetches the ESI OpenAPI spec and reports:
924
-
925
- - Endpoints in the codebase that are no longer in the ESI spec
926
- - Endpoints in the ESI spec that the codebase doesn't cover
927
- - HTTP method mismatches between codebase and spec
928
-
929
- ### Pre-commit Hooks
930
-
931
- The project uses husky with lint-staged to run ESLint and Prettier on staged files before each commit. This is set up automatically when you run `npm install`.
932
-
933
- ### CI/CD
934
-
935
- Every pull request runs the full validation suite:
936
-
937
- - ESLint (with security and sonarjs plugins)
938
- - Prettier formatting check
939
- - TypeScript compilation
940
- - Generated types staleness check (regenerates from live ESI OpenAPI spec and verifies no diff)
941
- - Unit tests across Node.js 18, 20, and 22
942
- - BDD scenario tests
943
- - Coverage threshold enforcement (branches: 80%, functions: 75%, lines: 90%, statements: 90%)
944
- - Auth/scopes cross-validation
945
- - Spec-alignment type assertions
946
- - Schema drift detection
947
- - Mutation testing (Stryker)
948
- - Dead code detection via knip
949
- - npm security audit
950
-
951
- See [.github/workflows/README.md](.github/workflows/README.md) for full workflow details.
952
-
953
- ## Contributing
954
-
955
- 1. Fork the repository
956
- 2. Create a feature branch
957
- 3. Write tests for your changes
958
- 4. Run `npm run validate` to check everything passes
959
- 5. Open a Pull Request
960
-
961
- ## License
962
-
963
- GPL-3.0-or-later - see the [LICENSE](LICENSE) file for details.
964
-
965
- ---
966
-
967
- **o7**
1
+ # ESI.ts
2
+
3
+ [![npm version](https://badge.fury.io/js/%40lgriffin%2Fesi.ts.svg)](https://badge.fury.io/js/%40lgriffin%2Fesi.ts)
4
+ [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-6.0%2B-blue)](https://www.typescriptlang.org/)
6
+ [![CI/CD Pipeline](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml/badge.svg)](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml)
7
+ [![Coverage](https://img.shields.io/badge/coverage-90%25%2B-brightgreen)](https://github.com/lgriffin/ESI.ts)
8
+ [![npm downloads](https://img.shields.io/npm/dm/%40lgriffin/esi.ts)](https://www.npmjs.com/package/@lgriffin/esi.ts)
9
+
10
+ A production-grade TypeScript client for the [EVE Online ESI API](https://esi.evetech.net/), built on the **OpenAPI 3.1 spec**, with runtime validation, intelligent caching, and full endpoint coverage.
11
+
12
+ **v9.1.0** — Expanded test pyramid (schema rejection, domain fuzz, benchmark, type tests), updated documentation and examples, fuzz test date handling fix.
13
+
14
+ **223 endpoint definitions — 194 from the public ESI OpenAPI spec, plus 29 for newer EVE features (Equinox sovereignty, orbital skyhooks, mercenary dens, access lists, freelance jobs, military campaigns, corporation projects). All 221 exercisable endpoints validated against live Tranquility on 2026-08-14.**
15
+
16
+ ## Why ESI.ts vs. OpenAPI-Generated Clients?
17
+
18
+ Tools like `openapi-typescript` or `openapi-generator` can produce a typed client from the ESI OpenAPI spec in minutes. They're a reasonable starting point — but they stop at type generation. ESI.ts is a purpose-built SDK that handles the problems you hit _after_ the types compile.
19
+
20
+ ### What generators give you
21
+
22
+ - TypeScript interfaces from the OpenAPI spec
23
+ - Basic request/response typing
24
+ - A thin HTTP wrapper
25
+
26
+ ### What ESI.ts gives you on top of that
27
+
28
+ | Capability | openapi-typescript | ESI.ts |
29
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
30
+ | **Runtime response validation** | None — types are erased at compile time. If CCP changes a field, you get silent data corruption. | Every GET response is validated at runtime via [Zod](https://zod.dev/) schemas — all 173 GET endpoints have schemas. Schema mismatches throw `EsiValidationError` immediately. |
31
+ | **Intelligent caching** | None — you build your own. | Three-tier: spec-aware TTL (zero HTTP calls within ESI's `x-cached-seconds` window), ETag conditional GETs, stale-on-error fallback on 5xx. Write operations auto-invalidate related GET caches. |
32
+ | **Rate limiting** | None — you build your own. | 36 per-group token buckets extracted from the ESI spec at build time. Market requests can't starve wallet requests. Optional per-user bucketing for multi-character apps. |
33
+ | **Pagination** | Manual — you write the page loop. | Automatic offset pagination, cursor-based pagination (Equinox-era endpoints), and streaming `AsyncGenerator` pagination for memory-efficient processing of large datasets. |
34
+ | **Retry & resilience** | None. | Exponential backoff with jitter, circuit breaker (closed/open/half-open), automatic 401 token refresh with concurrent coalescing. |
35
+ | **Wire format correctness** | Generates from spec, but ESI's spec has inconsistencies (query params documented as body, missing required fields). | Every endpoint tested against live ESI. Wire format bugs (query params vs. body, field naming) are caught and fixed — see the contacts and UI endpoint fixes in v6.1.0. |
36
+ | **Batch operations** | None. | `batch()` with bounded concurrency for GET fan-out, `batchPost()` with auto-chunking for large POST payloads. |
37
+ | **Domain knowledge** | None — generic HTTP client. | 37 domain clients with typed methods, JSDoc documentation, and input validation (e.g., fleet wing/squad names are capped at 10 characters before hitting the API). |
38
+ | **Streaming pagination** | None. | 21 domain clients with 73+ `stream*` methods via `AsyncGenerator` — process large datasets page-by-page without loading everything into memory. |
39
+ | **Testing** | Whatever you write. | 143 test suites, 4,182 tests across 9 tiers including property-based fuzzing (fast-check), mutation testing (Stryker), deep contract tests against live OpenAPI spec, and consumer type tests (tsd). 46 runnable example scripts. |
40
+
41
+ ### The real problem with generated clients
42
+
43
+ The ESI OpenAPI spec is not a perfect source of truth. During live endpoint validation against the OpenAPI 3.1 spec, we discovered:
44
+
45
+ - `addContacts`, `editContacts`, and 4 UI endpoints document parameters as request body when ESI actually expects query parameters
46
+ - `deleteCharacterContacts` expects comma-separated contact IDs as a query param, not a JSON body
47
+ - Fleet wing/squad names have a 10-character limit not documented in the spec
48
+ - The `updateMailMetadata` endpoint uses the field name `read`, not `is_read`
49
+
50
+ A generated client faithfully reproduces these spec bugs. ESI.ts fixes them.
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ npm install @lgriffin/esi.ts
56
+ ```
57
+
58
+ ### Building from Source
59
+
60
+ ```bash
61
+ git clone https://github.com/lgriffin/ESI.ts.git
62
+ cd ESI.ts
63
+ npm install # installs dependencies and compiles (via the prepare script)
64
+ ```
65
+
66
+ If you've already installed and just need to recompile:
67
+
68
+ ```bash
69
+ npm run build
70
+ ```
71
+
72
+ Verify everything works:
73
+
74
+ ```bash
75
+ npm run example:status # quick smoke test — checks ESI is reachable
76
+ npm test # run the full test suite (143 suites, 4,182 tests)
77
+ ```
78
+
79
+ ## Sub-path Exports
80
+
81
+ ESI.ts provides sub-path exports for targeted imports, reducing bundle size when you only need specific parts of the library:
82
+
83
+ ```typescript
84
+ // Zod schemas for runtime validation
85
+ import { MarketOrderSchema } from '@lgriffin/esi.ts/schemas';
86
+
87
+ // Error classes and type guards
88
+ import { EsiError, isCircuitOpen } from '@lgriffin/esi.ts/errors';
89
+
90
+ // Test utilities
91
+ import { TestDataFactory } from '@lgriffin/esi.ts/testing';
92
+ ```
93
+
94
+ ## Quick Start
95
+
96
+ ```typescript
97
+ import { EsiClient } from '@lgriffin/esi.ts';
98
+
99
+ const client = new EsiClient();
100
+
101
+ // Public data — no auth required
102
+ const alliances = await client.alliance.getAlliances();
103
+ const character = await client.characters.getCharacterPublicInfo(1689391488);
104
+ const system = await client.universe.getSystemById(30000142);
105
+ const prices = await client.market.getMarketPrices();
106
+
107
+ // Authenticated data — token read from ESI_ACCESS_TOKEN env var
108
+ const authedClient = new EsiClient();
109
+ const assets = await authedClient.assets.getCharacterAssets(characterId);
110
+ const wallet = await authedClient.wallet.getCharacterWallet(characterId);
111
+
112
+ // Clean up when done
113
+ await client.shutdown();
114
+ ```
115
+
116
+ ## Configuration
117
+
118
+ ```typescript
119
+ const client = new EsiClient({
120
+ clientId: 'my-app', // User-Agent identifier (default: 'esi-client')
121
+ accessToken: 'your-token', // EVE SSO token for authenticated endpoints
122
+ baseUrl: 'https://esi.evetech.net', // ESI base URL (default)
123
+ onTokenRefresh: async () => newToken, // Auto-refresh on 401 (optional)
124
+ language: 'en', // Accept-Language header: en, de, fr, ja, ru, zh, ko, es (default: none)
125
+ timeout: 30000, // Request timeout in ms (default: 30000)
126
+ retryConfig: {
127
+ maxRetries: 3, // Max retry attempts for transient errors (default: 3)
128
+ baseDelayMs: 1000, // Initial backoff delay (default: 1000)
129
+ maxDelayMs: 30000, // Maximum backoff delay (default: 30000)
130
+ retryMutations: false, // Retry POST/PUT/DELETE (default: false, GET only)
131
+ },
132
+ enableETagCache: true, // ETag caching (default: true)
133
+ etagCacheConfig: {
134
+ maxEntries: 1000, // Max cached responses (default: 1000)
135
+ defaultTtl: 300000, // Fallback TTL in ms (default: 5 min)
136
+ cleanupInterval: 60000, // Expired entry cleanup interval (default: 1 min)
137
+ },
138
+ validateResponse: true, // Runtime Zod validation of ESI responses (default: true)
139
+ validateRequest: false, // Opt-in request body Zod validation for POST/PUT/DELETE (default: false)
140
+ retryStrategy: customRetryStrategy, // Injectable IRetryStrategy (default: built-in exponential backoff)
141
+ circuitBreakerConfig: {
142
+ keyStrategy: 'resolved', // CB keying: 'resolved' (per-URL) or 'template' (per-route) (default: 'resolved')
143
+ cleanupIntervalMs: 300000, // Automatic stale circuit cleanup interval (default: 5 min)
144
+ },
145
+ });
146
+ ```
147
+
148
+ Retry is enabled by default (`maxRetries: 3`). Transient errors (502, 503, 504, timeout, rate limit) are retried with exponential backoff and jitter. The circuit breaker is respected — requests are not retried when the circuit is open. Set `maxRetries: 0` to disable retry.
149
+
150
+ The access token can be updated at runtime:
151
+
152
+ ```typescript
153
+ client.setAccessToken('new-token');
154
+ ```
155
+
156
+ ## Authentication
157
+
158
+ Many ESI endpoints require an EVE SSO access token. There are three ways to provide one:
159
+
160
+ ### 1. Environment variable (recommended)
161
+
162
+ Set `ESI_ACCESS_TOKEN` in your environment or a `.env` file. The client reads it automatically — no token in source code.
163
+
164
+ ```bash
165
+ # Copy the example and fill in your token
166
+ cp .env.example .env
167
+ ```
168
+
169
+ ```env
170
+ ESI_ACCESS_TOKEN=your-eve-sso-access-token
171
+ ESI_CLIENT_ID=my-app-name
172
+ ```
173
+
174
+ If you use a `.env` loader like [dotenv](https://www.npmjs.com/package/dotenv), load it before creating the client:
175
+
176
+ ```typescript
177
+ import 'dotenv/config';
178
+ import { EsiClient } from '@lgriffin/esi.ts';
179
+
180
+ const client = new EsiClient();
181
+ // Token is picked up from process.env.ESI_ACCESS_TOKEN
182
+ ```
183
+
184
+ ### 2. Constructor parameter
185
+
186
+ Pass the token directly (useful for apps that manage tokens themselves):
187
+
188
+ ```typescript
189
+ const client = new EsiClient({ accessToken: token });
190
+ ```
191
+
192
+ ### 3. Runtime update
193
+
194
+ Set or refresh the token after construction:
195
+
196
+ ```typescript
197
+ client.setAccessToken(newToken);
198
+ ```
199
+
200
+ ### Getting an EVE SSO token
201
+
202
+ 1. Register an application at [EVE Developers](https://developers.eveonline.com/)
203
+ 2. Set a callback URL and select the ESI scopes your app needs
204
+ 3. Implement the [OAuth2 flow](https://docs.esi.evetech.net/docs/sso/) to obtain an access token
205
+ 4. Access tokens expire — use the refresh token to get new ones
206
+
207
+ ### Automatic Token Refresh
208
+
209
+ EVE SSO access tokens expire after 20 minutes. Instead of manually tracking expiry, you can provide a refresh callback — the client will automatically call it on 401, update the token, and retry the request:
210
+
211
+ ```typescript
212
+ const client = new EsiClient({
213
+ accessToken: initialToken,
214
+ onTokenRefresh: async () => {
215
+ const response = await fetch('https://login.eveonline.com/v2/oauth/token', {
216
+ method: 'POST',
217
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
218
+ body: new URLSearchParams({
219
+ grant_type: 'refresh_token',
220
+ refresh_token: myRefreshToken,
221
+ client_id: myClientId,
222
+ }),
223
+ });
224
+ const { access_token } = await response.json();
225
+ return access_token;
226
+ },
227
+ });
228
+
229
+ // Requests now auto-refresh on 401 — no manual token management needed
230
+ const location = await client.location.getCharacterLocation(characterId);
231
+ ```
232
+
233
+ The token provider can also be set or changed at runtime:
234
+
235
+ ```typescript
236
+ client.setTokenProvider(myRefreshFunction);
237
+ client.setTokenProvider(undefined); // disable auto-refresh
238
+ ```
239
+
240
+ Key behaviors:
241
+
242
+ - Only retries **once** per request — if the refreshed token also gets a 401, the error is thrown
243
+ - **Concurrent coalescing** — if multiple requests hit 401 simultaneously, only one refresh call is made
244
+ - If the refresh callback throws (e.g., refresh token revoked), a `TOKEN_REFRESH_FAILED` error is raised
245
+ - Without a token provider, 401 errors throw immediately as before
246
+
247
+ ### Environment variables reference
248
+
249
+ | Variable | Description | Default |
250
+ | ------------------ | -------------------------------------------- | ------------------------- |
251
+ | `ESI_ACCESS_TOKEN` | EVE SSO access token | none |
252
+ | `ESI_CLIENT_ID` | User-Agent identifier | `esi-client` |
253
+ | `ESI_BASE_URL` | ESI API base URL | `https://esi.evetech.net` |
254
+ | `ESI_LOG_LEVEL` | Log level (`error`, `warn`, `info`, `debug`) | `warn` |
255
+
256
+ ## Available APIs
257
+
258
+ All clients are accessed as properties on the `EsiClient` instance. Authenticated endpoints require an access token.
259
+
260
+ | Client | Property | Auth | Examples |
261
+ | ------------------ | ---------------------------- | ---- | -------------------------------------------------------------------------------- |
262
+ | Alliance | `client.alliance` | Some | `getAlliances()`, `getAllianceById(id)` |
263
+ | Assets | `client.assets` | Yes | `getCharacterAssets(id)` |
264
+ | Calendar | `client.calendar` | Yes | `getCalendarEvents(id)` |
265
+ | Characters | `client.characters` | Some | `getCharacterPublicInfo(id)`, `getCharacterPortrait(id)` |
266
+ | Clones | `client.clones` | Yes | `getCharacterClones(id)` |
267
+ | Contacts | `client.contacts` | Yes | `getCharacterContacts(id)`, `postCharacterContacts(id, standing, contactIds)` |
268
+ | Contracts | `client.contracts` | Yes | `getCharacterContracts(id)` |
269
+ | Corp Projects | `client.corporationProjects` | Yes | `getCorporationProjects(corpId)`, `getCorporationProject(corpId, projectId)` |
270
+ | Corporations | `client.corporations` | Some | `getCorporationInfo(id)`, `getCorporationMembers(id)` |
271
+ | Dogma | `client.dogma` | No | `getDogmaAttributes()`, `getDynamicItemInfo(typeId, itemId)` |
272
+ | Factions | `client.factions` | Some | `getFactionWarStats()` |
273
+ | Fittings | `client.fittings` | Yes | `getFittings(id)`, `createFitting(id, body)` |
274
+ | Fleets | `client.fleets` | Yes | `getFleetInformation(id)`, `getFleetMembers(id)` |
275
+ | Incursions | `client.incursions` | No | `getIncursions()` |
276
+ | Industry | `client.industry` | Some | `getCharacterIndustryJobs(id)` |
277
+ | Insurance | `client.insurance` | No | `getInsurancePrices()` |
278
+ | Killmails | `client.killmails` | Some | `getKillmail(id, hash)` |
279
+ | Location | `client.location` | Yes | `getCharacterLocation(id)` |
280
+ | Loyalty | `client.loyalty` | Yes | `getCharacterLoyaltyPoints(id)` |
281
+ | Mail | `client.mail` | Yes | `getCharacterMail(id)`, `sendMail(id, body)` |
282
+ | Market | `client.market` | Some | `getMarketPrices()`, `getMarketOrders(regionId)` |
283
+ | Military Campaigns | `client.militaryCampaigns` | Some | `getMilitaryCampaigns()`, `getMilitaryCampaignById(id)` |
284
+ | PI | `client.pi` | Yes | `getCharacterPlanets(id)` |
285
+ | Route | `client.route` | No | `getRoute(origin, destination)` |
286
+ | Search | `client.search` | Some | `search(characterId, query)` |
287
+ | Skills | `client.skills` | Yes | `getCharacterSkills(id)` |
288
+ | Sovereignty | `client.sovereignty` | No | `getSovereigntySystems()`, `getSovereigntyMap()` |
289
+ | Skyhooks | `client.skyhooks` | No | `getSovereigntyHubs()`, `getRaidableSkyhooks()` |
290
+ | Mercenary | `client.mercenary` | No | `getMercenaryDens()`, `getMercenaryTacticalOperations()` |
291
+ | Access Lists | `client.accessLists` | Yes | `getAccessList(id)` |
292
+ | Status | `client.status` | No | `getStatus()` |
293
+ | UI | `client.ui` | Yes | `setAutopilotWaypoint(destId, addToBeginning, clear)`, `openNewMailWindow(body)` |
294
+ | Universe | `client.universe` | Some | `getSystemById(id)`, `getTypeById(id)` |
295
+ | Wallet | `client.wallet` | Yes | `getCharacterWallet(id)` |
296
+ | Wars | `client.wars` | No | `getWars()`, `getWarById(id)` |
297
+ | Freelance Jobs | `client.freelanceJobs` | Some | `getFreelanceJobs()`, `getFreelanceJobById(id)` |
298
+ | Meta | `client.meta` | No | `getOpenApiJson()`, `getOpenApiYaml()` |
299
+
300
+ ## Runtime Response Validation
301
+
302
+ ESI.ts validates API responses at runtime using [Zod](https://zod.dev/) schemas. All GET endpoints have schemas — these are the endpoints that return data your application consumes, where a silent shape change from CCP would cause bugs. POST/PUT/DELETE mutations typically return `204 No Content` (no body to validate) or simple confirmation values, so schemas are omitted where there is nothing meaningful to validate.
303
+
304
+ Validation is **on by default**. Extra fields from ESI are preserved via `z.looseObject()` passthrough mode, so new fields added by CCP won't break your application — they flow through to your code untouched.
305
+
306
+ ```typescript
307
+ import {
308
+ EsiClient,
309
+ EsiValidationError,
310
+ isValidationError,
311
+ schemas,
312
+ } from '@lgriffin/esi.ts';
313
+
314
+ const client = new EsiClient();
315
+
316
+ // Validation happens automatically on every request
317
+ const character = await client.characters.getCharacterPublicInfo(12345);
318
+
319
+ // Disable validation globally if needed
320
+ const rawClient = new EsiClient({ validateResponse: false });
321
+
322
+ // Use schemas directly for your own validation
323
+ const result = schemas.CharacterInfoSchema.safeParse(someData);
324
+ if (result.success) {
325
+ console.log(result.data.name);
326
+ }
327
+ ```
328
+
329
+ ### Request Body Validation
330
+
331
+ For POST/PUT/DELETE endpoints, opt-in request body validation ensures outgoing payloads match the endpoint's `requestSchema` before the request is sent:
332
+
333
+ ```typescript
334
+ // Opt-in request body validation for POST/PUT/DELETE
335
+ const client = new EsiClient({ validateRequest: true });
336
+
337
+ // Throws EsiValidationError if the request body doesn't match the endpoint's requestSchema
338
+ await client.mail.sendMail(characterId, {
339
+ recipients: [{ recipient_id: 12345, recipient_type: 'character' }],
340
+ subject: 'Hello',
341
+ body: 'Message body',
342
+ });
343
+ ```
344
+
345
+ See [guides/RUNTIME-VALIDATION.md](guides/RUNTIME-VALIDATION.md) for the full guide on schemas, error handling, and extending schemas.
346
+
347
+ ## Caching
348
+
349
+ ETag caching is enabled by default. The client automatically:
350
+
351
+ 1. Stores ETag and response data on GET requests
352
+ 2. Sends `If-None-Match` on subsequent requests
353
+ 3. Returns cached data on `304 Not Modified`
354
+ 4. Parses `Cache-Control: max-age` from ESI for per-endpoint TTL
355
+ 5. Serves stale cached data when ESI returns 5xx errors
356
+ 6. Invalidates related GET caches when POST/PUT/DELETE requests are made
357
+
358
+ ```typescript
359
+ // Cache stats
360
+ const stats = client.getCacheStats();
361
+ console.log(`${stats.totalEntries}/${stats.maxEntries} entries cached`);
362
+
363
+ // Manual cache operations
364
+ client.clearCache();
365
+ client.updateCacheConfig({ maxEntries: 2000 });
366
+
367
+ // Disable caching entirely
368
+ const uncachedClient = new EsiClient({ enableETagCache: false });
369
+ ```
370
+
371
+ ### Spec-Aware Cache TTLs
372
+
373
+ The library reads `x-cache-age` from the ESI OpenAPI spec (126 of 195 endpoints). Within the TTL window, repeated GET requests return cached data with **zero HTTP calls** — not even a conditional GET.
374
+
375
+ This layers on top of ETag caching in three tiers:
376
+
377
+ 1. **Spec TTL** — data can't have changed yet, return cached data immediately
378
+ 2. **ETag conditional GET** — data might have changed, send `If-None-Match` to check
379
+ 3. **Full request** — no cache entry, fetch fresh data
380
+
381
+ ```typescript
382
+ const client = new EsiClient();
383
+
384
+ // First call — fetches from ESI
385
+ const alliances = await client.alliance.getAlliances();
386
+
387
+ // Second call within the next 3600s — returns cached data, zero HTTP calls
388
+ const same = await client.alliance.getAlliances();
389
+ ```
390
+
391
+ ## Batch Requests
392
+
393
+ Fetch data for multiple IDs with bounded concurrency using `batch()`, or chunk large POST payloads with `batchPost()`:
394
+
395
+ ```typescript
396
+ import { EsiClient } from '@lgriffin/esi.ts';
397
+
398
+ const client = new EsiClient();
399
+
400
+ // Fetch 500 type details with at most 10 concurrent requests
401
+ const result = await client.batch(
402
+ typeIds,
403
+ (id) => client.universe.getTypeById(id),
404
+ {
405
+ concurrency: 10,
406
+ onProgress: (done, total) => console.log(`${done}/${total}`),
407
+ },
408
+ );
409
+
410
+ // result.results: Map<number, T> — successful responses
411
+ // result.errors: Map<number, Error> — failed requests
412
+ console.log(`${result.results.size} succeeded, ${result.errors.size} failed`);
413
+ ```
414
+
415
+ For POST endpoints that accept arrays (e.g., `postUniverseNames` with a 1000-ID limit), `batchPost` auto-chunks and concatenates:
416
+
417
+ ```typescript
418
+ const allNames = await client.batchPost(
419
+ largeIdArray,
420
+ (chunk) => client.universe.postUniverseNames(chunk),
421
+ 1000, // chunk size
422
+ );
423
+ ```
424
+
425
+ ## Streaming Pagination
426
+
427
+ For large paginated endpoints (market orders, contracts, assets), streaming yields one page at a time via `AsyncGenerator` instead of eagerly fetching all pages into memory:
428
+
429
+ ```typescript
430
+ import { EsiClient } from '@lgriffin/esi.ts';
431
+
432
+ const client = new EsiClient();
433
+
434
+ // Stream all market orders in The Forge, page by page
435
+ for await (const page of client.market.streamMarketOrders(10000002)) {
436
+ console.log(
437
+ `Page ${page.page}/${page.totalPages}: ${page.data.length} orders`,
438
+ );
439
+
440
+ // Process each order as it arrives
441
+ for (const order of page.data) {
442
+ if (order.is_buy_order && order.price > 1_000_000) {
443
+ console.log(`High-value buy: ${order.type_id} @ ${order.price} ISK`);
444
+ }
445
+ }
446
+
447
+ // Early termination — stops fetching remaining pages
448
+ if (page.page >= 3) break;
449
+ }
450
+ ```
451
+
452
+ 21 domain clients expose 73+ streaming methods. `BaseEsiClient.streamEndpoint()` is also public as an escape hatch for any paginated endpoint not yet wrapped with a convenience method.
453
+
454
+ Available streaming methods (representative selection):
455
+
456
+ - **MarketClient** — `streamMarketOrders`, `streamMarketTypes`, `streamCharacterOrderHistory`, `streamCorporationOrders`, `streamCorporationOrderHistory`, `streamMarketOrdersInStructure`
457
+ - **CorporationsClient** — `streamCorporationMembers`, `streamCorporationStructures`, `streamCorporationBlueprints`, + 14 more
458
+ - **CharacterClient** — `streamCharacterBlueprints`, `streamCharacterNotifications`, `streamCharacterStandings`, + 5 more
459
+ - **ContractsClient** — `streamPublicContracts`, `streamCharacterContracts`, `streamCorporationContracts`
460
+ - **WalletClient** — `streamCharacterWalletJournal`, `streamCorporationWalletJournal`, `streamCharacterWalletTransactions`
461
+ - **IndustryClient** — `streamCorporationIndustryJobs`, `streamCorporationMiningObservers`, + 6 more
462
+ - **ContactsClient** — `streamAllianceContacts`, `streamCharacterContacts`, `streamCorporationContacts`, + 3 more
463
+ - **AssetsClient** — `streamCharacterAssets`, `streamCorporationAssets`
464
+ - **KillmailsClient** — `streamCharacterRecentKillmails`, `streamCorporationRecentKillmails`
465
+ - **MailClient** — `streamCharacterMail`, `streamCharacterMailLabels`
466
+ - **FleetsClient** — `streamFleetMembers`, `streamFleetWings`
467
+ - **CalendarClient** — `streamCalendarEvents`
468
+ - **FittingsClient** — `streamCharacterFittings`
469
+ - **SkillsClient** — `streamCharacterSkillQueue`
470
+ - **LoyaltyClient** — `streamCorporationLoyaltyStoreOffers`
471
+ - **BookmarksClient** — `streamCharacterBookmarks`, `streamCorporationBookmarks`
472
+ - **ClonesClient** — `streamCharacterImplants`
473
+ - **PIClient** — `streamCharacterPlanets`
474
+ - **WarsClient** — `streamWars`
475
+ - **FactionWarfareClient** — `streamFactionWarfareStats`
476
+ - **AllianceClient** — `streamAllianceCorporations`
477
+
478
+ Try it: `npm run example:streaming`
479
+
480
+ ## Cursor-based Pagination
481
+
482
+ Newer ESI routes (Freelance Jobs, and future routes) use cursor-based pagination with opaque `before`/`after` tokens in the response body. See the [ESI blog post](https://developers.eveonline.com/blog/changing-pagination-turning-a-new-page) for background.
483
+
484
+ ```typescript
485
+ import { EsiClient, fetchAllCursorPages } from '@lgriffin/esi.ts';
486
+
487
+ const client = new EsiClient();
488
+
489
+ // Fetch first page — returns { cursor: { before, after }, freelance_jobs: [...] }
490
+ const page = await client.freelanceJobs.getFreelanceJobs();
491
+ console.log(page.freelance_jobs); // job records
492
+ console.log(page.cursor.after); // opaque token for next page
493
+
494
+ // Fetch next page using the cursor
495
+ const nextPage = await client.freelanceJobs.getFreelanceJobs(
496
+ undefined,
497
+ page.cursor.after,
498
+ );
499
+
500
+ // Auto-fetch all pages in one call
501
+ const allJobs = await fetchAllCursorPages(
502
+ (before, after) => client.freelanceJobs.getFreelanceJobs(before, after),
503
+ (response) => response.freelance_jobs,
504
+ (response) => response.cursor,
505
+ );
506
+
507
+ // Authenticated endpoints — character/corporation freelance jobs
508
+ const authedClient = new EsiClient({ accessToken: 'your-token' });
509
+ const myJobs =
510
+ await authedClient.freelanceJobs.getCharacterFreelanceJobs(characterId);
511
+ const corpJobs =
512
+ await authedClient.freelanceJobs.getCorporationFreelanceJobs(corporationId);
513
+ ```
514
+
515
+ **Polling for changes** — cursor tokens persist across sessions, so you can save the last `after` token and poll later to get only records that changed:
516
+
517
+ ```typescript
518
+ // After initial scan, save the final cursor
519
+ let savedCursor = lastPage.cursor.after;
520
+
521
+ // Later: check for updates (hours, days, or weeks later)
522
+ const updates = await client.freelanceJobs.getFreelanceJobs(
523
+ undefined,
524
+ savedCursor,
525
+ );
526
+ if (updates.freelance_jobs.length > 0) {
527
+ // Process changed records — duplicates are expected for modified records
528
+ savedCursor = updates.cursor.after;
529
+ }
530
+ ```
531
+
532
+ Key points:
533
+
534
+ - Cursor tokens are **opaque strings** — never parse or validate them
535
+ - An **empty result array** signals the end of the dataset (not a short page)
536
+ - **Duplicates across pages** are expected when records are modified between requests
537
+ - Existing offset-based routes (`getMarketOrders`, etc.) are unchanged
538
+
539
+ ## Generated Types
540
+
541
+ The library includes TypeScript interfaces generated directly from the ESI OpenAPI 3.1 spec, available as the `EsiSpec` namespace. These are guaranteed to match the live spec and complement the hand-written types:
542
+
543
+ ```typescript
544
+ import { EsiSpec } from '@lgriffin/esi.ts';
545
+
546
+ // Generated type — uses OpenAPI schema names (v7.0.0+)
547
+ const order: EsiSpec.MarketsRegionIdOrdersGet = {
548
+ order_id: 123,
549
+ type_id: 34,
550
+ price: 5.5,
551
+ volume_remain: 1000,
552
+ volume_total: 5000,
553
+ is_buy_order: false,
554
+ // ...
555
+ };
556
+ ```
557
+
558
+ To regenerate types from the latest ESI spec:
559
+
560
+ ```bash
561
+ npm run generate:types # fetches OpenAPI spec, generates 161 interfaces + cache TTL map + rate limit groups + scope map
562
+ npm run validate:esi # reports type drift between hand-written and generated types
563
+ ```
564
+
565
+ ## ESI Scopes
566
+
567
+ The library includes a generated scope-to-endpoint mapping extracted from the ESI OpenAPI spec. Use it to check which OAuth scopes an endpoint requires before making a request:
568
+
569
+ ```typescript
570
+ import { esiEndpointScopes, EsiScope } from '@lgriffin/esi.ts';
571
+
572
+ // Look up scopes for a specific endpoint
573
+ const walletScopes = esiEndpointScopes['GET:characters/{character_id}/wallet'];
574
+ // → ['esi-wallet.read_character_wallet.v1']
575
+
576
+ // Check if an endpoint requires auth
577
+ const isPublic = !esiEndpointScopes['GET:universe/types/{type_id}'];
578
+ // → true (public endpoint, no scopes needed)
579
+
580
+ // Type-safe scope values
581
+ const scope: EsiScope = 'esi-assets.read_assets.v1';
582
+ ```
583
+
584
+ ## Error Handling
585
+
586
+ API errors throw `EsiError` with `statusCode`, `message`, and `url` properties:
587
+
588
+ ```typescript
589
+ import {
590
+ EsiError,
591
+ TimeoutError,
592
+ EsiValidationError,
593
+ isTimeout,
594
+ isRetryable,
595
+ isValidationError,
596
+ isCircuitOpen,
597
+ } from '@lgriffin/esi.ts';
598
+
599
+ try {
600
+ const alliance = await client.alliance.getAllianceById(99999999);
601
+ console.log('Alliance:', alliance.name);
602
+ } catch (err) {
603
+ if (isCircuitOpen(err)) {
604
+ console.log('Circuit breaker is open — endpoint temporarily unavailable');
605
+ } else if (isValidationError(err)) {
606
+ console.log('Response validation failed:', err.validationError);
607
+ } else if (isTimeout(err)) {
608
+ console.log(`Request timed out after ${err.timeoutMs}ms`);
609
+ } else if (err instanceof EsiError) {
610
+ console.log(`ESI error ${err.statusCode}: ${err.message}`);
611
+ console.log(`Retryable: ${err.retryable}`);
612
+ }
613
+ }
614
+ ```
615
+
616
+ - **204 No Content** — returns `undefined` (valid for DELETE/POST actions)
617
+ - **304 Not Modified** — handled internally, returns cached data
618
+ - **4xx/5xx** — throws `EsiError`
619
+ - **5xx with cache** — returns stale cached data instead of throwing
620
+ - **Timeout** — throws `TimeoutError` (extends `EsiError` with `statusCode: 0` and `timeoutMs`)
621
+ - **Retryable errors** — `EsiError.retryable` returns `true` for 502, 503, 504, 420, 429, and timeouts
622
+ - **Validation errors** — throws `EsiValidationError` (extends `EsiError`) when response data doesn't match the expected Zod schema
623
+
624
+ ## Response Metadata
625
+
626
+ Use `withMetadata()` to get response headers, cache status, rate limit info, and timing alongside the data:
627
+
628
+ ```typescript
629
+ const metaClient = client.alliance.withMetadata();
630
+ const result = await metaClient.getAllianceById(99000001);
631
+
632
+ console.log(result.data.name); // "Goonswarm Federation"
633
+ console.log(result.meta.fromCache); // true if served from cache
634
+ console.log(result.meta.cacheHitType); // 'spec-ttl' | 'etag-304' | 'stale-on-error'
635
+ console.log(result.meta.responseTimeMs); // milliseconds
636
+ console.log(result.meta.rateLimit); // { remaining, limit, used, group }
637
+ console.log(result.meta.requestId); // ESI request ID for debugging
638
+ ```
639
+
640
+ The `meta` object includes:
641
+
642
+ | Field | Type | Description |
643
+ | ---------------- | ------------------------ | ------------------------------------------------- |
644
+ | `headers` | `Record<string, string>` | Raw response headers |
645
+ | `fromCache` | `boolean` | Whether data was served from cache |
646
+ | `stale` | `boolean` | Whether cached data is stale (5xx fallback) |
647
+ | `cacheHitType` | `string?` | `'spec-ttl'`, `'etag-304'`, or `'stale-on-error'` |
648
+ | `rateLimit` | `RateLimitMeta?` | Rate limit status from ESI headers |
649
+ | `responseTimeMs` | `number?` | Request duration in milliseconds |
650
+ | `requestId` | `string?` | ESI request ID |
651
+ | `warning` | `object?` | ESI deprecation warning |
652
+
653
+ ## Rate Limiting
654
+
655
+ ESI.ts automatically manages rate limiting using ESI's per-group token bucket system. The 36 rate limit groups from the ESI OpenAPI spec are extracted at build time, so each group (e.g., `market-order`, `char-notification`) gets its own independent bucket. A burst of market requests won't starve unrelated endpoints.
656
+
657
+ Rate limiting works out of the box with no configuration. For multi-character applications, enable per-user bucketing:
658
+
659
+ ```typescript
660
+ import { EsiClient } from '@lgriffin/esi.ts';
661
+
662
+ const client = new EsiClient({
663
+ rateLimiterConfig: {
664
+ userKeyExtractor: (headers) => headers['authorization'] ?? 'anon',
665
+ },
666
+ });
667
+ ```
668
+
669
+ Monitor rate limit status per group:
670
+
671
+ ```typescript
672
+ const limiter = client.getRateLimiter();
673
+
674
+ // Worst-case across all groups (backward-compatible)
675
+ const status = limiter.getStatus();
676
+ console.log(status.remaining, status.limit, status.group);
677
+
678
+ // Specific group
679
+ const marketStatus = limiter.getGroupStatus('market-order');
680
+ console.log(marketStatus?.remaining); // tokens remaining in this group
681
+
682
+ // All active groups
683
+ const all = limiter.getAllGroupStatuses();
684
+ for (const [group, info] of all) {
685
+ console.log(`${group}: ${info.remaining}/${info.limit}`);
686
+ }
687
+
688
+ // Check if a specific group is blocked
689
+ console.log(limiter.isBlocked('char-notification')); // true if 429'd
690
+ ```
691
+
692
+ ## Lightweight Clients
693
+
694
+ All three client creation patterns (`EsiClient`, `CustomEsiClient`, `EsiApiFactory`) now get identical middleware defaults (cache, request deduplication, rate limiter) thanks to `configureApiClient()`. Previously `CustomEsiClient` and `EsiApiFactory` only configured the rate limiter.
695
+
696
+ If you only need a subset of APIs, use `CustomEsiClient` or `EsiClientBuilder` to load only what you need:
697
+
698
+ ```typescript
699
+ import { EsiClientBuilder } from '@lgriffin/esi.ts';
700
+
701
+ const client = new EsiClientBuilder()
702
+ .addClients(['market', 'universe', 'characters'])
703
+ .withClientId('my-trading-bot')
704
+ .withAccessToken('your-token')
705
+ .build();
706
+
707
+ const prices = await client.market?.getMarketPrices();
708
+ const system = await client.universe?.getSystemById(30000142);
709
+ ```
710
+
711
+ Or create standalone single-API clients:
712
+
713
+ ```typescript
714
+ import { EsiApiFactory } from '@lgriffin/esi.ts';
715
+
716
+ const marketClient = EsiApiFactory.createMarketClient({
717
+ clientId: 'price-checker',
718
+ });
719
+ const prices = await marketClient.getMarketPrices();
720
+ ```
721
+
722
+ ## Endpoint Coverage
723
+
724
+ All 223 endpoint definitions have been validated against live Tranquility using the **OpenAPI 3.1 spec** — 194 from the public ESI spec plus 29 for newer EVE features. 221 endpoints are exercisable (2 mercenary den endpoints await CCP deployment). Full output is captured in [`openapi.output.md`](openapi.output.md).
725
+
726
+ | Category | Endpoints | Method |
727
+ | --------------------------- | --------- | -------------------------------------------------- |
728
+ | Public GETs | 78 | 46 runnable example scripts with captured output |
729
+ | Authenticated GETs | 72 | Example scripts + live testing with EVE SSO tokens |
730
+ | Contacts (POST/PUT/DELETE) | 3 | Live create/edit/delete lifecycle |
731
+ | Fittings (POST/DELETE) | 2 | Live create/delete lifecycle |
732
+ | Mail (POST/PUT/DELETE) | 5 | Live send/label/metadata/delete lifecycle |
733
+ | UI (POST) | 5 | Live testing with EVE client running |
734
+ | Calendar (PUT) | 1 | Live RSVP to event |
735
+ | Fleet (GET/POST/PUT/DELETE) | 14 | Live fleet with fleet commander + squad members |
736
+ | Assets POST | 3 | Live asset location/name queries |
737
+ | CSPA (POST) | 1 | Live charge cost calculation |
738
+ | Dogma dynamic (GET) | 1 | Live mutaplasmid (Abyssal) item query |
739
+ | Universe POST helpers | 3 | Live name resolution and affiliation |
740
+ | Freelance Jobs (GET) | 4 | Live queries (graceful 404 for no active jobs) |
741
+
742
+ ## Examples
743
+
744
+ 46 runnable examples are in the `examples/` directory.
745
+
746
+ ### Public Endpoints (no auth needed)
747
+
748
+ ```bash
749
+ npm run example:status # Server status — quickest smoke test
750
+ npm run example:character # Character public info, portrait, corporation
751
+ npm run example:universe # Solar system, constellation, region, station
752
+ npm run example:market # Average prices + Tritanium price history
753
+ npm run example:alliance # Alliance info + member corporations
754
+ npm run example:route # Jita-to-Amarr route with system names
755
+ npm run example:wars # Recent wars with aggressor/defender details
756
+ npm run example:sovereignty # Nullsec sovereignty map + active campaigns
757
+ npm run example:industry # Industry facilities, cost indices, insurance
758
+ npm run example:incursions # Active incursions + faction warfare stats
759
+ npm run example:dogma # Item type details + dogma attributes
760
+ npm run example:contracts # Public region contracts + auction bids/items
761
+ npm run example:rate-limiting # Rate limiter & pagination demonstration
762
+ npm run example:cursor-pagination # Freelance Jobs with cursor pagination
763
+ npm run example:streaming # Streaming pagination for large datasets
764
+ npm run example:token-refresh # Automatic token refresh on 401
765
+ npm run example:universe-encyclopedia # Ancestries, bloodlines, races, celestials
766
+ npm run example:dogma-meta-sov # Dogma effects, sovereignty, meta endpoint
767
+ npm run example:faction-details # Faction warfare leaderboards and stats
768
+ ```
769
+
770
+ ### Authenticated Endpoints (require ESI_ACCESS_TOKEN)
771
+
772
+ ```bash
773
+ npm run example # Full character profile assembly
774
+ npm run example:wallet # Wallet balance, journal, transactions
775
+ npm run example:skills # Trained skills, queue, attributes
776
+ npm run example:assets # Asset inventory with bulk name lookup
777
+ npm run example:killmails # Recent killmails + full details
778
+ npm run example:fleet # Fleet info, members, wing/squad structure
779
+ npm run example:mail # Inbox headers, labels, mailing lists
780
+ npm run example:location # Current system, online status, ship
781
+ npm run example:fittings # Saved fittings + clone state + implants
782
+ npm run example:contacts # Contact list with standings + labels
783
+ npm run example:character-details # Blueprints, roles, standings, medals
784
+ npm run example:corporation-details # Corp members, divisions, structures
785
+ npm run example:calendar-search # Calendar events + character search
786
+ npm run example:loyalty-pi # Loyalty points + planetary interaction
787
+ npm run example:industry-mining # Industry jobs + mining ledger
788
+ npm run example:market-orders # Character/corp market orders
789
+ npm run example:corp-contracts-wallet # Corp contracts, contacts, wallets
790
+ ```
791
+
792
+ ### Write Operations (require specific scopes + caution)
793
+
794
+ ```bash
795
+ npm run example:write-ops # Contacts, fittings, mail, UI lifecycle tests
796
+ npm run example:universe-posts # Name resolution + character affiliation (public)
797
+ npm run example:freelance-jobs # Freelance job queries
798
+ ```
799
+
800
+ ### Parallel Requests
801
+
802
+ ```typescript
803
+ const [character, portrait, corp] = await Promise.all([
804
+ client.characters.getCharacterPublicInfo(characterId),
805
+ client.characters.getCharacterPortrait(characterId),
806
+ client.corporations.getCorporationInfo(corporationId),
807
+ ]);
808
+
809
+ console.log(`${character.name} [${corp.ticker}]`);
810
+ ```
811
+
812
+ ### Market Analysis
813
+
814
+ ```typescript
815
+ const [orders, history] = await Promise.all([
816
+ client.market.getMarketOrders(regionId),
817
+ client.market.getMarketHistory(regionId, typeId),
818
+ ]);
819
+
820
+ const buyOrders = orders.filter((o) => o.is_buy_order);
821
+ const sellOrders = orders.filter((o) => !o.is_buy_order);
822
+
823
+ console.log(`Best buy: ${Math.max(...buyOrders.map((o) => o.price))}`);
824
+ console.log(`Best sell: ${Math.min(...sellOrders.map((o) => o.price))}`);
825
+ ```
826
+
827
+ ## Resource Management
828
+
829
+ Always call `shutdown()` when you're done to clean up cache timers:
830
+
831
+ ```typescript
832
+ const client = new EsiClient();
833
+ try {
834
+ const status = await client.status.getStatus();
835
+ console.log(status.server_version);
836
+ } finally {
837
+ await client.shutdown();
838
+ }
839
+ ```
840
+
841
+ ## Testing
842
+
843
+ ESI.ts has a comprehensive multi-tier testing strategy with 139 suites and 4,104 tests:
844
+
845
+ | Tier | Tests | Purpose |
846
+ | -------------------------- | ---------------- | ------------------------------------------------------------------ |
847
+ | **TDD unit tests** | 100 files | Every client method, endpoint path, query param, and body format |
848
+ | **BDD scenario tests** | 41 feature files | Behavioral specifications in Gherkin (Given/When/Then) |
849
+ | **Mocked integration** | Full suite | Cross-layer request flow with jest-fetch-mock |
850
+ | **Live smoke tests** | 46 examples | Every endpoint against live Tranquility |
851
+ | **ESI spec contract** | 15 tests | Endpoint definitions validated against live OpenAPI spec |
852
+ | **Deep contract tests** | 8 categories | Path params, query params, body, auth, schemas, pagination vs spec |
853
+ | **Property-based fuzzing** | 601 tests | fast-check fuzzing of validation, URL construction, Zod schemas |
854
+ | **Mutation testing** | Stryker | Validates test suite kills code mutants |
855
+ | **Type-level tests** | tsd | Consumer API type correctness via tsd |
856
+ | **Gated auth tests** | 33 tests | Authenticated endpoints with real tokens |
857
+ | **Construction parity** | Per-surface | Verifies all client surfaces get identical middleware defaults |
858
+ | **Spec-alignment** | Type assertions | Ensures hand-written types align with generated OpenAPI types |
859
+
860
+ ```bash
861
+ npm test # Unit + BDD tests (143 suites, 4,182 tests)
862
+ npm run coverage # Tests with coverage report (thresholds enforced)
863
+ npm run bdd # BDD scenario tests only
864
+ npm run contract # Contract tests (skipped without ESI_LIVE_TESTS=true)
865
+ npm run fuzz # Property-based fuzz tests (601 tests)
866
+ npm run mutation # Mutation testing (Stryker)
867
+ npm run benchmark # Performance benchmark tests
868
+ npm run test:types # tsd consumer type tests
869
+ ```
870
+
871
+ Coverage: statements 98.47%, branches 90.10%, functions 97.54%, lines 98.59%. Thresholds enforced in CI: branches 80%, functions 75%, lines 90%, statements 90%.
872
+
873
+ See [guides/TESTING.md](guides/TESTING.md) for the full testing guide, and [guides/ARCHITECTURE.md](guides/ARCHITECTURE.md) for architecture diagrams.
874
+
875
+ ## Development
876
+
877
+ ### Prerequisites
878
+
879
+ - Node.js 18+
880
+ - npm
881
+
882
+ ### Code Quality Tools
883
+
884
+ The project uses a comprehensive suite of static analysis and code quality tools:
885
+
886
+ | Tool | Purpose | Command |
887
+ | ------------------------------------------------------------------------------------ | ------------------------------------------------------- | ------------------------------ |
888
+ | [ESLint](https://eslint.org/) | Linting with TypeScript, security, and code smell rules | `npm run lint` |
889
+ | [Prettier](https://prettier.io/) | Code formatting | `npm run format:check` |
890
+ | [knip](https://knip.dev/) | Dead code and unused export detection | `npm run knip` |
891
+ | [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security) | Security anti-pattern detection | Integrated into `npm run lint` |
892
+ | [eslint-plugin-sonarjs](https://github.com/SonarSource/eslint-plugin-sonarjs) | Cognitive complexity and code smell detection | Integrated into `npm run lint` |
893
+ | [husky](https://typicode.github.io/husky/) | Git pre-commit hooks | Automatic on commit |
894
+ | [lint-staged](https://github.com/lint-staged/lint-staged) | Run linters on staged files only | Automatic on commit |
895
+ | [Redocly CLI](https://redocly.com/docs/cli/) | OpenAPI spec validation and linting | `npm run validate:spec` |
896
+
897
+ ### Available Scripts
898
+
899
+ ```bash
900
+ # Development
901
+ npm run build # Compile TypeScript
902
+ npm run lint # Run ESLint
903
+ npm run lint:fix # Run ESLint with auto-fix
904
+ npm run format # Format code with Prettier
905
+ npm run format:check # Check formatting without modifying
906
+
907
+ # Testing
908
+ npm test # Unit tests (143 suites, 4,182 tests)
909
+ npm run test:all # Unit + BDD + integration + fuzz + type tests
910
+ npm run coverage # Tests with coverage report (thresholds enforced)
911
+ npm run bdd # BDD scenario tests
912
+ npm run contract:live # Deep contract tests against live ESI spec
913
+ npm run fuzz # Property-based fuzz tests (fast-check)
914
+ npm run mutation # Mutation testing (Stryker)
915
+ npm run benchmark # Performance benchmark tests
916
+ npm run test:types # Consumer type tests (tsd)
917
+ npm run mock:esi # Start Prism mock ESI server on port 4010
918
+
919
+ # Static Analysis
920
+ npm run knip # Detect dead code and unused exports
921
+ npm run validate:esi # Validate endpoints against live ESI OpenAPI spec
922
+ npm run validate:spec # Lint ESI OpenAPI spec with Redocly (structural + best practices)
923
+ npm run validate:auth-scopes # Auth/scope cross-validation
924
+ npm run schema:drift # Schema drift detection (hand-written vs OpenAPI spec)
925
+ npm run validate # Run all checks: lint, format, build, coverage, knip
926
+ npm run generate:types # Regenerate TypeScript interfaces from ESI OpenAPI spec
927
+ npm run generate:endpoints # Regenerate endpoint definitions from ESI OpenAPI spec
928
+ npm run generate:all # Run all generators (types + endpoints + OKF)
929
+ npm run generate:okf # Generate OKF knowledge bundle from ESI OpenAPI spec
930
+
931
+ # Documentation
932
+ npm run docs # Generate TypeDoc API documentation
933
+ npm run docs:serve # Serve docs locally on port 8080
934
+ ```
935
+
936
+ ### ESI Endpoint Validation
937
+
938
+ To verify that the codebase endpoint definitions match the live ESI OpenAPI spec:
939
+
940
+ ```bash
941
+ npm run validate:esi
942
+ ```
943
+
944
+ This fetches the ESI OpenAPI spec and reports:
945
+
946
+ - Endpoints in the codebase that are no longer in the ESI spec
947
+ - Endpoints in the ESI spec that the codebase doesn't cover
948
+ - HTTP method mismatches between codebase and spec
949
+
950
+ ### Pre-commit Hooks
951
+
952
+ The project uses husky with lint-staged to run ESLint and Prettier on staged files before each commit. This is set up automatically when you run `npm install`.
953
+
954
+ ### CI/CD
955
+
956
+ Every pull request runs the full validation suite:
957
+
958
+ - ESLint (with security and sonarjs plugins)
959
+ - Prettier formatting check
960
+ - TypeScript compilation
961
+ - Generated types staleness check (regenerates from live ESI OpenAPI spec and verifies no diff)
962
+ - Unit tests across Node.js 18, 20, and 22
963
+ - BDD scenario tests
964
+ - Coverage threshold enforcement (branches: 80%, functions: 75%, lines: 90%, statements: 90%)
965
+ - Auth/scopes cross-validation
966
+ - Spec-alignment type assertions
967
+ - Schema drift detection
968
+ - Mutation testing (Stryker)
969
+ - Dead code detection via knip
970
+ - npm security audit
971
+
972
+ See [.github/workflows/README.md](.github/workflows/README.md) for full workflow details.
973
+
974
+ ## Contributing
975
+
976
+ 1. Fork the repository
977
+ 2. Create a feature branch
978
+ 3. Write tests for your changes
979
+ 4. Run `npm run validate` to check everything passes
980
+ 5. Open a Pull Request
981
+
982
+ ## License
983
+
984
+ GPL-3.0-or-later - see the [LICENSE](LICENSE) file for details.
985
+
986
+ ---
987
+
988
+ **o7**