|
1 | 1 | import { readFileSync } from 'node:fs'; |
2 | | -import { tmpdir } from 'node:os'; |
3 | | -import { join } from 'node:path'; |
| 2 | +import { |
| 3 | + buildPortFilePath, |
| 4 | + DOCUMENT_ROUTE, |
| 5 | + LOOPBACK_HOST, |
| 6 | + parsePortFile, |
| 7 | + TOKEN_HEADER, |
| 8 | +} from '@lemoncode/quickmock-registry-protocol'; |
4 | 9 | import { nullClient, type RegistryClient } from './registry.models'; |
5 | | -import { workspaceHash } from './registry.utils'; |
6 | 10 |
|
7 | | -/** HTTP client for the VSCode extension's registry server. Falls back to nullClient when the extension is not running. */ |
8 | | -export function createRegistryClient(): RegistryClient { |
9 | | - const workspaceRoot = process.env.QM_WORKSPACE_ROOT ?? process.cwd(); |
| 11 | +const REQUEST_TIMEOUT_MS = 2_000; |
10 | 12 |
|
11 | | - let port: number; |
| 13 | +function readPortFile(workspaceRoot: string) { |
12 | 14 | try { |
13 | | - const hash = workspaceHash(workspaceRoot); |
14 | | - const portFile = join(tmpdir(), `quickmock-${hash}.port`); |
15 | | - port = parseInt(readFileSync(portFile, 'utf-8').trim(), 10); |
16 | | - if (Number.isNaN(port)) { |
17 | | - return nullClient; |
18 | | - } |
| 15 | + const raw = readFileSync(buildPortFilePath(workspaceRoot), 'utf-8'); |
| 16 | + return parsePortFile(raw); |
19 | 17 | } catch { |
20 | | - return nullClient; |
| 18 | + return null; |
21 | 19 | } |
| 20 | +} |
| 21 | + |
| 22 | +/** HTTP client for the VSCode extension's registry server. Falls back to nullClient when the extension is not running. */ |
| 23 | +export function createRegistryClient(): RegistryClient { |
| 24 | + const workspaceRoot = process.env.QM_WORKSPACE_ROOT ?? process.cwd(); |
| 25 | + const portFile = readPortFile(workspaceRoot); |
| 26 | + if (!portFile) return nullClient; |
| 27 | + const { port, token } = portFile; |
22 | 28 |
|
23 | 29 | return { |
24 | 30 | async getDocument(fsPath: string): Promise<string | null> { |
25 | 31 | try { |
26 | | - const url = `http://127.0.0.1:${port}/document?path=${encodeURIComponent(fsPath)}`; |
27 | | - const res = await fetch(url, { signal: AbortSignal.timeout(2_000) }); |
28 | | - if (!res.ok) { |
29 | | - return null; |
30 | | - } |
| 32 | + const url = `http://${LOOPBACK_HOST}:${port}${DOCUMENT_ROUTE}?path=${encodeURIComponent(fsPath)}`; |
| 33 | + const res = await fetch(url, { |
| 34 | + headers: { [TOKEN_HEADER]: token }, |
| 35 | + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), |
| 36 | + }); |
| 37 | + if (!res.ok) return null; |
31 | 38 | return await res.text(); |
32 | 39 | } catch { |
33 | 40 | return null; |
|
0 commit comments