@localisprimary/esi 2.0.17 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,11 +29,27 @@ 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
+
33
+ | Parameter | Description | Type | Default | Required |
34
+ | ------------------- | ------------------------------------------------------ | --------- | ----------- | -------- |
35
+ | `userAgent` | Resolves to `"localisprimary/esi <userAgent>"` | `string` | | Yes |
36
+ | `token` | Optional auth token | `string` | `undefined` | No |
37
+ | `useRequestHeaders` | If false, use query parameters for userAgent and token | `boolean` | `true` | No |
38
+ | `cache` | Cache eligible GET responses using ESI `Cache-Control` | `boolean` | `true` | No |
39
+
40
+ ## Caching
41
+
42
+ The client caches successful `GET` responses when ESI returns a cacheable
43
+ `Cache-Control` policy. Cache entries are shared by all `EsiClient` instances
44
+ in the current JavaScript runtime and use an LRU limit of 1,000 entries. This
45
+ works in browser tabs, Node.js processes, and warm Next.js server-function
46
+ instances, but does not persist across reloads, cold starts, or server
47
+ instances.
48
+
49
+ Fresh entries are returned without a network request. Stale entries are
50
+ revalidated with `ETag` and `If-None-Match` when request headers are enabled;
51
+ a `304 Not Modified` response reuses the cached body. Set `cache: false` to
52
+ always make a network request.
37
53
 
38
54
  ## Methods
39
55
 
@@ -68,7 +84,7 @@ esi.postCharacterMail({
68
84
  character_id: 91884358,
69
85
 
70
86
  // request body
71
- approved_cost: 0,
87
+ subject: 'Test mail',
72
88
  body: 'Hello from the ESI!',
73
89
  recipients: [{ recipient_type: 'character', recipient_id: 96135698 }],
74
90
  })
@@ -83,7 +99,7 @@ esi.postCharacterMail({
83
99
  | [`getAllianceIcons`](https://developers.eveonline.com/api-explorer#/operations/GetAlliancesAllianceIdIcons) | Get the icon urls for a alliance. This route expires daily at 11:05 |
84
100
  | [`getAlliances`](https://developers.eveonline.com/api-explorer#/operations/GetAlliances) | List all active player alliances |
85
101
  | [`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) |
102
+ | [`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
103
  | [`getCharacterAssets`](https://developers.eveonline.com/api-explorer#/operations/GetCharactersCharacterIdAssets) | Return a list of the characters assets |
88
104
  | [`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
105
  | [`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.js';
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
@@ -1,13 +1,15 @@
1
- import * as Types from './types';
1
+ import type * as Types from './types.js';
2
2
  export declare class EsiClient {
3
3
  private readonly baseUrl;
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.js';
2
+ const COMPATIBILITY_DATE = '2026-08-23';
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
  }
@@ -17,7 +19,8 @@ export class EsiClient {
17
19
  if (params) {
18
20
  Object.entries(params).forEach(([key, value]) => {
19
21
  if (value !== undefined) {
20
- url.searchParams.append(key, String(value));
22
+ const values = Array.isArray(value) ? value : [value];
23
+ values.forEach(item => url.searchParams.append(key, String(item)));
21
24
  }
22
25
  });
23
26
  }
@@ -36,31 +39,84 @@ export class EsiClient {
36
39
  if (this.token) {
37
40
  headers['Authorization'] = `Bearer ${this.token}`;
38
41
  }
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;
42
+ const getResponse = async (etag) => {
43
+ const requestHeaders = etag
44
+ ? { ...headers, 'If-None-Match': etag }
45
+ : headers;
46
+ const response = await fetch(url.toString(), {
47
+ method,
48
+ headers: this.useRequestHeaders ? requestHeaders : undefined,
49
+ body: body === undefined ? undefined : JSON.stringify(body),
50
+ });
51
+ const responseText = await response.text();
52
+ const responseHeaders = Object.fromEntries(response.headers.entries());
53
+ if (response.status === 304) {
54
+ return { response, responseText, headers: responseHeaders };
55
+ }
56
+ if (!response.ok) {
57
+ let error = 'Request failed';
58
+ if (responseText) {
59
+ try {
60
+ const errorData = JSON.parse(responseText);
61
+ error = errorData.error || error;
62
+ }
63
+ catch { }
51
64
  }
52
- catch { }
65
+ throw {
66
+ error,
67
+ status: response.status,
68
+ };
69
+ }
70
+ return { response, responseText, headers: responseHeaders };
71
+ };
72
+ if (method === 'GET' && this.cacheEnabled) {
73
+ const key = await createCacheKey(url.toString(), COMPATIBILITY_DATE, this.token);
74
+ const cached = esiMemoryCache.get(key);
75
+ if (cached && isFresh(cached)) {
76
+ return cached.response;
53
77
  }
54
- throw {
55
- error,
56
- status: response.status,
57
- };
78
+ const result = await esiMemoryCache.getOrCreate(key, async () => {
79
+ const existing = esiMemoryCache.get(key);
80
+ if (existing && isFresh(existing))
81
+ return existing.response;
82
+ const fetched = await getResponse(existing?.etag);
83
+ if (fetched.response.status === 304 && existing) {
84
+ const refreshed = refreshCacheEntry(existing, fetched.headers);
85
+ if (refreshed) {
86
+ esiMemoryCache.set(key, refreshed);
87
+ return refreshed.response;
88
+ }
89
+ esiMemoryCache.delete(key);
90
+ return existing.response;
91
+ }
92
+ if (fetched.response.status === 304) {
93
+ throw {
94
+ error: 'Received 304 Not Modified without a cached response',
95
+ status: 304,
96
+ };
97
+ }
98
+ const response = {
99
+ data: fetched.responseText
100
+ ? JSON.parse(fetched.responseText)
101
+ : undefined,
102
+ status: fetched.response.status,
103
+ headers: fetched.headers,
104
+ };
105
+ const entry = createCacheEntry(response);
106
+ if (entry)
107
+ esiMemoryCache.set(key, entry);
108
+ return response;
109
+ });
110
+ return result;
58
111
  }
59
- const data = responseText ? JSON.parse(responseText) : undefined;
112
+ const fetched = await getResponse();
113
+ const data = fetched.responseText
114
+ ? JSON.parse(fetched.responseText)
115
+ : undefined;
60
116
  return {
61
117
  data: data,
62
- status: response.status,
63
- headers: Object.fromEntries(response.headers.entries()),
118
+ status: fetched.response.status,
119
+ headers: fetched.headers,
64
120
  };
65
121
  }
66
122
  /**
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { EsiClient } from './client';
2
- export * from './types';
1
+ export { EsiClient } from './client.js';
2
+ export * from './types.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { EsiClient } from './client';
2
- export * from './types';
1
+ export { EsiClient } from './client.js';
2
+ export * from './types.js';