@g33ks/foundryvtt-mcp 0.0.0-stage → 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/LICENSE +22 -0
- package/README.md +457 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +65 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +38 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +450 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +48 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/tool-dependencies.js +194 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview What each tool and resource needs from FoundryVTT.
|
|
3
|
+
*
|
|
4
|
+
* Decides which calls wait for a connection being restored (see
|
|
5
|
+
* {@link FoundryCore}): only those that read the Socket.IO cache or go
|
|
6
|
+
* through the socket wait for it — a cache nobody keeps live must not answer
|
|
7
|
+
* during an outage. The others never touch the socket and must not wait for it.
|
|
8
|
+
*
|
|
9
|
+
* - `socket`: the cached world or a Socket.IO request (every document write).
|
|
10
|
+
* - `socket+bridge`: the socket and the companion module (see {@link needsBridge}).
|
|
11
|
+
* - `bridge`: the companion module only.
|
|
12
|
+
* - `rest`: the REST API module (`FOUNDRY_API_KEY`) only.
|
|
13
|
+
* - `rest-or-local`: the REST API module when a key is set, a local computation otherwise.
|
|
14
|
+
* - `local`: no FoundryVTT at all (a computation, or files under `FOUNDRY_DATA_PATH`).
|
|
15
|
+
* - `health`: reports the connections themselves, so waits for none.
|
|
16
|
+
*
|
|
17
|
+
* A unit test checks that every tool and resource is classified.
|
|
18
|
+
*/
|
|
19
|
+
import { isRecord } from '../utils/guards.js';
|
|
20
|
+
const SOCKET_TOOLS = [
|
|
21
|
+
// Reads from the cached world (search_actors, get_actor_details,
|
|
22
|
+
// search_items, get_scene_info and get_world_summary ask the REST API
|
|
23
|
+
// module first when a key is set, then fall back to the cache).
|
|
24
|
+
'search_actors',
|
|
25
|
+
'get_actor_details',
|
|
26
|
+
'get_actor_inventory',
|
|
27
|
+
'search_items',
|
|
28
|
+
'get_scene_info',
|
|
29
|
+
'list_tiles',
|
|
30
|
+
'list_walls',
|
|
31
|
+
'list_tokens',
|
|
32
|
+
'list_lights',
|
|
33
|
+
'list_sounds',
|
|
34
|
+
'list_notes',
|
|
35
|
+
'list_drawings',
|
|
36
|
+
'list_templates',
|
|
37
|
+
'list_regions',
|
|
38
|
+
'find_open_cells',
|
|
39
|
+
'list_actor_effects',
|
|
40
|
+
'get_combat_state',
|
|
41
|
+
'get_chat_messages',
|
|
42
|
+
'get_users',
|
|
43
|
+
'search_journals',
|
|
44
|
+
'search_world',
|
|
45
|
+
'get_world_summary',
|
|
46
|
+
'list_roll_tables',
|
|
47
|
+
'roll_table',
|
|
48
|
+
'list_folders',
|
|
49
|
+
'list_macros',
|
|
50
|
+
'list_playlists',
|
|
51
|
+
'get_world_setting',
|
|
52
|
+
// The event log is fed by socket broadcasts: during an outage it would
|
|
53
|
+
// answer "nothing new", which is not true.
|
|
54
|
+
'watch_events',
|
|
55
|
+
// The cache, plus compendium packs through the module when it is there.
|
|
56
|
+
'lookup_rule',
|
|
57
|
+
// Requests to the server over the socket.
|
|
58
|
+
'get_journal',
|
|
59
|
+
'refresh_world_data',
|
|
60
|
+
// Writes (Socket.IO modifyDocument).
|
|
61
|
+
'update_actor_attributes',
|
|
62
|
+
'create_world_actor',
|
|
63
|
+
'create_full_actor',
|
|
64
|
+
'delete_world_actor',
|
|
65
|
+
'update_actor_item',
|
|
66
|
+
'delete_actor_item',
|
|
67
|
+
'create_scene',
|
|
68
|
+
'switch_scene',
|
|
69
|
+
'delete_scene',
|
|
70
|
+
'set_scene_lighting',
|
|
71
|
+
'reset_fog',
|
|
72
|
+
'set_scene_weather',
|
|
73
|
+
'create_wall',
|
|
74
|
+
'delete_wall',
|
|
75
|
+
'set_door_state',
|
|
76
|
+
'create_tile',
|
|
77
|
+
'delete_tile',
|
|
78
|
+
'create_light',
|
|
79
|
+
'update_light',
|
|
80
|
+
'delete_light',
|
|
81
|
+
'create_sound',
|
|
82
|
+
'delete_sound',
|
|
83
|
+
'create_note',
|
|
84
|
+
'delete_note',
|
|
85
|
+
'create_drawing',
|
|
86
|
+
'delete_drawing',
|
|
87
|
+
'create_template',
|
|
88
|
+
'delete_template',
|
|
89
|
+
'create_region',
|
|
90
|
+
'delete_region',
|
|
91
|
+
'next_turn',
|
|
92
|
+
'end_combat',
|
|
93
|
+
'set_initiative',
|
|
94
|
+
'start_combat',
|
|
95
|
+
'move_token',
|
|
96
|
+
'apply_status_effect',
|
|
97
|
+
'spawn_token',
|
|
98
|
+
'delete_token',
|
|
99
|
+
'move_token_pathfind',
|
|
100
|
+
'move_tokens',
|
|
101
|
+
'update_token_vision',
|
|
102
|
+
'send_chat_message',
|
|
103
|
+
'create_journal_entry',
|
|
104
|
+
'update_journal_page',
|
|
105
|
+
'add_journal_page',
|
|
106
|
+
'update_journal_entry',
|
|
107
|
+
'delete_journal_entry',
|
|
108
|
+
'create_folder',
|
|
109
|
+
'create_macro',
|
|
110
|
+
'delete_macro',
|
|
111
|
+
'create_playlist',
|
|
112
|
+
'set_playlist_state',
|
|
113
|
+
'delete_playlist',
|
|
114
|
+
'set_document_ownership',
|
|
115
|
+
'create_actor_effect',
|
|
116
|
+
'update_actor_effect',
|
|
117
|
+
'delete_actor_effect',
|
|
118
|
+
'create_roll_table',
|
|
119
|
+
'delete_roll_table',
|
|
120
|
+
'set_world_setting',
|
|
121
|
+
'set_user_role',
|
|
122
|
+
];
|
|
123
|
+
const TOOL_DEPENDENCIES = new Map([
|
|
124
|
+
...SOCKET_TOOLS.map((name) => [name, 'socket']),
|
|
125
|
+
// Reads a compendium document through the module, then writes over the socket.
|
|
126
|
+
['import_compendium_actor', 'socket+bridge'],
|
|
127
|
+
// The module only for a compendium source; see needsBridge.
|
|
128
|
+
['create_actor_item', 'socket+bridge'],
|
|
129
|
+
['capture_scene', 'bridge'],
|
|
130
|
+
['get_document_schema', 'bridge'],
|
|
131
|
+
['search_compendium_content', 'bridge'],
|
|
132
|
+
['get_targets', 'bridge'],
|
|
133
|
+
['roll_and_post', 'bridge'],
|
|
134
|
+
['set_target', 'bridge'],
|
|
135
|
+
['ping_canvas', 'bridge'],
|
|
136
|
+
['set_pause', 'bridge'],
|
|
137
|
+
['upload_asset', 'bridge'],
|
|
138
|
+
['search_compendium', 'rest'],
|
|
139
|
+
['get_recent_logs', 'rest'],
|
|
140
|
+
['search_logs', 'rest'],
|
|
141
|
+
['get_system_health', 'rest'],
|
|
142
|
+
['diagnose_errors', 'rest'],
|
|
143
|
+
['roll_dice', 'rest-or-local'],
|
|
144
|
+
['generate_npc', 'local'],
|
|
145
|
+
['generate_loot', 'local'],
|
|
146
|
+
['list_scene_assets', 'local'],
|
|
147
|
+
['get_health_status', 'health'],
|
|
148
|
+
]);
|
|
149
|
+
/** Every `foundry://` resource reads the cache, except the REST diagnostics. */
|
|
150
|
+
const RESOURCE_DEPENDENCIES = new Map([
|
|
151
|
+
['foundry://actors', 'socket'],
|
|
152
|
+
['foundry://items', 'socket'],
|
|
153
|
+
['foundry://scenes', 'socket'],
|
|
154
|
+
['foundry://scenes/current', 'socket'],
|
|
155
|
+
['foundry://journals', 'socket'],
|
|
156
|
+
['foundry://users', 'socket'],
|
|
157
|
+
['foundry://combat', 'socket'],
|
|
158
|
+
['foundry://world/settings', 'socket'],
|
|
159
|
+
['foundry://system/diagnostics', 'rest'],
|
|
160
|
+
]);
|
|
161
|
+
/** The tool's dependency; `undefined` for a name nobody classified. */
|
|
162
|
+
export function toolDependency(name) {
|
|
163
|
+
return TOOL_DEPENDENCIES.get(name);
|
|
164
|
+
}
|
|
165
|
+
/** The resource's dependency; `undefined` for a URI nobody classified. */
|
|
166
|
+
export function resourceDependency(uri) {
|
|
167
|
+
return RESOURCE_DEPENDENCIES.get(uri);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* True when the dependency involves the socket. An unclassified name counts
|
|
171
|
+
* as one: waiting is the safe default for something that may read the cache.
|
|
172
|
+
*/
|
|
173
|
+
export function waitsForSocket(dependency) {
|
|
174
|
+
return dependency === undefined || dependency === 'socket' || dependency === 'socket+bridge';
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* True when this call goes through the companion module: every `bridge`
|
|
178
|
+
* tool, `import_compendium_actor`, and `create_actor_item` from a
|
|
179
|
+
* compendium source (an inline item needs only the socket).
|
|
180
|
+
*/
|
|
181
|
+
export function needsBridge(name, args) {
|
|
182
|
+
const dependency = toolDependency(name);
|
|
183
|
+
if (dependency === 'bridge') {
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
if (dependency !== 'socket+bridge') {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
if (name === 'create_actor_item') {
|
|
190
|
+
return isRecord(args.source) && args.source.type === 'compendium';
|
|
191
|
+
}
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
//# sourceMappingURL=tool-dependencies.js.map
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Which tools change game state.
|
|
3
|
+
*
|
|
4
|
+
* Their calls are serialised through one queue (see {@link FoundryCore}):
|
|
5
|
+
* clients (and, in shared mode, several clients) may fire tool calls in
|
|
6
|
+
* parallel, and a read-modify-write such as a journal page append must not
|
|
7
|
+
* interleave with another write. Reads keep running in parallel.
|
|
8
|
+
*
|
|
9
|
+
* Every `*MutationTools` definition group is covered by a unit test; tools
|
|
10
|
+
* that mutate from a mixed group are listed by hand below.
|
|
11
|
+
*/
|
|
12
|
+
export const WRITE_TOOLS = new Set([
|
|
13
|
+
// actorMutationTools
|
|
14
|
+
'update_actor_attributes',
|
|
15
|
+
'create_world_actor',
|
|
16
|
+
'create_full_actor',
|
|
17
|
+
'delete_world_actor',
|
|
18
|
+
// itemMutationTools
|
|
19
|
+
'create_actor_item',
|
|
20
|
+
'update_actor_item',
|
|
21
|
+
'delete_actor_item',
|
|
22
|
+
// sceneMutationTools
|
|
23
|
+
'create_scene',
|
|
24
|
+
'switch_scene',
|
|
25
|
+
'delete_scene',
|
|
26
|
+
'set_scene_lighting',
|
|
27
|
+
'reset_fog',
|
|
28
|
+
'set_scene_weather',
|
|
29
|
+
// wallMutationTools (list_walls is a read)
|
|
30
|
+
'create_wall',
|
|
31
|
+
'delete_wall',
|
|
32
|
+
'set_door_state',
|
|
33
|
+
// tileMutationTools
|
|
34
|
+
'create_tile',
|
|
35
|
+
'delete_tile',
|
|
36
|
+
// placeableMutationTools
|
|
37
|
+
'create_light',
|
|
38
|
+
'update_light',
|
|
39
|
+
'delete_light',
|
|
40
|
+
'create_sound',
|
|
41
|
+
'delete_sound',
|
|
42
|
+
'create_note',
|
|
43
|
+
'delete_note',
|
|
44
|
+
'create_drawing',
|
|
45
|
+
'delete_drawing',
|
|
46
|
+
'create_template',
|
|
47
|
+
'delete_template',
|
|
48
|
+
// combatMutationTools
|
|
49
|
+
'next_turn',
|
|
50
|
+
'end_combat',
|
|
51
|
+
'set_initiative',
|
|
52
|
+
'start_combat',
|
|
53
|
+
// tokenMutationTools
|
|
54
|
+
'move_token',
|
|
55
|
+
'apply_status_effect',
|
|
56
|
+
'spawn_token',
|
|
57
|
+
'delete_token',
|
|
58
|
+
'move_token_pathfind',
|
|
59
|
+
'move_tokens',
|
|
60
|
+
'update_token_vision',
|
|
61
|
+
// chatMutationTools
|
|
62
|
+
'send_chat_message',
|
|
63
|
+
// journalMutationTools
|
|
64
|
+
'create_journal_entry',
|
|
65
|
+
'update_journal_page',
|
|
66
|
+
'add_journal_page',
|
|
67
|
+
'update_journal_entry',
|
|
68
|
+
'delete_journal_entry',
|
|
69
|
+
// worldDocumentMutationTools
|
|
70
|
+
'create_folder',
|
|
71
|
+
'create_macro',
|
|
72
|
+
'delete_macro',
|
|
73
|
+
'create_playlist',
|
|
74
|
+
'set_playlist_state',
|
|
75
|
+
'delete_playlist',
|
|
76
|
+
'set_document_ownership',
|
|
77
|
+
// mixed groups
|
|
78
|
+
'create_actor_effect',
|
|
79
|
+
'update_actor_effect',
|
|
80
|
+
'delete_actor_effect',
|
|
81
|
+
'create_region',
|
|
82
|
+
'delete_region',
|
|
83
|
+
'create_roll_table',
|
|
84
|
+
'delete_roll_table',
|
|
85
|
+
'set_world_setting',
|
|
86
|
+
'set_user_role',
|
|
87
|
+
'roll_and_post',
|
|
88
|
+
'import_compendium_actor',
|
|
89
|
+
'set_target',
|
|
90
|
+
'ping_canvas',
|
|
91
|
+
'set_pause',
|
|
92
|
+
'upload_asset',
|
|
93
|
+
]);
|
|
94
|
+
export function isWriteTool(name) {
|
|
95
|
+
return WRITE_TOOLS.has(name);
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=write-tools.js.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Global cache instance singleton
|
|
3
|
+
*
|
|
4
|
+
* This module provides a singleton cache instance that's configured
|
|
5
|
+
* from the application configuration.
|
|
6
|
+
*/
|
|
7
|
+
import { config } from '../config/index.js';
|
|
8
|
+
import { CacheService } from './cache.js';
|
|
9
|
+
/**
|
|
10
|
+
* Global cache instance
|
|
11
|
+
* Initialized with configuration from config system
|
|
12
|
+
*/
|
|
13
|
+
export const cache = new CacheService(config?.cache || {
|
|
14
|
+
enabled: false,
|
|
15
|
+
ttlSeconds: 300,
|
|
16
|
+
maxSize: 1000,
|
|
17
|
+
});
|
|
18
|
+
/**
|
|
19
|
+
* Cache key generators for consistent naming
|
|
20
|
+
*/
|
|
21
|
+
export const CacheKeys = {
|
|
22
|
+
worldInfo: () => 'world:info',
|
|
23
|
+
actor: (id) => `actor:${id}`,
|
|
24
|
+
actorSearch: (query, type, limit) => `actor:search:${query}:${type || 'all'}:${limit || 10}`,
|
|
25
|
+
item: (id) => `item:${id}`,
|
|
26
|
+
itemSearch: (query, type, rarity, limit) => `item:search:${query}:${type || 'all'}:${rarity || 'all'}:${limit || 10}`,
|
|
27
|
+
scene: (id) => (id ? `scene:${id}` : 'scene:current'),
|
|
28
|
+
rule: (query, system) => `rule:${query}:${system || 'default'}`,
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=cache-instance.js.map
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Caching utility with TTL (Time To Live) support
|
|
3
|
+
*
|
|
4
|
+
* This module provides a simple in-memory cache with automatic expiration
|
|
5
|
+
* and configurable size limits to improve performance for quasi-static data.
|
|
6
|
+
*/
|
|
7
|
+
import { logger } from './logger.js';
|
|
8
|
+
/**
|
|
9
|
+
* Simple in-memory cache with TTL and LRU eviction
|
|
10
|
+
*/
|
|
11
|
+
export class CacheService {
|
|
12
|
+
config;
|
|
13
|
+
cache = new Map();
|
|
14
|
+
stats = {
|
|
15
|
+
hits: 0,
|
|
16
|
+
misses: 0,
|
|
17
|
+
evictions: 0,
|
|
18
|
+
};
|
|
19
|
+
cleanupInterval;
|
|
20
|
+
constructor(config) {
|
|
21
|
+
this.config = config;
|
|
22
|
+
if (config.enabled) {
|
|
23
|
+
logger.info('Cache service initialized', {
|
|
24
|
+
ttlSeconds: config.ttlSeconds,
|
|
25
|
+
maxSize: config.maxSize,
|
|
26
|
+
});
|
|
27
|
+
// Clean up expired entries periodically
|
|
28
|
+
this.cleanupInterval = setInterval(() => {
|
|
29
|
+
try {
|
|
30
|
+
this.cleanup();
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
logger.warn('Cache cleanup error', { error: err instanceof Error ? err.message : err });
|
|
34
|
+
}
|
|
35
|
+
}, Math.max((config.ttlSeconds * 1000) / 4, 30000));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Get a value from the cache
|
|
40
|
+
*/
|
|
41
|
+
get(key) {
|
|
42
|
+
if (!this.config.enabled) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const entry = this.cache.get(key);
|
|
46
|
+
if (!entry) {
|
|
47
|
+
this.stats.misses++;
|
|
48
|
+
logger.debug('Cache miss', { key });
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
// Check if entry has expired
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
if (now - entry.timestamp > entry.ttl * 1000) {
|
|
54
|
+
this.cache.delete(key);
|
|
55
|
+
this.stats.misses++;
|
|
56
|
+
logger.debug('Cache expired', { key, age: now - entry.timestamp });
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
// Update access metadata
|
|
60
|
+
entry.accessCount++;
|
|
61
|
+
entry.lastAccessed = now;
|
|
62
|
+
this.stats.hits++;
|
|
63
|
+
logger.debug('Cache hit', { key, accessCount: entry.accessCount });
|
|
64
|
+
return entry.value;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Set a value in the cache with custom TTL
|
|
68
|
+
*/
|
|
69
|
+
set(key, value, customTtlSeconds) {
|
|
70
|
+
if (!this.config.enabled) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const ttl = customTtlSeconds ?? this.config.ttlSeconds;
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
// Ensure cache doesn't exceed max size
|
|
76
|
+
if (this.cache.size >= this.config.maxSize && !this.cache.has(key)) {
|
|
77
|
+
this.evictLeastRecentlyUsed();
|
|
78
|
+
}
|
|
79
|
+
const entry = {
|
|
80
|
+
value,
|
|
81
|
+
timestamp: now,
|
|
82
|
+
ttl,
|
|
83
|
+
accessCount: 0,
|
|
84
|
+
lastAccessed: now,
|
|
85
|
+
};
|
|
86
|
+
this.cache.set(key, entry);
|
|
87
|
+
logger.debug('Cache set', { key, ttl, size: this.cache.size });
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Delete a specific key from the cache
|
|
91
|
+
*/
|
|
92
|
+
delete(key) {
|
|
93
|
+
const deleted = this.cache.delete(key);
|
|
94
|
+
if (deleted) {
|
|
95
|
+
logger.debug('Cache deleted', { key });
|
|
96
|
+
}
|
|
97
|
+
return deleted;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Clear all entries from the cache
|
|
101
|
+
*/
|
|
102
|
+
clear() {
|
|
103
|
+
const size = this.cache.size;
|
|
104
|
+
this.cache.clear();
|
|
105
|
+
this.stats.hits = 0;
|
|
106
|
+
this.stats.misses = 0;
|
|
107
|
+
this.stats.evictions = 0;
|
|
108
|
+
logger.info('Cache cleared', { previousSize: size });
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Get or set a value using a factory function
|
|
112
|
+
*/
|
|
113
|
+
async getOrSet(key, factory, customTtlSeconds) {
|
|
114
|
+
if (!this.config.enabled) {
|
|
115
|
+
return await factory();
|
|
116
|
+
}
|
|
117
|
+
const cached = this.get(key);
|
|
118
|
+
if (cached !== undefined) {
|
|
119
|
+
return cached;
|
|
120
|
+
}
|
|
121
|
+
const value = await factory();
|
|
122
|
+
this.set(key, value, customTtlSeconds);
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Get cache statistics
|
|
127
|
+
*/
|
|
128
|
+
getStats() {
|
|
129
|
+
const total = this.stats.hits + this.stats.misses;
|
|
130
|
+
const hitRate = total > 0 ? this.stats.hits / total : 0;
|
|
131
|
+
return {
|
|
132
|
+
hits: this.stats.hits,
|
|
133
|
+
misses: this.stats.misses,
|
|
134
|
+
hitRate: Math.round(hitRate * 100) / 100,
|
|
135
|
+
size: this.cache.size,
|
|
136
|
+
maxSize: this.config.maxSize,
|
|
137
|
+
evictions: this.stats.evictions,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Check if cache is enabled
|
|
142
|
+
*/
|
|
143
|
+
isEnabled() {
|
|
144
|
+
return this.config.enabled;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Destroy the cache service and release resources
|
|
148
|
+
*/
|
|
149
|
+
destroy() {
|
|
150
|
+
if (this.cleanupInterval) {
|
|
151
|
+
clearInterval(this.cleanupInterval);
|
|
152
|
+
this.cleanupInterval = undefined;
|
|
153
|
+
}
|
|
154
|
+
this.cache.clear();
|
|
155
|
+
logger.info('Cache service destroyed');
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Get cache keys (for debugging)
|
|
159
|
+
*/
|
|
160
|
+
getKeys() {
|
|
161
|
+
return Array.from(this.cache.keys());
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Cleanup expired entries
|
|
165
|
+
*/
|
|
166
|
+
cleanup() {
|
|
167
|
+
const now = Date.now();
|
|
168
|
+
let cleaned = 0;
|
|
169
|
+
for (const [key, entry] of this.cache.entries()) {
|
|
170
|
+
if (now - entry.timestamp > entry.ttl * 1000) {
|
|
171
|
+
this.cache.delete(key);
|
|
172
|
+
cleaned++;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (cleaned > 0) {
|
|
176
|
+
logger.debug('Cache cleanup completed', {
|
|
177
|
+
cleaned,
|
|
178
|
+
remaining: this.cache.size,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Evict least recently used entry
|
|
184
|
+
*/
|
|
185
|
+
evictLeastRecentlyUsed() {
|
|
186
|
+
let lruKey;
|
|
187
|
+
let lruTime = Date.now(); // Start with current time
|
|
188
|
+
// Find the entry with the oldest lastAccessed time
|
|
189
|
+
for (const [key, entry] of this.cache.entries()) {
|
|
190
|
+
if (entry.lastAccessed <= lruTime) {
|
|
191
|
+
lruTime = entry.lastAccessed;
|
|
192
|
+
lruKey = key;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (lruKey) {
|
|
196
|
+
this.cache.delete(lruKey);
|
|
197
|
+
this.stats.evictions++;
|
|
198
|
+
logger.debug('Cache evicted LRU entry', {
|
|
199
|
+
key: lruKey,
|
|
200
|
+
age: Date.now() - lruTime,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
//# sourceMappingURL=cache.js.map
|