/** Resolve an existing session for exactly one project, from the shared registry. * Never fall back to another project. */ import { existsSync, realpathSync, statSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { resolveManifestPath } from '@volter/project/manifest/locate'; import { resolveProductForProject } from './product-locator.js'; import { EDITOR_SESSION_DISCOVERY_TIMEOUT_MS, type EditorSessionInfo, type SessionListingTransport as SessionDiscoveryTransport, HttpSessionDiscovery, withTimeout, } from './discovery.js'; /** Nearest ancestor containing the project's canonical manifest. */ export function findProjectRootFrom(dir: string): string | null { let cur = resolve(dir); for (;;) { if (existsSync(resolveManifestPath(cur))) return cur; const parent = dirname(cur); if (parent === cur) return null; cur = parent; } } /** The minimal slice of `EditorTransport` `resolveSession` actually needs — narrower than the full interface so a test double only has to implement one method. */ export type SessionListingTransport = SessionDiscoveryTransport; export interface ResolvedSession { /** Editor dev-server port the resolved session is listening on. */ port: number; /** Absolute project root — the nearest ancestor of the requested directory containing `volter.project.json`. */ projectRoot: string; } export interface SessionResolutionDeps { /** Session listing + liveness verification — defaults to a real `HttpSessionDiscovery`. Overridable for tests. */ transport?: SessionListingTransport; /** Project-root discovery — defaults to the real fs walk (`findProjectRootFrom` above). Overridable for tests. */ findProjectRootFrom?: (dir: string) => string | null; } function canonicalPath(path: string): string { try { return realpathSync(path); } catch { return resolve(path); } } /** Whether two paths are the same folder on disk, which `canonicalPath` alone misses on Windows * (it keeps the letter case typed, and short names and `subst` drives unexpanded). */ function sameDirectory(a: string, b: string): boolean { try { const x = statSync(a, { bigint: true }); const y = statSync(b, { bigint: true }); return x.dev === y.dev && x.ino === y.ino; } catch { return false; } } /** The code a refusal carries when the registry was read and no session opens the project: the * one state in which "no editor is open here" is a fact, which `close` answers as done. */ export const NO_SESSION_FOR_PROJECT = 'VOLTER_NO_SESSION_FOR_PROJECT'; /** The `code` of the refusal for this project's session whose manifest does not load; it carries `session`. */ export const SESSION_MANIFEST_UNREADABLE = 'VOLTER_SESSION_MANIFEST_UNREADABLE'; /** * The refusal for a session that IS this project's and cannot be driven, * because the project's manifest does not load. * * A refusal, not an attach: with no readable manifest the editor page itself * renders its startup-error screen, so there is no editor behind this door to * bind `{ editor, session }` to. It names the failing file and key, so an * operator fixes the manifest rather than starting a second editor. */ function manifestRefusal(projectRoot: string, manifestError: string, port: number): Error { return Object.assign( new Error( `@volter/live: the editor session for ${projectRoot} is live, but its volter.project.json does ` + 'not load, so there is no editor or project to drive — the editor page is showing this same ' + `error. Fix the manifest and retry; the session recovers on save, no restart needed.\n${manifestError}`, ), // The session is still this project's, so a caller that only needs to END it (`close`) can. { code: SESSION_MANIFEST_UNREADABLE, session: { port, projectRoot } }, ); } /** * Distinguish failed discovery, a readable empty registry and sessions serving * other canonical paths. Include the requested and listed paths for a path * mismatch; only a confirmed absence carries `NO_SESSION_FOR_PROJECT`. */ function noMatchingSessionRefusal( projectRoot: string, canon: string, sessions: readonly EditorSessionInfo[], discoveryFailure: string | null, ): Error { if (discoveryFailure !== null) { return new Error( `@volter/live: could not complete editor session discovery while looking for ${projectRoot} — ` + `${discoveryFailure}. This is not the answer "no editor is running": the question went ` + 'unanswered, so nothing is known about what is live. The step named above is the one that ' + 'did not answer: that session\'s server holds its port but did not reply to the request. ' + 'Its own log (logs/editor-.log in the project it serves) says how far its start got; ' + `${sessionsCommandFor(projectRoot)} asks the same question directly.`, ); } if (sessions.length === 0) { return Object.assign(new Error( `@volter/live: the editor session registry is readable and lists NO live sessions, so none ` + `covers ${projectRoot}. @volter/live only attaches to an already-running session — it ` + `never starts one — so run ${editCommandFor(projectRoot)} in that project first, then retry.`, ), { code: NO_SESSION_FOR_PROJECT }); } const listed = sessions .map((s) => ` port ${s.port} → ${s.project === null ? '(no project)' : s.project}`) .join('\n'); // A listed session that is this same folder under another spelling is not "nothing open here": // it keeps the refusal, so `close` does not report done while that editor runs on. const thisFolderElsewhere = sessions.some((s) => s.project !== null && sameDirectory(s.project, projectRoot)); return Object.assign(new Error( `@volter/live: ${sessions.length} live editor session(s) are running, but none of them opens ` + `${projectRoot}. @volter/live never silently attaches to a different project.\n` + ` looking for (resolved): ${canon}\n` + ` live sessions:\n${listed}\n` + ' If one of those is meant to be this project, the two paths differ after resolution — ' + 'the usual cause is a git worktree or a symlink, where the session was opened through a ' + `different path to the same files. Run ${editCommandFor(projectRoot)} from THIS path, or use the path the ` + 'session lists.', ), thisFolderElsewhere ? {} : { code: NO_SESSION_FOR_PROJECT }); } /** * Resolve `projectDir` (default `process.cwd()`) to its already-running editor * session from the shared registry, with each discovery probe bounded by * `EDITOR_SESSION_DISCOVERY_TIMEOUT_MS`. * Throw when no project manifest or matching live session is found. */ export async function resolveSession( projectDir: string = process.cwd(), deps: SessionResolutionDeps = {}, ): Promise { const findRoot = deps.findProjectRootFrom ?? findProjectRootFrom; const transport = deps.transport ?? new HttpSessionDiscovery(); const projectRoot = findRoot(projectDir); if (projectRoot === null) { throw new Error( `@volter/live: no volter.project.json found in ${projectDir} or any parent directory — is this a project?`, ); } let sessions: EditorSessionInfo[]; // Retain discovery failures separately from an empty session list so the // refusal names an unanswered probe rather than claiming no session exists. let discoveryFailure: string | null = null; try { sessions = await withTimeout( transport.listSessions(EDITOR_SESSION_DISCOVERY_TIMEOUT_MS), EDITOR_SESSION_DISCOVERY_TIMEOUT_MS, 'editor session discovery', ); } catch (err) { sessions = []; discoveryFailure = err instanceof Error ? err.message : String(err); } const canon = canonicalPath(projectRoot); const match = sessions.find((s) => s.project !== null && canonicalPath(s.project) === canon); if (!match) throw noMatchingSessionRefusal(projectRoot, canon, sessions, discoveryFailure); if (match.manifestError != null) throw manifestRefusal(projectRoot, match.manifestError, match.port); return { port: match.port, projectRoot }; } /** `` ` edit` `` for the product this project declares, or a generic * phrase when it declares none — this package serves every product and * names only the one the project installed. */ function editCommandFor(projectRoot: string): string { return verbFor(projectRoot, 'edit'); } function sessionsCommandFor(projectRoot: string): string { return verbFor(projectRoot, 'sessions'); } function verbFor(projectRoot: string, verb: string): string { try { return `\`${resolveProductForProject(projectRoot).command} ${verb}\``; } catch { return `its product's \`${verb}\` command`; } }