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