/**
 * @license
 * Copyright 2025 ReverseCraft
 * SPDX-License-Identifier: Apache-2.0
 */
import*as t from"fs/promises";import*as i from"path";import*as r from"os";export class ScriptCacheManager{tempDir;scriptIdToEntry=new Map;filePathToScriptId=new Map;initialized=!1;constructor(t){this.tempDir=i.join(r.tmpdir(),`mcp-scripts-${t}-${Date.now()}`)}async ensureInitialized(){if(!this.initialized)try{await t.mkdir(this.tempDir,{recursive:!0}),this.initialized=!0}catch(t){throw console.error(`Failed to create temp directory: ${t}`),t}}async cacheScript(r,e,a){if(await this.ensureInitialized(),this.scriptIdToEntry.has(r))return this.scriptIdToEntry.get(r).filePath;try{const s=this.generateSafeFilename(r,e),c=i.join(this.tempDir,s);await t.writeFile(c,a,"utf-8");const n={scriptId:r,url:e,filePath:c};return this.scriptIdToEntry.set(r,n),this.filePathToScriptId.set(c,r),c}catch(t){return void console.error(`Failed to cache script ${r}: ${t}`)}}generateSafeFilename(t,r){let e=t;try{if(r&&""!==r){const t=new URL(r).pathname;e=(i.basename(t)||"script").replace(/[^a-zA-Z0-9._-]/g,"_")}}catch{}return`${t}_${e}.js`}getScriptIdFromFile(t){return this.filePathToScriptId.get(t)}getFileFromScriptId(t){return this.scriptIdToEntry.get(t)?.filePath}getScriptUrl(t){return this.scriptIdToEntry.get(t)?.url}getAllCachedScripts(){const t=new Map;for(const[i,r]of this.scriptIdToEntry)t.set(i,{filePath:r.filePath,url:r.url});return t}getCachedScriptCount(){return this.scriptIdToEntry.size}async cleanup(){try{for(const i of this.scriptIdToEntry.values())try{await t.unlink(i.filePath)}catch{}if(this.initialized)try{await t.rmdir(this.tempDir)}catch{}this.scriptIdToEntry.clear(),this.filePathToScriptId.clear(),this.initialized=!1}catch(t){console.error(`Failed to cleanup script cache: ${t}`)}}}