Skip to main content

foundry_core 0.0.1-dev.2 copy "foundry_core: ^0.0.1-dev.2" to clipboard
foundry_core: ^0.0.1-dev.2 copied to clipboard

Core library for Foundry — mold parsing, variable resolution, template rendering, and cast orchestration.

foundry_core #

Core Dart library for Foundry — mold manifests, variable resolution, template rendering, and cast orchestration.

Preview release. APIs may change before 1.0.0.

What it does #

Foundry molds are Dart packages with a variables.dart manifest, a template/ tree, and optional lifecycle hooks. This library provides:

  • Mold model — parse root pubspec.yaml and build a Mold with an in-memory live FoundryVariableGroup (callbacks such as visibleWhen / defaultValue stay intact)
  • Inspection — validate mold layout (template/, conventional hook paths); structural only — does not import variables.dart
  • Variable resolution — evaluate visibleWhen, defaultValue, and validators against a read-only SnapshotFoundryContext
  • Template rendering — render Liquid templates to an output directory. renderTemplate projects every cast context entry through projectLiquidView and fails loudly on unsupported types (including plain Dart enums). Non-JSON objects seeded for hooks must implement FoundryLiquidView (or be a liquify Drop), already be Liquid-safe, or be removed before render.
  • Hook execution — run prepare/shape/finish hooks against a mutable FoundryContext. Prefer runMoldHookInProcess when the hook's run is already imported in the current isolate (live context, no JSON round-trip). runMoldHook still spawns a dart run subprocess for host-side callers.
  • Cast orchestration — end-to-end castMold pipeline and .foundry/last_cast.json persistence
  • Import — copy molds from a local path or git (shallow clone; sparse checkout of a subdirectory when path is set, with full shallow fallback)
  • Pattern inspect / mold derive / mold sync — summarize pattern directories, best-effort derive a starter mold, and refresh an existing mold's template/ while preserving variables.dart and hooks/. Derive/sync resolve pattern comment annotations and .foundry/pattern.yaml replacements / lineDeletions into Liquid templates.

For day-to-day use, install the foundry_cli package (foundry mold init, foundry cast, and related commands). Use this library when embedding Foundry in tools or automation.

Installation #

Add foundry_core to your pubspec.yaml:

dependencies:
  foundry_core: ^0.0.1-dev.1

Requires Dart SDK >=3.5.0 <4.0.0.

Usage #

Inspect a mold structurally, then cast with an in-memory live variable group:

import 'dart:io';

import 'package:foundry_core/foundry_core.dart';

Future<void> main() async {
  final moldPath = 'path/to/my_mold';
  final outputPath = 'path/to/output';

  final report = await inspectMold(moldPath);
  if (!report.isValid) {
    for (final issue in report.issues) {
      stderr.writeln(issue);
    }
    exitCode = 1;
    return;
  }

  final mold = Mold(
    directory: report.mold!.directory,
    pubspec: report.mold!.pubspec,
    variableGroup: FoundryVariableGroup(
      variables: {
        'project_name': FoundryStringVariable(label: 'Project name'),
      },
    ),
  );
  final outcome = await castMold(
    mold: mold,
    outputPath: outputPath,
    values: {'project_name': 'my_app'},
    force: true,
    skipHooks: {
      MoldHookPhase.prepare,
      MoldHookPhase.shape,
      MoldHookPhase.finish,
    },
  );

  stdout.writeln(
    'Cast completed: ${outcome.artifactCount} file(s) written.',
  );
}

See the example/ directory for a runnable program against a bundled fixture mold.

Lifecycle hooks #

Mold hooks are top-level Dart files under hooks/ (prepare.dart, shape.dart, finish.dart). Each file that exists must export:

Future<void> run(FoundryContext context) async {
  // Mutate context with set / merge / remove as needed.
}

Missing hook files are no-ops unless a caller marks that phase in requiredHooks — then validateMoldHookSelection fails before the cast mutates the filesystem. Pass skipHooks to skip a subset of phases; skipping a required phase also fails validation. Optional hooks/policy.dart is a stable path (MoldHooks.policyPath / Mold.policyFile) for hosts to load author-declared required phases — core does not execute it.

Relative file I/O inside a hook uses the cast output directory as the process working directory.

When a host already imports the hook (for example via a file URI and moldHookFileUriImport), call runMoldHookInProcess with that run as entryPoint, or pass CastHooks to castMold / prepareCastContext / completeCast so the cast runner invokes those entry points in-process. Mutations stay on the same FoundryContext instance — including non-JSON Object values seeded by prepare — with no JSON round-trip between phases. Prefer that path whenever prepare, gather/shape, and finish must share a live heap. Use runMoldHook only when the host cannot import the hook and must spawn dart run (values are JSON-encoded across the process boundary).

Objects that templates should read must implement FoundryLiquidView (return a map, list, primitive, nested view, or liquify Drop from toLiquid()), or be stored as already Liquid-safe values. Plain custom classes and Dart enums are rejected at render time; prefer Flavor.vanilla.name (or a view) when an enum must appear in a template. Every context entry is projected at render — hook-only private objects must implement FoundryLiquidView, already be Liquid-safe, or be removed before render.

Do not invoke overlapping runMoldHookInProcess calls concurrently in the same process: Directory.current is process-wide for the duration of each hook.

Public API #

Import package:foundry_core/foundry_core.dart.

Area Key symbols
Mold parseMoldPubspec, inspectMold, Mold, FoundryVariableGroup
Derive deriveMoldFromPattern, MoldDeriveException
Sync syncMoldFromPattern, MoldSyncException
Pattern inspectPattern, PatternInspectionReport, PatternMarker
Context SnapshotFoundryContext, FoundryContext, FoundryContextException
Cast castMold, prepareCastContext, completeCast, CastHooks, parseCastVariableInputs (supports dotted object --vars paths such as publish.host=), CastOutcome, readCastState, writeCastState
Render renderTemplate, FoundryLiquidView, projectLiquidView, LiquidViewProjectionException
Hooks runMoldHook, runMoldHookInProcess, MoldHookEntryPoint, moldHookFileUriImport, moldHookPathForPhase, validateMoldHookSelection, FoundryHookException, MoldHookSelectionException
Import importMoldFromLocal, importMoldFromGit

Resources #

License #

MIT — see LICENSE.

0
likes
160
points
100
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Core library for Foundry — mold parsing, variable resolution, template rendering, and cast orchestration.

Homepage
Repository (GitHub)
View/report issues
Contributing

Topics

#mason #template #codegen #yaml #liquid

License

MIT (license)

Dependencies

checked_yaml, glob, liquify, meta, path, pubspec_parse, recase

More

Packages that depend on foundry_core