executeFile function
Execute a Dart script file with fresh interpreter state.
This method:
- Reads the script from the file
- Recursively resolves all relative imports
- 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);
}
}