@localisprimary/esi 2.0.17 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,11 +29,26 @@ console.log(alliance.data)
29
29
  ## Options
30
30
 
31
31
  The `EsiClient` constructor requires an options object with the following properties:
32
- | Parameter | Description | Type | Default | Required |
33
- |-----------|-------------|------|---------|----------|
34
- | `userAgent` | Resolves to `"localisprimary/esi <userAgent>"` | `string` | | Yes |
35
- | `token` | Optional auth token | `string` | `undefined` | No |
36
- | `useRequestHeaders` | If false, use query parameters for userAgent and token | `boolean` | `true` | No |
32
+ | Parameter | Description | Type | Default | Required |
33
+ | ------------------- | ------------------------------------------------------ | --------- | ----------- | -------- |
34
+ | `userAgent` | Resolves to `"localisprimary/esi <userAgent>"` | `string` | | Yes |
35
+ | `token` | Optional auth token | `string` | `undefined` | No |
36
+ | `useRequestHeaders` | If false, use query parameters for userAgent and token | `boolean` | `true` | No |
37
+ | `cache` | Cache eligible GET responses using ESI `Cache-Control` | `boolean` | `true` | No |
38
+
39
+ ## Caching
40
+
41
+ The client caches successful `GET` responses when ESI returns a cacheable
42
+ `Cache-Control` policy. Cache entries are shared by all `EsiClient` instances
43
+ in the current JavaScript runtime and use an LRU limit of 1,000 entries. This
44
+ works in browser tabs, Node.js processes, and warm Next.js server-function
45
+ instances, but does not persist across reloads, cold starts, or server
46
+ instances.
47
+
48
+ Fresh entries are returned without a network request. Stale entries are
49
+ revalidated with `ETag` and `If-None-Match` when request headers are enabled;
50
+ a `304 Not Modified` response reuses the cached body. Set `cache: false` to
51
+ always make a network request.
37
52
 
38
53
  ## Methods
39
54
 
