build method

Future<FlutterWebBuildResult> build(
  1. BuildWebOptions options, {
  2. StaticRouteManifest? routeManifest,
  3. MantleApp? app,
  4. void onProgress(
    1. String message
    )?,
})

Executes the complete Flutter Web build and static rendering pipeline.

Implementation

Future<FlutterWebBuildResult> build(
  BuildWebOptions options, {
  StaticRouteManifest? routeManifest,
  MantleApp? app,
  void Function(String message)? onProgress,
}) async {
  final stopwatch = Stopwatch()..start();
  final projectDir = Directory(options.projectDir);
  final String resolvedOutputPath;
  if (options.output.startsWith('/') || options.output.contains(':')) {
    resolvedOutputPath = options.output;
  } else if (projectDir.path != '.' &&
      (options.output == projectDir.path ||
          options.output.startsWith('${projectDir.path}/') ||
          options.output.startsWith('${projectDir.path}\\'))) {
    resolvedOutputPath = options.output;
  } else {
    resolvedOutputPath =
        '${projectDir.path}${Platform.pathSeparator}${options.output}';
  }
  final outputDir = Directory(resolvedOutputPath);

  onProgress?.call(
    'MetaMantle Web Build Engine starting [Mode: ${options.mode.name.toUpperCase()}]...',
  );

  // 1. Discover and validate Flutter project
  final pubspecFile = File(
    '${projectDir.path}${Platform.pathSeparator}pubspec.yaml',
  );
  if (!await pubspecFile.exists()) {
    throw FileSystemException(
      'Not a valid Dart/Flutter project directory. Missing pubspec.yaml.',
      pubspecFile.path,
    );
  }

  final webDir = Directory('${projectDir.path}${Platform.pathSeparator}web');
  final webIndex = File('${webDir.path}${Platform.pathSeparator}index.html');
  if (!await webIndex.exists()) {
    throw FileSystemException(
      'Missing web/index.html template in Flutter project.',
      webIndex.path,
    );
  }

  // 2. Resolve configuration & routes
  final File configFile;
  if (File(options.configPath).isAbsolute ||
      await File(options.configPath).exists()) {
    configFile = File(options.configPath);
  } else {
    configFile = File(
      '${projectDir.path}${Platform.pathSeparator}${options.configPath}',
    );
  }

  StaticHeadConfig? parsedConfig;
  if (await configFile.exists()) {
    parsedConfig = await StaticHeadConfig.load(configFile);
    onProgress?.call('Loaded configuration from ${configFile.path}');
  } else {
    parsedConfig = StaticHeadConfig(
      baseUrl: 'https://example.com',
      routes: const [
        StaticRoute(
          path: '/',
          metadata: WebMetadata(title: 'Home'),
        ),
      ],
    );
    onProgress?.call(
      'Config file not found; proceeding with defaults and manifest routes.',
    );
  }

  // 3. Manifest Discovery and Execution
  if (app != null) {
    final appManifest = routeManifest ?? StaticRouteManifest();
    for (final route in app.routes) {
      if (!route.path.contains(':')) {
        appManifest.register(
          StaticPageRoute(
            path: route.path,
            metadata: WebMetadata(title: route.title ?? app.title),
            componentBuilder: (ctx) => route.builder(ctx),
          ),
        );
      }
    }
    routeManifest = appManifest;
  }

  if (routeManifest == null) {
    final discoveredManifestFile = await _findManifestFile(
      projectDir,
      options,
      parsedConfig,
    );
    if (discoveredManifestFile != null) {
      onProgress?.call(
        'Discovered route manifest at ${discoveredManifestFile.path}',
      );
      final executedManifest = await _executeConsumerManifest(
        manifestFile: discoveredManifestFile,
        projectDir: projectDir,
        options: options,
        onProgress: onProgress,
      );
      if (executedManifest != null) {
        routeManifest = executedManifest;
      }
    }
  }

  final resolvedRoutes = await _resolveAllRoutes(
    config: parsedConfig,
    configFile: await configFile.exists() ? configFile : null,
    manifest: routeManifest,
  );

  if (resolvedRoutes.isEmpty) {
    throw const FormatException(
      'No routes resolved for static web generation.',
    );
  }

  final routesDiscovered = resolvedRoutes.length;
  onProgress?.call('Resolved $routesDiscovered route(s) for generation.');

  // 4. Compile Flutter Web project (unless dry-run or compileFlutter is disabled)
  if (!options.dryRun && options.compileFlutter) {
    if (options.clean) {
      onProgress?.call('Running flutter clean...');
      await _executeProcess('flutter', [
        'clean',
      ], workingDirectory: projectDir.path);
    }

    onProgress?.call('Compiling Flutter Web production build...');
    final buildArgs = <String>['build', 'web'];
    if (options.output.isNotEmpty &&
        options.output != 'build/web' &&
        options.output != '${projectDir.path}/build/web') {
      buildArgs.add('--output=${outputDir.path}');
    }
    if (options.release && !options.debug) {
      buildArgs.add('--release');
    } else if (options.debug) {
      buildArgs.add('--debug');
    }

    if (options.baseHref.isNotEmpty && options.baseHref != '/') {
      buildArgs.add('--base-href=${options.baseHref}');
    }
    if (options.wasm) {
      buildArgs.add('--wasm');
    }

    final buildResult = await _executeProcess(
      'flutter',
      buildArgs,
      workingDirectory: projectDir.path,
    );

    if (buildResult.exitCode != 0) {
      throw ProcessException(
        'flutter',
        buildArgs,
        'Flutter web build failed with exit code ${buildResult.exitCode}:\n${buildResult.stderr}',
        buildResult.exitCode,
      );
    }
    onProgress?.call('Flutter Web build succeeded.');
  } else if (!options.compileFlutter) {
    onProgress?.call(
      'Skipping Flutter Web compilation (--no-compile-flutter).',
    );
  } else {
    onProgress?.call('[DRY RUN] Skipping flutter build execution.');
  }

  // 5. Locate output template index.html
  var templateIndexFile = File(
    '${outputDir.path}${Platform.pathSeparator}index.html',
  );

  // If custom outputDir was requested and templateIndexFile is not there yet,
  // sync compiled web assets from default build/web if it exists.
  if (!await templateIndexFile.exists()) {
    final defaultBuildWeb = Directory(
      '${projectDir.path}${Platform.pathSeparator}build${Platform.pathSeparator}web',
    );
    if (await defaultBuildWeb.exists() &&
        defaultBuildWeb.path != outputDir.path) {
      onProgress?.call('Syncing compiled web assets to ${outputDir.path}...');
      await _copyDirectory(defaultBuildWeb, outputDir);
      templateIndexFile = File(
        '${outputDir.path}${Platform.pathSeparator}index.html',
      );
    }
  }

  String baseTemplateHtml;
  if (await templateIndexFile.exists()) {
    baseTemplateHtml = await templateIndexFile.readAsString();
  } else if (await webIndex.exists()) {
    baseTemplateHtml = await webIndex.readAsString();
  } else {
    throw FileSystemException(
      'Unable to find compiled index.html or source web/index.html.',
      templateIndexFile.path,
    );
  }

  // 6. Generate route-specific HTML documents
  final generatedFiles = <String>[];
  final warnings = <String>[];
  final sitemapUrls = <String>[];

  var componentsSerialized = 0;
  var dynamicRoutesCount = 0;
  var metadataErrorsCount = 0;
  var unsupportedComponentsCount = 0;
  var missingRouteContentCount = 0;
  var assetErrorsCount = 0;
  var htmlValidationErrorsCount = 0;

  final baseUrl = parsedConfig.baseUrl;
  final strategy =
      options.renderingStrategy != RenderingStrategy.flutterCanvas
      ? options.renderingStrategy
      : (parsedConfig.renderingStrategy ?? options.renderingStrategy);

  for (final route in resolvedRoutes) {
    final normPath = _normalizeRoute(route.path);
    final canonicalUrl =
        route.metadata.canonical ??
        _buildAbsoluteUrl(baseUrl, normPath, parsedConfig.trailingSlash);

    if (!_isNoindex(route.metadata.robots ?? parsedConfig.defaultRobots)) {
      sitemapUrls.add(canonicalUrl);
    }

    if (route.metadata.title == null ||
        route.metadata.title!.trim().isEmpty) {
      metadataErrorsCount++;
      warnings.add('Route $normPath has no title.');
    }

    if (route.dataSource != null) {
      dynamicRoutesCount++;
    }

    // Generate HTML with completeness tracking
    final docResult = _renderRouteDocument(
      templateHtml: baseTemplateHtml,
      route: route,
      config: parsedConfig,
      canonicalUrl: canonicalUrl,
      mode: options.mode,
      renderingStrategy: strategy,
      strict: options.strict,
    );

    if (docResult.hasComponentContent) {
      componentsSerialized += docResult.componentsCount;
      unsupportedComponentsCount += docResult.unsupportedComponentsCount;
    } else if (options.mode != BuildMode.metadata) {
      missingRouteContentCount++;
      warnings.add(
        'Route "$normPath" has no component tree or HTML content; emitting minimal shell.',
      );
    }

    if (docResult.htmlValidationErrors > 0) {
      htmlValidationErrorsCount += docResult.htmlValidationErrors;
      warnings.add(
        'Route "$normPath" has ${docResult.htmlValidationErrors} HTML validation error(s).',
      );
    }

    assetErrorsCount += _validateAssets(
      html: docResult.html,
      outputDir: outputDir,
      projectDir: projectDir,
      normPath: normPath,
      warnings: warnings,
    );

    final docHtml = docResult.html;
    final outputFile = _determineOutputFile(outputDir, normPath);
    if (!options.dryRun) {
      await outputFile.parent.create(recursive: true);
      await outputFile.writeAsString(docHtml, flush: true);
    }
    generatedFiles.add(outputFile.path);
    if (options.verbose) {
      onProgress?.call('Generated: $normPath -> ${outputFile.path}');
    }
  }

  // 7. Generate sitemap.xml & robots.txt
  final sortedUrls = sitemapUrls.toSet().toList()..sort();
  final isChunked = sortedUrls.length > 50000;

  if (parsedConfig.sitemap) {
    final entries = sortedUrls
        .map((url) => SitemapUrlEntry(loc: url))
        .toList();
    const generator = SitemapGenerator();
    final sitemapFiles = generator.generateSitemapIndex(
      entries: entries,
      sitemapBaseUrl: baseUrl,
    );

    for (final entry in sitemapFiles.entries) {
      final sFile = File(
        '${outputDir.path}${Platform.pathSeparator}${entry.key}',
      );
      if (!options.dryRun) {
        await sFile.parent.create(recursive: true);
        await sFile.writeAsString(entry.value, flush: true);
      }
      generatedFiles.add(sFile.path);
    }
    onProgress?.call(
      'Generated ${sitemapFiles.keys.join(', ')} with ${sortedUrls.length} entries.',
    );
  }

  if (parsedConfig.robotsTxt) {
    final robotsFile = File(
      '${outputDir.path}${Platform.pathSeparator}robots.txt',
    );
    final sitemapName = isChunked ? 'sitemap_index.xml' : 'sitemap.xml';
    final sitemapUrl = baseUrl.endsWith('/')
        ? '$baseUrl$sitemapName'
        : '$baseUrl/$sitemapName';
    final robotsContent = 'User-agent: *\nAllow: /\n\nSitemap: $sitemapUrl\n';

    if (!options.dryRun) {
      await robotsFile.parent.create(recursive: true);
      await robotsFile.writeAsString(robotsContent, flush: true);
    }
    generatedFiles.add(robotsFile.path);
    onProgress?.call('Generated robots.txt.');
  }

  stopwatch.stop();

  // 8. Write build report
  final reportFile = File(
    '${outputDir.path}${Platform.pathSeparator}meta_mantle_report.json',
  );

  final isSuccess = warnings.isEmpty || !options.strict;

  final buildResult = FlutterWebBuildResult(
    success: isSuccess,
    mode: options.mode,
    renderingStrategy: strategy,
    routes: resolvedRoutes.map((r) => r.path).toList(),
    generatedFiles: generatedFiles,
    warnings: warnings,
    durationMs: stopwatch.elapsedMilliseconds,
    reportPath: reportFile.path,
    routesDiscovered: routesDiscovered,
    routesRendered: generatedFiles
        .where((f) => f.endsWith('index.html'))
        .length,
    componentsSerialized: componentsSerialized,
    dynamicRoutes: dynamicRoutesCount,
    metadataErrors: metadataErrorsCount,
    unsupportedComponents: unsupportedComponentsCount,
    missingRouteContent: missingRouteContentCount,
    assetErrors: assetErrorsCount,
    htmlValidationErrors: htmlValidationErrorsCount,
  );

  if (!options.dryRun) {
    await reportFile.parent.create(recursive: true);
    await reportFile.writeAsString(
      const JsonEncoder.withIndent('  ').convert(buildResult.toJson()),
      flush: true,
    );
  }

  onProgress?.call(
    'Build complete in ${stopwatch.elapsedMilliseconds}ms. ${generatedFiles.length} files generated.',
  );

  if (options.strict && warnings.isNotEmpty) {
    throw FormatException(
      'Strict mode failed due to metadata/route warnings:\n${warnings.join('\n')}',
    );
  }

  return buildResult;
}