llmDiscoverNode function

Future<LlmNodeResolution> llmDiscoverNode({
  1. required LlmNodeHost host,
  2. String? nodePath,
  3. int floor = llmRequiredNodeMajorVersion,
})

Finds a Node at or above floor through host, or accounts for why not.

With nodePath set, only that executable is looked at — the setting replaces the search (library note). Without one the search runs in the order the library note states and stops at the first acceptable Node; a place that PATH and a fixed location both name is looked at once.

Implementation

Future<LlmNodeResolution> llmDiscoverNode({
  required LlmNodeHost host,
  String? nodePath,
  int floor = llmRequiredNodeMajorVersion,
}) async {
  final pathEntries = List<String>.unmodifiable(host.pathEntries);
  final looked = <LlmNodeCandidate>[];

  Future<LlmNodeCandidate> look(String path, LlmNodeSource source) async {
    if (!host.fileExists(path)) {
      return LlmNodeCandidate(
        path: path,
        source: source,
        outcome: LlmNodeLookOutcome.absent,
      );
    }
    final answer = await host.versionOf(path);
    if (answer == null) {
      return LlmNodeCandidate(
        path: path,
        source: source,
        outcome: LlmNodeLookOutcome.notRunnable,
      );
    }
    final parsed = llmParseNodeVersion(answer);
    if (parsed == null) {
      return LlmNodeCandidate(
        path: path,
        source: source,
        outcome: LlmNodeLookOutcome.accepted,
        version: answer.trim(),
      );
    }
    return LlmNodeCandidate(
      path: path,
      source: source,
      outcome: parsed.major < floor
          ? LlmNodeLookOutcome.tooOld
          : LlmNodeLookOutcome.accepted,
      version: parsed.version,
      major: parsed.major,
    );
  }

  LlmNodeResolution resolve() {
    final accepted = looked
        .where((c) => c.outcome == LlmNodeLookOutcome.accepted)
        .firstOrNull;
    return LlmNodeResolution(
      executable: accepted?.path,
      version: accepted?.version,
      looked: List.unmodifiable(looked),
      setting: nodePath,
      pathEntries: pathEntries,
      floor: floor,
    );
  }

  if (nodePath != null) {
    looked.add(await look(nodePath, LlmNodeSource.setting));
    return resolve();
  }

  final seen = <String>{};
  for (final (path, source) in llmNodeSearchPlaces(host)) {
    if (!seen.add(path)) continue;
    final candidate = await look(path, source);
    looked.add(candidate);
    if (candidate.outcome == LlmNodeLookOutcome.accepted) break;
  }
  return resolve();
}