@@ -83,7 +98,7 @@ esi.postCharacterMail({
83
98
  | [`getAllianceIcons`](https://developers.eveonline.com/api-explorer#/operations/GetAlliancesAllianceIdIcons) | Get the icon urls for a alliance. This route expires daily at 11:05 |
84
99
  | [`getAlliances`](https://developers.eveonline.com/api-explorer#/operations/GetAlliances) | List all active player alliances |
85
100
  | [`getCharacter`](https://developers.eveonline.com/api-explorer#/operations/GetCharactersCharacterId) | Public information about a character |
86
- | [`getCharacterAgentsResearch`](https://developers.eveonline.com/api-explorer#/operations/GetCharactersCharacterIdAgentsResearch) | Return a list of agents research information for a character. The formula for finding the current research points with an agent is: currentPoints = remainderPoints + pointsPerDay \* days(currentTime - researchStartDate) |
101
+ | [`getCharacterAgentsResearch`](https://developers.eveonline.com/api-explorer#/operations/GetCharactersCharacterIdAgentsResearch) | Return a list of agents research information for a character. The formula for finding the current research points with an agent is: currentPoints = remainderPoints + pointsPerDay * days(currentTime - researchStartDate) |
87
102
  | [`getCharacterAssets`](https://developers.eveonline.com/api-explorer#/operations/GetCharactersCharacterIdAssets) | Return a list of the characters assets |
88
103
  | [`postCharacterAssetsLocations`](https://developers.eveonline.com/api-explorer#/operations/PostCharactersCharacterIdAssetsLocations) | Return locations for a set of item ids, which you can get from character assets endpoint. Coordinates for items in hangars or stations are set to (0,0,0) |
89
104
  | [`postCharacterAssetsNames`](https://developers.eveonline.com/api-explorer#/operations/PostCharactersCharacterIdAssetsNames) | Return names for a set of item ids, which you can get from character assets endpoint. Typically used for items that can customize names, like containers or ships. |
@@ -0,0 +1,22 @@
1
+ import type { EsiResponse } from './types';
2
+ type CacheHeaders = Record<string, string>;
3
+ interface CacheEntry {
4
+ response: EsiResponse<unknown, CacheHeaders>;
5
+ etag?: string;
6
+ expiresAt: number;
7
+ revalidateEveryTime: boolean;
8
+ }
9
+ export declare function createCacheEntry(response: EsiResponse<unknown, CacheHeaders>, now?: number): CacheEntry | undefined;
10
+ export declare function isFresh(entry: CacheEntry, now?: number): boolean;
11
+ export declare function refreshCacheEntry(entry: CacheEntry, headers: CacheHeaders, now?: number): CacheEntry | undefined;
12
+ export declare function createCacheKey(url: string, compatibilityDate: string, token?: string): Promise<string>;
13
+ declare class EsiMemoryCache {
14
+ private readonly entries;
15
+ private readonly inFlight;
16
+ get(key: string): CacheEntry | undefined;
17
+ set(key: string, entry: CacheEntry): void;
18
+ delete(key: string): void;
19
+ getOrCreate(key: string, create: () => Promise<EsiResponse<unknown, CacheHeaders>>): Promise<EsiResponse<unknown, CacheHeaders>>;
20
+ }
21
+ export declare const esiMemoryCache: EsiMemoryCache;
22
+ export {};
package/dist/cache.js ADDED
@@ -0,0 +1,89 @@
1
+ function getDirective(cacheControl, name) {
2
+ for (const directive of cacheControl.split(',')) {
3
+ const [key, value] = directive.trim().split('=', 2);
4
+ if (key.toLowerCase() === name) {
5
+ return value?.replace(/^"|"$/g, '') ?? '';
6
+ }
7
+ }
8
+ }
9
+ function getMaxAge(cacheControl) {
10
+ const value = getDirective(cacheControl, 's-maxage') ??
11
+ getDirective(cacheControl, 'max-age');
12
+ if (!value || !/^\d+$/.test(value))
13
+ return undefined;
14
+ return Number(value);
15
+ }
16
+ function getResponseExpiry(headers, now) {
17
+ const cacheControl = headers['cache-control'];
18
+ if (!cacheControl || getDirective(cacheControl, 'no-store') !== undefined) {
19
+ return undefined;
20
+ }
21
+ const maxAge = getMaxAge(cacheControl);
22
+ if (maxAge === undefined)
23
+ return undefined;
24
+ const age = Number(headers.age ?? 0);
25
+ const currentAge = Number.isFinite(age) && age > 0 ? age : 0;
26
+ return now + Math.max(0, maxAge - currentAge) * 1000;
27
+ }
28
+ export function createCacheEntry(response, now = Date.now()) {
29
+ const expiresAt = getResponseExpiry(response.headers, now);
30
+ if (expiresAt === undefined)
31
+ return undefined;
32
+ return {
33
+ response,
34
+ etag: response.headers.etag,
35
+ expiresAt,
36
+ revalidateEveryTime: getDirective(response.headers['cache-control'], 'no-cache') !== undefined,
37
+ };
38
+ }
39
+ export function isFresh(entry, now = Date.now()) {
40
+ return !entry.revalidateEveryTime && entry.expiresAt > now;
41
+ }
42
+ export function refreshCacheEntry(entry, headers, now = Date.now()) {
43
+ return createCacheEntry({
44
+ ...entry.response,
45
+ headers: { ...entry.response.headers, ...headers },
46
+ }, now);
47
+ }
48
+ export async function createCacheKey(url, compatibilityDate, token) {
49
+ const input = `${url}\n${compatibilityDate}\n${token ?? ''}`;
50
+ const bytes = new TextEncoder().encode(input);
51
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
52
+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
53
+ }
54
+ class EsiMemoryCache {
55
+ constructor() {
56
+ this.entries = new Map();
57
+ this.inFlight = new Map();
58
+ }
59
+ get(key) {
60
+ const entry = this.entries.get(key);
61
+ if (!entry)
62
+ return undefined;
63
+ this.entries.delete(key);
64
+ this.entries.set(key, entry);
65
+ return entry;
66
+ }
67
+ set(key, entry) {
68
+ this.entries.delete(key);
69
+ this.entries.set(key, entry);
70
+ if (this.entries.size > 1000) {
71
+ const oldestKey = this.entries.keys().next().value;
72
+ if (oldestKey)
73
+ this.entries.delete(oldestKey);
74
+ }
75
+ }
76
+ delete(key) {
77
+ this.entries.delete(key);
78
+ }
79
+ getOrCreate(key, create) {
80
+ const inFlight = this.inFlight.get(key);
81
+ if (inFlight)
82
+ return inFlight;
83
+ const request = create().finally(() => this.inFlight.delete(key));
84
+ this.inFlight.set(key, request);
85
+ return request;
86
+ }
87
+ }
88
+ // Shared per JavaScript runtime: browser tab, Node process, or warm serverless instance.
89
+ export const esiMemoryCache = new EsiMemoryCache();
package/dist/client.d.ts CHANGED
@@ -4,10 +4,12 @@ export declare class EsiClient {
4
4
  private readonly userAgent;
5
5
  private readonly token?;
6
6
  private readonly useRequestHeaders;
7
+ private readonly cacheEnabled;
7
8
  constructor(options: {
8
9
  userAgent: string;
9
10
  token?: string;
10
11
  useRequestHeaders?: boolean;
12
+ cache?: boolean;
11
13
  });
12
14
  private request;
13
15
  /**
package/dist/client.js CHANGED
@@ -1,10 +1,12 @@
1
- const COMPATIBILITY_DATE = '2026-08-11';
1
+ import { createCacheEntry, createCacheKey, esiMemoryCache, isFresh, refreshCacheEntry, } from './cache';
2
+ const COMPATIBILITY_DATE = '2026-08-19';
2
3
  export class EsiClient {
3
4
  constructor(options) {
4
5
  this.baseUrl = 'https://esi.evetech.net';
5
6
  this.userAgent = 'localisprimary/esi';
6
7
  this.token = options.token;
7
8
  this.useRequestHeaders = options.useRequestHeaders ?? true;
9
+ this.cacheEnabled = options.cache ?? true;
8
10
  if (options.userAgent?.length) {
9
11
  this.userAgent += ` ${options.userAgent}`;
10
12
  }
@@ -36,31 +38,84 @@ export class EsiClient {
36
38
  if (this.token) {
37
39
  headers['Authorization'] = `Bearer ${this.token}`;
38
40
  }
39
- const response = await fetch(url.toString(), {
40
- method,
41
- headers: this.useRequestHeaders ? headers : undefined,
42
- body: body === undefined ? undefined : JSON.stringify(body),
43
- });
44
- const responseText = await response.text();
45
- if (!response.ok) {
46
- let error = 'Request failed';
47
- if (responseText) {
48
- try {
49
- const errorData = JSON.parse(responseText);
50
- error = errorData.error || error;
41
+ const getResponse = async (etag) => {
42
+ const requestHeaders = etag
43
+ ? { ...headers, 'If-None-Match': etag }
44
+ : headers;
45
+ const response = await fetch(url.toString(), {
46
+ method,
47
+ headers: this.useRequestHeaders ? requestHeaders : undefined,
48
+ body: body === undefined ? undefined : JSON.stringify(body),
49
+ });
50
+ const responseText = await response.text();
51
+ const responseHeaders = Object.fromEntries(response.headers.entries());
52
+ if (response.status === 304) {
53
+ return { response, responseText, headers: responseHeaders };
54
+ }
55
+ if (!response.ok) {
56
+ let error = 'Request failed';
57
+ if (responseText) {
58
+ try {
59
+ const errorData = JSON.parse(responseText);
60
+ error = errorData.error || error;
61
+ }
62
+ catch { }
51
63
  }
52
- catch { }
64
+ throw {
65
+ error,
66
+ status: response.status,
67
+ };
68
+ }
69
+ return { response, responseText, headers: responseHeaders };
70
+ };
71
+ if (method === 'GET' && this.cacheEnabled) {
72
+ const key = await createCacheKey(url.toString(), COMPATIBILITY_DATE, this.token);
73
+ const cached = esiMemoryCache.get(key);
74
+ if (cached && isFresh(cached)) {
75
+ return cached.response;
53
76
  }
54
- throw {
55
- error,
56
- status: response.status,
57
- };
77
+ const result = await esiMemoryCache.getOrCreate(key, async () => {
78
+ const existing = esiMemoryCache.get(key);
79
+ if (existing && isFresh(existing))
80
+ return existing.response;
81
+ const fetched = await getResponse(existing?.etag);
82
+ if (fetched.response.status === 304 && existing) {
83
+ const refreshed = refreshCacheEntry(existing, fetched.headers);
84
+ if (refreshed) {
85
+ esiMemoryCache.set(key, refreshed);
86
+ return refreshed.response;
87
+ }
88
+ esiMemoryCache.delete(key);
89
+ return existing.response;
90
+ }
91
+ if (fetched.response.status === 304) {
92
+ throw {
93
+ error: 'Received 304 Not Modified without a cached response',
94
+ status: 304,
95
+ };
96
+ }
97
+ const response = {
98
+ data: fetched.responseText
99
+ ? JSON.parse(fetched.responseText)
100
+ : undefined,
101
+ status: fetched.response.status,
102
+ headers: fetched.headers,
103
+ };
104
+ const entry = createCacheEntry(response);
105
+ if (entry)
106
+ esiMemoryCache.set(key, entry);
107
+ return response;
108
+ });
109
+ return result;
58
110
  }
59
- const data = responseText ? JSON.parse(responseText) : undefined;
111
+ const fetched = await getResponse();
112
+ const data = fetched.responseText
113
+ ? JSON.parse(fetched.responseText)
114
+ : undefined;
60
115
  return {
61
116
  data: data,
62
- status: response.status,
63
- headers: Object.fromEntries(response.headers.entries()),
117
+ status: fetched.response.status,
118
+ headers: fetched.headers,
64
119
  };
65
120
  }
66
121
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@localisprimary/esi",
3
- "version": "2.0.17",
3
+ "version": "2.1.0",
4
4
  "type": "module",
5
5
  "description": "Auto-generated TypeScript client for the EVE Online API",
6
6
  "main": "dist/index.js",
@@ -33,15 +33,15 @@
33
33
  },
34
34
  "license": "ISC",
35
35
  "devDependencies": {
36
- "@types/node": "^24.10.9",
37
- "@vitest/ui": "^4.0.18",
38
- "beachball": "^2.63.0",
36
+ "@types/node": "^24.13.3",
37
+ "@vitest/ui": "^4.1.11",
38
+ "beachball": "^2.65.5",
39
39
  "camelcase": "^9.0.0",
40
- "oxfmt": "^0.34.0",
41
- "oxlint": "^1.49.0",
40
+ "oxfmt": "^0.64.0",
41
+ "oxlint": "^1.79.0",
42
42
  "rimraf": "^6.1.3",
43
- "typescript": "^5.9.3",
44
- "vitest": "^4.0.18"
43
+ "typescript": "^7.0.2",
44
+ "vitest": "^4.1.11"
45
45
  },
46
46
  "files": [
47
47
  "dist/**/*"
@@ -53,5 +53,5 @@
53
53
  "engines": {
54
54
  "node": "^24.13.0"
55
55
  },
56
- "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264"
56
+ "packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e"
57
57
  }