@lgriffin/esi.ts 8.0.0 → 9.0.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 (107) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +26 -26
  3. package/README.md +986 -967
  4. package/dist/config/jest/globalSetup.d.ts.map +1 -1
  5. package/dist/config/jest/globalTeardown.d.ts.map +1 -1
  6. package/dist/core/configureApiClient.d.ts.map +1 -1
  7. package/dist/core/pagination/CursorPaginationHandler.d.ts +9 -4
  8. package/dist/core/pagination/CursorPaginationHandler.d.ts.map +1 -1
  9. package/dist/core/pagination/PaginationHandler.d.ts +6 -5
  10. package/dist/core/pagination/PaginationHandler.d.ts.map +1 -1
  11. package/dist/core/requestPipeline/cachePolicy.d.ts +1 -0
  12. package/dist/core/requestPipeline/cachePolicy.d.ts.map +1 -1
  13. package/dist/core/requestPipeline/paginationOrchestration.d.ts.map +1 -1
  14. package/dist/core/requestPipeline/statusHandling.d.ts.map +1 -1
  15. package/dist/core/util/error.d.ts +2 -0
  16. package/dist/core/util/error.d.ts.map +1 -1
  17. package/dist/errors.d.ts +4 -0
  18. package/dist/errors.d.ts.map +1 -0
  19. package/dist/errors.js +196 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/errors.mjs +146 -0
  22. package/dist/errors.mjs.map +1 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +400 -389
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +399 -389
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/schemas/index.js +2087 -0
  30. package/dist/schemas/index.js.map +1 -0
  31. package/dist/schemas/index.mjs +1914 -0
  32. package/dist/schemas/index.mjs.map +1 -0
  33. package/dist/testing/index.d.ts +2 -0
  34. package/dist/testing/index.d.ts.map +1 -0
  35. package/dist/testing/index.js +935 -0
  36. package/dist/testing/index.js.map +1 -0
  37. package/dist/testing/index.mjs +898 -0
  38. package/dist/testing/index.mjs.map +1 -0
  39. package/dist/types/generated/esi-spec.generated.d.ts +3 -3
  40. package/dist/types/generated/esi-spec.generated.d.ts.map +1 -1
  41. package/package.json +253 -235
  42. package/dist/schemas/generated/alliance.generated.d.ts +0 -15
  43. package/dist/schemas/generated/alliance.generated.d.ts.map +0 -1
  44. package/dist/schemas/generated/assets.generated.d.ts +0 -272
  45. package/dist/schemas/generated/assets.generated.d.ts.map +0 -1
  46. package/dist/schemas/generated/calendar.generated.d.ts +0 -41
  47. package/dist/schemas/generated/calendar.generated.d.ts.map +0 -1
  48. package/dist/schemas/generated/character.generated.d.ts +0 -670
  49. package/dist/schemas/generated/character.generated.d.ts.map +0 -1
  50. package/dist/schemas/generated/clones.generated.d.ts +0 -23
  51. package/dist/schemas/generated/clones.generated.d.ts.map +0 -1
  52. package/dist/schemas/generated/contacts.generated.d.ts +0 -50
  53. package/dist/schemas/generated/contacts.generated.d.ts.map +0 -1
  54. package/dist/schemas/generated/contracts.generated.d.ts +0 -162
  55. package/dist/schemas/generated/contracts.generated.d.ts.map +0 -1
  56. package/dist/schemas/generated/corporation-projects.generated.d.ts +0 -89
  57. package/dist/schemas/generated/corporation-projects.generated.d.ts.map +0 -1
  58. package/dist/schemas/generated/corporation.generated.d.ts +0 -1515
  59. package/dist/schemas/generated/corporation.generated.d.ts.map +0 -1
  60. package/dist/schemas/generated/dogma.generated.d.ts +0 -57
  61. package/dist/schemas/generated/dogma.generated.d.ts.map +0 -1
  62. package/dist/schemas/generated/faction-warfare.generated.d.ts +0 -155
  63. package/dist/schemas/generated/faction-warfare.generated.d.ts.map +0 -1
  64. package/dist/schemas/generated/fittings.generated.d.ts +0 -57
  65. package/dist/schemas/generated/fittings.generated.d.ts.map +0 -1
  66. package/dist/schemas/generated/fleets.generated.d.ts +0 -45
  67. package/dist/schemas/generated/fleets.generated.d.ts.map +0 -1
  68. package/dist/schemas/generated/freelance-jobs.generated.d.ts +0 -173
  69. package/dist/schemas/generated/freelance-jobs.generated.d.ts.map +0 -1
  70. package/dist/schemas/generated/incursions.generated.d.ts +0 -16
  71. package/dist/schemas/generated/incursions.generated.d.ts.map +0 -1
  72. package/dist/schemas/generated/index.d.ts +0 -33
  73. package/dist/schemas/generated/index.d.ts.map +0 -1
  74. package/dist/schemas/generated/industry.generated.d.ts +0 -117
  75. package/dist/schemas/generated/industry.generated.d.ts.map +0 -1
  76. package/dist/schemas/generated/insurance.generated.d.ts +0 -10
  77. package/dist/schemas/generated/insurance.generated.d.ts.map +0 -1
  78. package/dist/schemas/generated/killmails.generated.d.ts +0 -55
  79. package/dist/schemas/generated/killmails.generated.d.ts.map +0 -1
  80. package/dist/schemas/generated/location.generated.d.ts +0 -18
  81. package/dist/schemas/generated/location.generated.d.ts.map +0 -1
  82. package/dist/schemas/generated/loyalty.generated.d.ts +0 -18
  83. package/dist/schemas/generated/loyalty.generated.d.ts.map +0 -1
  84. package/dist/schemas/generated/mail.generated.d.ts +0 -68
  85. package/dist/schemas/generated/mail.generated.d.ts.map +0 -1
  86. package/dist/schemas/generated/market.generated.d.ts +0 -201
  87. package/dist/schemas/generated/market.generated.d.ts.map +0 -1
  88. package/dist/schemas/generated/meta.generated.d.ts +0 -26
  89. package/dist/schemas/generated/meta.generated.d.ts.map +0 -1
  90. package/dist/schemas/generated/planetary-interaction.generated.d.ts +0 -90
  91. package/dist/schemas/generated/planetary-interaction.generated.d.ts.map +0 -1
  92. package/dist/schemas/generated/routes.generated.d.ts +0 -5
  93. package/dist/schemas/generated/routes.generated.d.ts.map +0 -1
  94. package/dist/schemas/generated/search.generated.d.ts +0 -15
  95. package/dist/schemas/generated/search.generated.d.ts.map +0 -1
  96. package/dist/schemas/generated/skills.generated.d.ts +0 -32
  97. package/dist/schemas/generated/skills.generated.d.ts.map +0 -1
  98. package/dist/schemas/generated/sovereignty.generated.d.ts +0 -37
  99. package/dist/schemas/generated/sovereignty.generated.d.ts.map +0 -1
  100. package/dist/schemas/generated/status.generated.d.ts +0 -8
  101. package/dist/schemas/generated/status.generated.d.ts.map +0 -1
  102. package/dist/schemas/generated/universe.generated.d.ts +0 -394
  103. package/dist/schemas/generated/universe.generated.d.ts.map +0 -1
  104. package/dist/schemas/generated/wallet.generated.d.ts +0 -411
  105. package/dist/schemas/generated/wallet.generated.d.ts.map +0 -1
  106. package/dist/schemas/generated/wars.generated.d.ts +0 -31
  107. package/dist/schemas/generated/wars.generated.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,967 +1,986 @@
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.0.0** — Default retry count changed from 0 to 3, sub-path exports (`@lgriffin/esi.ts/schemas`, `/errors`, `/testing`), `isCircuitOpen()` type guard, cursor pagination routed through full pipeline, unified pagination retry via `IRetryStrategy`, response interceptor status fix, and CI consolidation.
13
+
14
+ **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.**
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. | 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). |
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. | 139 test suites, 4,104 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. |
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 (139 suites, 4,104 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
+ | Corporations | `client.corporations` | Some | `getCorporationInfo(id)`, `getCorporationMembers(id)` |
270
+ | Dogma | `client.dogma` | No | `getDogmaAttributes()`, `getDynamicItemInfo(typeId, itemId)` |
271
+ | Factions | `client.factions` | Some | `getFactionWarStats()` |
272
+ | Fittings | `client.fittings` | Yes | `getFittings(id)`, `createFitting(id, body)` |
273
+ | Fleets | `client.fleets` | Yes | `getFleetInformation(id)`, `getFleetMembers(id)` |
274
+ | Incursions | `client.incursions` | No | `getIncursions()` |
275
+ | Industry | `client.industry` | Some | `getCharacterIndustryJobs(id)` |
276
+ | Insurance | `client.insurance` | No | `getInsurancePrices()` |
277
+ | Killmails | `client.killmails` | Some | `getKillmail(id, hash)` |
278
+ | Location | `client.location` | Yes | `getCharacterLocation(id)` |
279
+ | Loyalty | `client.loyalty` | Yes | `getCharacterLoyaltyPoints(id)` |
280
+ | Mail | `client.mail` | Yes | `getCharacterMail(id)`, `sendMail(id, body)` |
281
+ | Market | `client.market` | Some | `getMarketPrices()`, `getMarketOrders(regionId)` |
282
+ | PI | `client.pi` | Yes | `getCharacterPlanets(id)` |
283
+ | Route | `client.route` | No | `getRoute(origin, destination)` |
284
+ | Search | `client.search` | Some | `search(characterId, query)` |
285
+ | Skills | `client.skills` | Yes | `getCharacterSkills(id)` |
286
+ | Sovereignty | `client.sovereignty` | No | `getSovereigntySystems()`, `getSovereigntyMap()` |
287
+ | Skyhooks | `client.skyhooks` | No | `getSovereigntyHubs()`, `getRaidableSkyhooks()` |
288
+ | Mercenary | `client.mercenary` | No | `getMercenaryDens()`, `getMercenaryTacticalOperations()` |
289
+ | Access Lists | `client.accessLists` | Yes | `getAccessList(id)` |
290
+ | Status | `client.status` | No | `getStatus()` |
291
+ | UI | `client.ui` | Yes | `setAutopilotWaypoint(destId, addToBeginning, clear)`, `openNewMailWindow(body)` |
292
+ | Universe | `client.universe` | Some | `getSystemById(id)`, `getTypeById(id)` |
293
+ | Wallet | `client.wallet` | Yes | `getCharacterWallet(id)` |
294
+ | Wars | `client.wars` | No | `getWars()`, `getWarById(id)` |
295
+ | Freelance Jobs | `client.freelanceJobs` | Some | `getFreelanceJobs()`, `getFreelanceJobById(id)` |
296
+ | Meta | `client.meta` | No | `getOpenApiJson()`, `getOpenApiYaml()` |
297
+
298
+ ## Runtime Response Validation
299
+
300
+ 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.
301
+
302
+ 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.
303
+
304
+ ```typescript
305
+ import {
306
+ EsiClient,
307
+ EsiValidationError,
308
+ isValidationError,
309
+ schemas,
310
+ } from '@lgriffin/esi.ts';
311
+
312
+ const client = new EsiClient();
313
+
314
+ // Validation happens automatically on every request
315
+ const character = await client.characters.getCharacterPublicInfo(12345);
316
+
317
+ // Disable validation globally if needed
318
+ const rawClient = new EsiClient({ validateResponse: false });
319
+
320
+ // Use schemas directly for your own validation
321
+ const result = schemas.CharacterInfoSchema.safeParse(someData);
322
+ if (result.success) {
323
+ console.log(result.data.name);
324
+ }
325
+ ```
326
+
327
+ ### Request Body Validation
328
+
329
+ For POST/PUT/DELETE endpoints, opt-in request body validation ensures outgoing payloads match the endpoint's `requestSchema` before the request is sent:
330
+
331
+ ```typescript
332
+ // Opt-in request body validation for POST/PUT/DELETE
333
+ const client = new EsiClient({ validateRequest: true });
334
+
335
+ // Throws EsiValidationError if the request body doesn't match the endpoint's requestSchema
336
+ await client.mail.sendMail(characterId, {
337
+ recipients: [{ recipient_id: 12345, recipient_type: 'character' }],
338
+ subject: 'Hello',
339
+ body: 'Message body',
340
+ });
341
+ ```
342
+
343
+ See [guides/RUNTIME-VALIDATION.md](guides/RUNTIME-VALIDATION.md) for the full guide on schemas, error handling, and extending schemas.
344
+
345
+ ## Caching
346
+
347
+ ETag caching is enabled by default. The client automatically:
348
+
349
+ 1. Stores ETag and response data on GET requests
350
+ 2. Sends `If-None-Match` on subsequent requests
351
+ 3. Returns cached data on `304 Not Modified`
352
+ 4. Parses `Cache-Control: max-age` from ESI for per-endpoint TTL
353
+ 5. Serves stale cached data when ESI returns 5xx errors
354
+ 6. Invalidates related GET caches when POST/PUT/DELETE requests are made
355
+
356
+ ```typescript
357
+ // Cache stats
358
+ const stats = client.getCacheStats();
359
+ console.log(`${stats.totalEntries}/${stats.maxEntries} entries cached`);
360
+
361
+ // Manual cache operations
362
+ client.clearCache();
363
+ client.updateCacheConfig({ maxEntries: 2000 });
364
+
365
+ // Disable caching entirely
366
+ const uncachedClient = new EsiClient({ enableETagCache: false });
367
+ ```
368
+
369
+ ### Spec-Aware Cache TTLs
370
+
371
+ 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.
372
+
373
+ This layers on top of ETag caching in three tiers:
374
+
375
+ 1. **Spec TTL** — data can't have changed yet, return cached data immediately
376
+ 2. **ETag conditional GET** — data might have changed, send `If-None-Match` to check
377
+ 3. **Full request** — no cache entry, fetch fresh data
378
+
379
+ ```typescript
380
+ const client = new EsiClient();
381
+
382
+ // First call — fetches from ESI
383
+ const alliances = await client.alliance.getAlliances();
384
+
385
+ // Second call within the next 3600s — returns cached data, zero HTTP calls
386
+ const same = await client.alliance.getAlliances();
387
+ ```
388
+
389
+ ## Batch Requests
390
+
391
+ Fetch data for multiple IDs with bounded concurrency using `batch()`, or chunk large POST payloads with `batchPost()`:
392
+
393
+ ```typescript
394
+ import { EsiClient } from '@lgriffin/esi.ts';
395
+
396
+ const client = new EsiClient();
397
+
398
+ // Fetch 500 type details with at most 10 concurrent requests
399
+ const result = await client.batch(
400
+ typeIds,
401
+ (id) => client.universe.getTypeById(id),
402
+ {
403
+ concurrency: 10,
404
+ onProgress: (done, total) => console.log(`${done}/${total}`),
405
+ },
406
+ );
407
+
408
+ // result.results: Map<number, T> — successful responses
409
+ // result.errors: Map<number, Error> — failed requests
410
+ console.log(`${result.results.size} succeeded, ${result.errors.size} failed`);
411
+ ```
412
+
413
+ For POST endpoints that accept arrays (e.g., `postUniverseNames` with a 1000-ID limit), `batchPost` auto-chunks and concatenates:
414
+
415
+ ```typescript
416
+ const allNames = await client.batchPost(
417
+ largeIdArray,
418
+ (chunk) => client.universe.postUniverseNames(chunk),
419
+ 1000, // chunk size
420
+ );
421
+ ```
422
+
423
+ ## Streaming Pagination
424
+
425
+ 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:
426
+
427
+ ```typescript
428
+ import { EsiClient } from '@lgriffin/esi.ts';
429
+
430
+ const client = new EsiClient();
431
+
432
+ // Stream all market orders in The Forge, page by page
433
+ for await (const page of client.market.streamMarketOrders(10000002)) {
434
+ console.log(
435
+ `Page ${page.page}/${page.totalPages}: ${page.data.length} orders`,
436
+ );
437
+
438
+ // Process each order as it arrives
439
+ for (const order of page.data) {
440
+ if (order.is_buy_order && order.price > 1_000_000) {
441
+ console.log(`High-value buy: ${order.type_id} @ ${order.price} ISK`);
442
+ }
443
+ }
444
+
445
+ // Early termination — stops fetching remaining pages
446
+ if (page.page >= 3) break;
447
+ }
448
+ ```
449
+
450
+ 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.
451
+
452
+ Available streaming methods (representative selection):
453
+
454
+ - **MarketClient** — `streamMarketOrders`, `streamMarketTypes`, `streamCharacterOrderHistory`, `streamCorporationOrders`, `streamCorporationOrderHistory`, `streamMarketOrdersInStructure`
455
+ - **CorporationsClient** — `streamCorporationMembers`, `streamCorporationStructures`, `streamCorporationBlueprints`, + 14 more
456
+ - **CharacterClient** — `streamCharacterBlueprints`, `streamCharacterNotifications`, `streamCharacterStandings`, + 5 more
457
+ - **ContractsClient** — `streamPublicContracts`, `streamCharacterContracts`, `streamCorporationContracts`
458
+ - **WalletClient** — `streamCharacterWalletJournal`, `streamCorporationWalletJournal`, `streamCharacterWalletTransactions`
459
+ - **IndustryClient** — `streamCorporationIndustryJobs`, `streamCorporationMiningObservers`, + 6 more
460
+ - **ContactsClient** — `streamAllianceContacts`, `streamCharacterContacts`, `streamCorporationContacts`, + 3 more
461
+ - **AssetsClient** — `streamCharacterAssets`, `streamCorporationAssets`
462
+ - **KillmailsClient** — `streamCharacterRecentKillmails`, `streamCorporationRecentKillmails`
463
+ - **MailClient** — `streamCharacterMail`, `streamCharacterMailLabels`
464
+ - **FleetsClient** — `streamFleetMembers`, `streamFleetWings`
465
+ - **CalendarClient** — `streamCalendarEvents`
466
+ - **FittingsClient** — `streamCharacterFittings`
467
+ - **SkillsClient** — `streamCharacterSkillQueue`
468
+ - **LoyaltyClient** — `streamCorporationLoyaltyStoreOffers`
469
+ - **BookmarksClient** — `streamCharacterBookmarks`, `streamCorporationBookmarks`
470
+ - **ClonesClient** — `streamCharacterImplants`
471
+ - **PIClient** — `streamCharacterPlanets`
472
+ - **WarsClient** — `streamWars`
473
+ - **FactionWarfareClient** — `streamFactionWarfareStats`
474
+ - **AllianceClient** — `streamAllianceCorporations`
475
+
476
+ Try it: `npm run example:streaming`
477
+
478
+ ## Cursor-based Pagination
479
+
480
+ 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.
481
+
482
+ ```typescript
483
+ import { EsiClient, fetchAllCursorPages } from '@lgriffin/esi.ts';
484
+
485
+ const client = new EsiClient();
486
+
487
+ // Fetch first page — returns { cursor: { before, after }, freelance_jobs: [...] }
488
+ const page = await client.freelanceJobs.getFreelanceJobs();
489
+ console.log(page.freelance_jobs); // job records
490
+ console.log(page.cursor.after); // opaque token for next page
491
+
492
+ // Fetch next page using the cursor
493
+ const nextPage = await client.freelanceJobs.getFreelanceJobs(
494
+ undefined,
495
+ page.cursor.after,
496
+ );
497
+
498
+ // Auto-fetch all pages in one call
499
+ const allJobs = await fetchAllCursorPages(
500
+ (before, after) => client.freelanceJobs.getFreelanceJobs(before, after),
501
+ (response) => response.freelance_jobs,
502
+ (response) => response.cursor,
503
+ );
504
+
505
+ // Authenticated endpoints — character/corporation freelance jobs
506
+ const authedClient = new EsiClient({ accessToken: 'your-token' });
507
+ const myJobs =
508
+ await authedClient.freelanceJobs.getCharacterFreelanceJobs(characterId);
509
+ const corpJobs =
510
+ await authedClient.freelanceJobs.getCorporationFreelanceJobs(corporationId);
511
+ ```
512
+
513
+ **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:
514
+
515
+ ```typescript
516
+ // After initial scan, save the final cursor
517
+ let savedCursor = lastPage.cursor.after;
518
+
519
+ // Later: check for updates (hours, days, or weeks later)
520
+ const updates = await client.freelanceJobs.getFreelanceJobs(
521
+ undefined,
522
+ savedCursor,
523
+ );
524
+ if (updates.freelance_jobs.length > 0) {
525
+ // Process changed records — duplicates are expected for modified records
526
+ savedCursor = updates.cursor.after;
527
+ }
528
+ ```
529
+
530
+ Key points:
531
+
532
+ - Cursor tokens are **opaque strings** — never parse or validate them
533
+ - An **empty result array** signals the end of the dataset (not a short page)
534
+ - **Duplicates across pages** are expected when records are modified between requests
535
+ - Existing offset-based routes (`getMarketOrders`, etc.) are unchanged
536
+
537
+ ## Generated Types
538
+
539
+ 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:
540
+
541
+ ```typescript
542
+ import { EsiSpec } from '@lgriffin/esi.ts';
543
+
544
+ // Generated type — uses OpenAPI schema names (v7.0.0+)
545
+ const order: EsiSpec.MarketsRegionIdOrdersGet = {
546
+ order_id: 123,
547
+ type_id: 34,
548
+ price: 5.5,
549
+ volume_remain: 1000,
550
+ volume_total: 5000,
551
+ is_buy_order: false,
552
+ // ...
553
+ };
554
+ ```
555
+
556
+ To regenerate types from the latest ESI spec:
557
+
558
+ ```bash
559
+ npm run generate:types # fetches OpenAPI spec, generates 161 interfaces + cache TTL map + rate limit groups + scope map
560
+ npm run validate:esi # reports type drift between hand-written and generated types
561
+ ```
562
+
563
+ ## ESI Scopes
564
+
565
+ 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:
566
+
567
+ ```typescript
568
+ import { esiEndpointScopes, EsiScope } from '@lgriffin/esi.ts';
569
+
570
+ // Look up scopes for a specific endpoint
571
+ const walletScopes = esiEndpointScopes['GET:characters/{character_id}/wallet'];
572
+ // → ['esi-wallet.read_character_wallet.v1']
573
+
574
+ // Check if an endpoint requires auth
575
+ const isPublic = !esiEndpointScopes['GET:universe/types/{type_id}'];
576
+ // → true (public endpoint, no scopes needed)
577
+
578
+ // Type-safe scope values
579
+ const scope: EsiScope = 'esi-assets.read_assets.v1';
580
+ ```
581
+
582
+ ## Error Handling
583
+
584
+ API errors throw `EsiError` with `statusCode`, `message`, and `url` properties:
585
+
586
+ ```typescript
587
+ import {
588
+ EsiError,
589
+ TimeoutError,
590
+ EsiValidationError,
591
+ isTimeout,
592
+ isRetryable,
593
+ isValidationError,
594
+ isCircuitOpen,
595
+ } from '@lgriffin/esi.ts';
596
+
597
+ try {
598
+ const alliance = await client.alliance.getAllianceById(99999999);
599
+ console.log('Alliance:', alliance.name);
600
+ } catch (err) {
601
+ if (isCircuitOpen(err)) {
602
+ console.log('Circuit breaker is open — endpoint temporarily unavailable');
603
+ } else if (isValidationError(err)) {
604
+ console.log('Response validation failed:', err.validationError);
605
+ } else if (isTimeout(err)) {
606
+ console.log(`Request timed out after ${err.timeoutMs}ms`);
607
+ } else if (err instanceof EsiError) {
608
+ console.log(`ESI error ${err.statusCode}: ${err.message}`);
609
+ console.log(`Retryable: ${err.retryable}`);
610
+ }
611
+ }
612
+ ```
613
+
614
+ - **204 No Content** — returns `undefined` (valid for DELETE/POST actions)
615
+ - **304 Not Modified** — handled internally, returns cached data
616
+ - **4xx/5xx** — throws `EsiError`
617
+ - **5xx with cache** — returns stale cached data instead of throwing
618
+ - **Timeout** — throws `TimeoutError` (extends `EsiError` with `statusCode: 0` and `timeoutMs`)
619
+ - **Retryable errors** — `EsiError.retryable` returns `true` for 502, 503, 504, 420, 429, and timeouts
620
+ - **Validation errors** — throws `EsiValidationError` (extends `EsiError`) when response data doesn't match the expected Zod schema
621
+
622
+ ## Response Metadata
623
+
624
+ Use `withMetadata()` to get response headers, cache status, rate limit info, and timing alongside the data:
625
+
626
+ ```typescript
627
+ const metaClient = client.alliance.withMetadata();
628
+ const result = await metaClient.getAllianceById(99000001);
629
+
630
+ console.log(result.data.name); // "Goonswarm Federation"
631
+ console.log(result.meta.fromCache); // true if served from cache
632
+ console.log(result.meta.cacheHitType); // 'spec-ttl' | 'etag-304' | 'stale-on-error'
633
+ console.log(result.meta.responseTimeMs); // milliseconds
634
+ console.log(result.meta.rateLimit); // { remaining, limit, used, group }
635
+ console.log(result.meta.requestId); // ESI request ID for debugging
636
+ ```
637
+
638
+ The `meta` object includes:
639
+
640
+ | Field | Type | Description |
641
+ | ---------------- | ------------------------ | ------------------------------------------------- |
642
+ | `headers` | `Record<string, string>` | Raw response headers |
643
+ | `fromCache` | `boolean` | Whether data was served from cache |
644
+ | `stale` | `boolean` | Whether cached data is stale (5xx fallback) |
645
+ | `cacheHitType` | `string?` | `'spec-ttl'`, `'etag-304'`, or `'stale-on-error'` |
646
+ | `rateLimit` | `RateLimitMeta?` | Rate limit status from ESI headers |
647
+ | `responseTimeMs` | `number?` | Request duration in milliseconds |
648
+ | `requestId` | `string?` | ESI request ID |
649
+ | `warning` | `object?` | ESI deprecation warning |
650
+
651
+ ## Rate Limiting
652
+
653
+ 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.
654
+
655
+ Rate limiting works out of the box with no configuration. For multi-character applications, enable per-user bucketing:
656
+
657
+ ```typescript
658
+ import { EsiClient } from '@lgriffin/esi.ts';
659
+
660
+ const client = new EsiClient({
661
+ rateLimiterConfig: {
662
+ userKeyExtractor: (headers) => headers['authorization'] ?? 'anon',
663
+ },
664
+ });
665
+ ```
666
+
667
+ Monitor rate limit status per group:
668
+
669
+ ```typescript
670
+ const limiter = client.getRateLimiter();
671
+
672
+ // Worst-case across all groups (backward-compatible)
673
+ const status = limiter.getStatus();
674
+ console.log(status.remaining, status.limit, status.group);
675
+
676
+ // Specific group
677
+ const marketStatus = limiter.getGroupStatus('market-order');
678
+ console.log(marketStatus?.remaining); // tokens remaining in this group
679
+
680
+ // All active groups
681
+ const all = limiter.getAllGroupStatuses();
682
+ for (const [group, info] of all) {
683
+ console.log(`${group}: ${info.remaining}/${info.limit}`);
684
+ }
685
+
686
+ // Check if a specific group is blocked
687
+ console.log(limiter.isBlocked('char-notification')); // true if 429'd
688
+ ```
689
+
690
+ ## Lightweight Clients
691
+
692
+ 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.
693
+
694
+ If you only need a subset of APIs, use `CustomEsiClient` or `EsiClientBuilder` to load only what you need:
695
+
696
+ ```typescript
697
+ import { EsiClientBuilder } from '@lgriffin/esi.ts';
698
+
699
+ const client = new EsiClientBuilder()
700
+ .addClients(['market', 'universe', 'characters'])
701
+ .withClientId('my-trading-bot')
702
+ .withAccessToken('your-token')
703
+ .build();
704
+
705
+ const prices = await client.market?.getMarketPrices();
706
+ const system = await client.universe?.getSystemById(30000142);
707
+ ```
708
+
709
+ Or create standalone single-API clients:
710
+
711
+ ```typescript
712
+ import { EsiApiFactory } from '@lgriffin/esi.ts';
713
+
714
+ const marketClient = EsiApiFactory.createMarketClient({
715
+ clientId: 'price-checker',
716
+ });
717
+ const prices = await marketClient.getMarketPrices();
718
+ ```
719
+
720
+ ## Endpoint Coverage
721
+
722
+ 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).
723
+
724
+ | Category | Endpoints | Method |
725
+ | --------------------------- | --------- | -------------------------------------------------- |
726
+ | Public GETs | 78 | 43 runnable example scripts with captured output |
727
+ | Authenticated GETs | 72 | Example scripts + live testing with EVE SSO tokens |
728
+ | Contacts (POST/PUT/DELETE) | 3 | Live create/edit/delete lifecycle |
729
+ | Fittings (POST/DELETE) | 2 | Live create/delete lifecycle |
730
+ | Mail (POST/PUT/DELETE) | 5 | Live send/label/metadata/delete lifecycle |
731
+ | UI (POST) | 5 | Live testing with EVE client running |
732
+ | Calendar (PUT) | 1 | Live RSVP to event |
733
+ | Fleet (GET/POST/PUT/DELETE) | 14 | Live fleet with fleet commander + squad members |
734
+ | Assets POST | 3 | Live asset location/name queries |
735
+ | CSPA (POST) | 1 | Live charge cost calculation |
736
+ | Dogma dynamic (GET) | 1 | Live mutaplasmid (Abyssal) item query |
737
+ | Universe POST helpers | 3 | Live name resolution and affiliation |
738
+ | Freelance Jobs (GET) | 4 | Live queries (graceful 404 for no active jobs) |
739
+
740
+ ## Examples
741
+
742
+ 43 runnable examples are in the `examples/` directory.
743
+
744
+ ### Public Endpoints (no auth needed)
745
+
746
+ ```bash
747
+ npm run example:status # Server status — quickest smoke test
748
+ npm run example:character # Character public info, portrait, corporation
749
+ npm run example:universe # Solar system, constellation, region, station
750
+ npm run example:market # Average prices + Tritanium price history
751
+ npm run example:alliance # Alliance info + member corporations
752
+ npm run example:route # Jita-to-Amarr route with system names
753
+ npm run example:wars # Recent wars with aggressor/defender details
754
+ npm run example:sovereignty # Nullsec sovereignty map + active campaigns
755
+ npm run example:industry # Industry facilities, cost indices, insurance
756
+ npm run example:incursions # Active incursions + faction warfare stats
757
+ npm run example:dogma # Item type details + dogma attributes
758
+ npm run example:contracts # Public region contracts + auction bids/items
759
+ npm run example:rate-limiting # Rate limiter & pagination demonstration
760
+ npm run example:cursor-pagination # Freelance Jobs with cursor pagination
761
+ npm run example:streaming # Streaming pagination for large datasets
762
+ npm run example:token-refresh # Automatic token refresh on 401
763
+ npm run example:universe-encyclopedia # Ancestries, bloodlines, races, celestials
764
+ npm run example:dogma-meta-sov # Dogma effects, sovereignty, meta endpoint
765
+ npm run example:faction-details # Faction warfare leaderboards and stats
766
+ ```
767
+
768
+ ### Authenticated Endpoints (require ESI_ACCESS_TOKEN)
769
+
770
+ ```bash
771
+ npm run example # Full character profile assembly
772
+ npm run example:wallet # Wallet balance, journal, transactions
773
+ npm run example:skills # Trained skills, queue, attributes
774
+ npm run example:assets # Asset inventory with bulk name lookup
775
+ npm run example:killmails # Recent killmails + full details
776
+ npm run example:fleet # Fleet info, members, wing/squad structure
777
+ npm run example:mail # Inbox headers, labels, mailing lists
778
+ npm run example:location # Current system, online status, ship
779
+ npm run example:fittings # Saved fittings + clone state + implants
780
+ npm run example:contacts # Contact list with standings + labels
781
+ npm run example:character-details # Blueprints, roles, standings, medals
782
+ npm run example:corporation-details # Corp members, divisions, structures
783
+ npm run example:calendar-search # Calendar events + character search
784
+ npm run example:loyalty-pi # Loyalty points + planetary interaction
785
+ npm run example:industry-mining # Industry jobs + mining ledger
786
+ npm run example:market-orders # Character/corp market orders
787
+ npm run example:corp-contracts-wallet # Corp contracts, contacts, wallets
788
+ ```
789
+
790
+ ### Write Operations (require specific scopes + caution)
791
+
792
+ ```bash
793
+ npm run example:write-ops # Contacts, fittings, mail, UI lifecycle tests
794
+ npm run example:universe-posts # Name resolution + character affiliation (public)
795
+ npm run example:freelance-jobs # Freelance job queries
796
+ ```
797
+
798
+ ### Parallel Requests
799
+
800
+ ```typescript
801
+ const [character, portrait, corp] = await Promise.all([
802
+ client.characters.getCharacterPublicInfo(characterId),
803
+ client.characters.getCharacterPortrait(characterId),
804
+ client.corporations.getCorporationInfo(corporationId),
805
+ ]);
806
+
807
+ console.log(`${character.name} [${corp.ticker}]`);
808
+ ```
809
+
810
+ ### Market Analysis
811
+
812
+ ```typescript
813
+ const [orders, history] = await Promise.all([
814
+ client.market.getMarketOrders(regionId),
815
+ client.market.getMarketHistory(regionId, typeId),
816
+ ]);
817
+
818
+ const buyOrders = orders.filter((o) => o.is_buy_order);
819
+ const sellOrders = orders.filter((o) => !o.is_buy_order);
820
+
821
+ console.log(`Best buy: ${Math.max(...buyOrders.map((o) => o.price))}`);
822
+ console.log(`Best sell: ${Math.min(...sellOrders.map((o) => o.price))}`);
823
+ ```
824
+
825
+ ## Resource Management
826
+
827
+ Always call `shutdown()` when you're done to clean up cache timers:
828
+
829
+ ```typescript
830
+ const client = new EsiClient();
831
+ try {
832
+ const status = await client.status.getStatus();
833
+ console.log(status.server_version);
834
+ } finally {
835
+ await client.shutdown();
836
+ }
837
+ ```
838
+
839
+ ## Testing
840
+
841
+ ESI.ts has a comprehensive multi-tier testing strategy with 139 suites and 4,104 tests:
842
+
843
+ | Tier | Tests | Purpose |
844
+ | -------------------------- | ---------------- | ------------------------------------------------------------------ |
845
+ | **TDD unit tests** | 81 files | Every client method, endpoint path, query param, and body format |
846
+ | **BDD scenario tests** | 40 feature files | Behavioral specifications in Gherkin (Given/When/Then) |
847
+ | **Mocked integration** | Full suite | Cross-layer request flow with jest-fetch-mock |
848
+ | **Live smoke tests** | 43 examples | Every endpoint against live Tranquility |
849
+ | **ESI spec contract** | 15 tests | Endpoint definitions validated against live OpenAPI spec |
850
+ | **Deep contract tests** | 8 categories | Path params, query params, body, auth, schemas, pagination vs spec |
851
+ | **Property-based fuzzing** | 601 tests | fast-check fuzzing of validation, URL construction, Zod schemas |
852
+ | **Mutation testing** | Stryker | Validates test suite kills code mutants |
853
+ | **Type-level tests** | tsd | Consumer API type correctness via tsd |
854
+ | **Gated auth tests** | 33 tests | Authenticated endpoints with real tokens |
855
+ | **Construction parity** | Per-surface | Verifies all client surfaces get identical middleware defaults |
856
+ | **Spec-alignment** | Type assertions | Ensures hand-written types align with generated OpenAPI types |
857
+
858
+ ```bash
859
+ npm test # Unit + BDD tests (139 suites, 4,104 tests)
860
+ npm run coverage # Tests with coverage report (thresholds enforced)
861
+ npm run bdd # BDD scenario tests only
862
+ npm run contract # Contract tests (skipped without ESI_LIVE_TESTS=true)
863
+ npm run fuzz # Property-based fuzz tests (601 tests)
864
+ npm run mutation # Mutation testing (Stryker)
865
+ npm run benchmark # Performance benchmark tests
866
+ npm run test:types # tsd consumer type tests
867
+ ```
868
+
869
+ 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%.
870
+
871
+ See [guides/TESTING.md](guides/TESTING.md) for the full testing guide, and [guides/ARCHITECTURE.md](guides/ARCHITECTURE.md) for architecture diagrams.
872
+
873
+ ## Development
874
+
875
+ ### Prerequisites
876
+
877
+ - Node.js 18+
878
+ - npm
879
+
880
+ ### Code Quality Tools
881
+
882
+ The project uses a comprehensive suite of static analysis and code quality tools:
883
+
884
+ | Tool | Purpose | Command |
885
+ | ------------------------------------------------------------------------------------ | ------------------------------------------------------- | ------------------------------ |
886
+ | [ESLint](https://eslint.org/) | Linting with TypeScript, security, and code smell rules | `npm run lint` |
887
+ | [Prettier](https://prettier.io/) | Code formatting | `npm run format:check` |
888
+ | [knip](https://knip.dev/) | Dead code and unused export detection | `npm run knip` |
889
+ | [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security) | Security anti-pattern detection | Integrated into `npm run lint` |
890
+ | [eslint-plugin-sonarjs](https://github.com/SonarSource/eslint-plugin-sonarjs) | Cognitive complexity and code smell detection | Integrated into `npm run lint` |
891
+ | [husky](https://typicode.github.io/husky/) | Git pre-commit hooks | Automatic on commit |
892
+ | [lint-staged](https://github.com/lint-staged/lint-staged) | Run linters on staged files only | Automatic on commit |
893
+ | [Redocly CLI](https://redocly.com/docs/cli/) | OpenAPI spec validation and linting | `npm run validate:spec` |
894
+
895
+ ### Available Scripts
896
+
897
+ ```bash
898
+ # Development
899
+ npm run build # Compile TypeScript
900
+ npm run lint # Run ESLint
901
+ npm run lint:fix # Run ESLint with auto-fix
902
+ npm run format # Format code with Prettier
903
+ npm run format:check # Check formatting without modifying
904
+
905
+ # Testing
906
+ npm test # Unit tests (139 suites, 4,104 tests)
907
+ npm run test:all # Unit + BDD + integration + fuzz + type tests
908
+ npm run coverage # Tests with coverage report (thresholds enforced)
909
+ npm run bdd # BDD scenario tests
910
+ npm run contract:live # Deep contract tests against live ESI spec
911
+ npm run fuzz # Property-based fuzz tests (fast-check)
912
+ npm run mutation # Mutation testing (Stryker)
913
+ npm run benchmark # Performance benchmark tests
914
+ npm run test:types # Consumer type tests (tsd)
915
+ npm run mock:esi # Start Prism mock ESI server on port 4010
916
+
917
+ # Static Analysis
918
+ npm run knip # Detect dead code and unused exports
919
+ npm run validate:esi # Validate endpoints against live ESI OpenAPI spec
920
+ npm run validate:spec # Lint ESI OpenAPI spec with Redocly (structural + best practices)
921
+ npm run validate:auth-scopes # Auth/scope cross-validation
922
+ npm run schema:drift # Schema drift detection (hand-written vs OpenAPI spec)
923
+ npm run validate # Run all checks: lint, format, build, coverage, knip
924
+ npm run generate:types # Regenerate TypeScript interfaces from ESI OpenAPI spec
925
+ npm run generate:endpoints # Regenerate endpoint definitions from ESI OpenAPI spec
926
+ npm run generate:all # Run all generators (types + endpoints + OKF)
927
+ npm run generate:okf # Generate OKF knowledge bundle from ESI OpenAPI spec
928
+
929
+ # Documentation
930
+ npm run docs # Generate TypeDoc API documentation
931
+ npm run docs:serve # Serve docs locally on port 8080
932
+ ```
933
+
934
+ ### ESI Endpoint Validation
935
+
936
+ To verify that the codebase endpoint definitions match the live ESI OpenAPI spec:
937
+
938
+ ```bash
939
+ npm run validate:esi
940
+ ```
941
+
942
+ This fetches the ESI OpenAPI spec and reports:
943
+
944
+ - Endpoints in the codebase that are no longer in the ESI spec
945
+ - Endpoints in the ESI spec that the codebase doesn't cover
946
+ - HTTP method mismatches between codebase and spec
947
+
948
+ ### Pre-commit Hooks
949
+
950
+ 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`.
951
+
952
+ ### CI/CD
953
+
954
+ Every pull request runs the full validation suite:
955
+
956
+ - ESLint (with security and sonarjs plugins)
957
+ - Prettier formatting check
958
+ - TypeScript compilation
959
+ - Generated types staleness check (regenerates from live ESI OpenAPI spec and verifies no diff)
960
+ - Unit tests across Node.js 18, 20, and 22
961
+ - BDD scenario tests
962
+ - Coverage threshold enforcement (branches: 80%, functions: 75%, lines: 90%, statements: 90%)
963
+ - Auth/scopes cross-validation
964
+ - Spec-alignment type assertions
965
+ - Schema drift detection
966
+ - Mutation testing (Stryker)
967
+ - Dead code detection via knip
968
+ - npm security audit
969
+
970
+ See [.github/workflows/README.md](.github/workflows/README.md) for full workflow details.
971
+
972
+ ## Contributing
973
+
974
+ 1. Fork the repository
975
+ 2. Create a feature branch
976
+ 3. Write tests for your changes
977
+ 4. Run `npm run validate` to check everything passes
978
+ 5. Open a Pull Request
979
+
980
+ ## License
981
+
982
+ GPL-3.0-or-later - see the [LICENSE](LICENSE) file for details.
983
+
984
+ ---
985
+
986
+ **o7**