executeFile function

ScriptExecutionResult executeFile(
  1. D4rt d4rt,
  2. String filePath, {
  3. void log(
    1. String
    )?,
})

Execute a Dart script file with fresh interpreter state.

This method:

  1. Reads the script from the file
  2. Recursively resolves all relative imports
  3. Executes using D4rt.execute (replaces initialization)

d4rt The D4rt interpreter instance. filePath Path to the Dart script file. log Optional logging function for debugging import resolution.

Returns a ScriptExecutionResult with the execution outcome.

Implementation

ScriptExecutionResult executeFile(
  D4rt d4rt,
  String filePath, {
  void Function(String)? log,
}) {
  final file = File(filePath);

  if (!file.existsSync()) {
    return ScriptExecutionResult.failure('File not found: $filePath');
  }

  // Use resolveSymbolicLinksSync to normalize path (removes ./ and ..)
  final fullPath = file.resolveSymbolicLinksSync();

  try {
    final source = file.readAsStringSync();
    final basePath = file.parent.path;
    final libraryUri = 'file://$fullPath';

    // Pre-resolve all imports into sources map
    final sources = <String, String>{};
    resolveImportsRecursively(source, libraryUri, sources, log);

    // Execute with sources
    final result = d4rt.execute(
      library: libraryUri,
      sources: sources,
      basePath: basePath,
      allowFileSystemImports: true,
    );

    return ScriptExecutionResult.success(result, sources.length);
  } catch (e, stackTrace) {
    return ScriptExecutionResult.failure(e.toString(), stackTrace: stackTrace);
  }
}