merman 0.10.0-alpha.2
merman: ^0.10.0-alpha.2 copied to clipboard
Flutter and Dart FFI bindings for merman headless Mermaid rendering.
Merman For Flutter #
Parse, analyze, lay out, and render Mermaid diagrams in Flutter or standalone Dart without a browser or JavaScript runtime. The package is a Dart-friendly facade over Merman's native ABI 3 table and uses Native Assets to bundle size-oriented native libraries for supported targets.
This guide documents 0.10.0-alpha.2. Check the host installation guide for verified versions and channel availability.
Merman.open()accepts only the exact native package version0.10.0-alpha.2paired with this Dart package.Merman.openPath(...)may load another package version, but both entry points require the current complete ABI 3 table, runtime catalog fields, Options JSON schema3, metadata and payload schemas, and service constructor. Historical partial ABI 3 producers and ABI 2 are not fallback paths.
Native ABI 3 and Options JSON schema 3 are unchanged from 0.10.0-alpha.1. Version 0.10.0-alpha.2 uses facts schema 3 and theme execution evidence schema 2, while alpha.1 retains facts schema 2 and theme execution evidence schema 1. Upgrade the Dart facade, manifest, and native assets together, and update JSON consumers for the source appearance and render-evidence changes.
Install #
Pin the exact package version when pairing the Dart facade with its Native Assets libraries:
flutter pub add 'merman:0.10.0-alpha.2'
For source development, use the matching 0.10.0-alpha.2 source revision and a local path dependency:
dependencies:
merman:
path: /path/to/merman/platforms/flutter
Run flutter pub get after adding the dependency.
For a stable 0.9.3 installation, use the tagged guide.
That release uses Options JSON schema 2 and math-free native libraries; keep its facade and
artifacts together rather than using them with the theme API documented here.
Requirements #
- Dart 3.10 or newer; Flutter apps require Flutter 3.47.7 or newer
- Android API 24 or newer
- iOS 13 or newer
- macOS 11 or newer
The Flutter floor follows the current native-hooks dependency graph and its SDK-pinned
meta compatibility. This package also supports native Dart without the Flutter SDK.
This is a package_ffi-style Dart package and does not depend on the Flutter SDK. Its build hook selects and bundles the native library for Flutter and Dart consumers. The public API can instead load a host-owned current-contract library with Merman.openPath(...); mermanPackageVersion is the exact version expected by Merman.open().
Target Native Assets #
The package ships a thin Dart facade. During a build, the hook downloads only the selected
OS, CPU and Apple SDK asset. hook/native-assets.json is generated from frozen release libraries
and included in that facade; it pins the package version, source commit/tree, compressed bytes
and library SHA-256 digests. Downloads and existing cache files are verified before bundling.
There is no runtime download or automatic Cargo build.
The 0.10.0-alpha.2 native assets belong to the workspace Merman Release v0.10.0-alpha.2, under https://github.com/Latias94/merman/releases/download/v0.10.0-alpha.2/, with filenames such as merman-flutter-native-0.10.0-alpha.2-macos-arm64.gz. Keep the facade, manifest, and target assets from the same release together. Check the host installation guide for verified download availability.
The 0.10.0-alpha.1 package retains its original download base https://github.com/Latias94/merman/releases/download/flutter-v0.10.0-alpha.1/. The hook always follows the manifest packaged with the installed version; historical packages keep their original URLs.
The cache lives in the hooks runner's outputDirectoryShared under .dart_tool. Preserve that
directory between online and offline builds of the same app and package version. Configure
acquisition in the consuming app's pubspec.yaml:
hooks:
user_defines:
merman:
offline: true
A cold offline cache fails with preparation instructions. To build without a network or a warm cache, explicitly supply a prepared native directory:
hooks:
user_defines:
merman:
native_assets: vendor/merman-native
offline: true
The path is relative to the pubspec that declares it and contains the selected target subtree,
for example macos/arm64/libmerman_ffi.dylib or android/arm64-v8a/libmerman_ffi.so.
This override participates in the hook's bundling and dependency tracking. It deliberately
selects host-owned bytes; package/ABI checks still run when the library is opened.
Merman.openPath(...) alone does not override build-hook acquisition.
An HTTPS mirror can host the same versioned asset filenames:
hooks:
user_defines:
merman:
mirror: https://artifacts.example.org/merman/v0.10.0-alpha.2/
The mirror changes the download location only; package-pinned digests remain mandatory.
HTTP is allowed solely for loopback qualification fixtures. Corrupt downloaded or cached bytes
fail visibly; remove the named invalid cache file before retrying. A source checkout without a
manifest can use explicitly built native/ libraries as described in Local Development.
Render A Diagram #
Merman is a stateless discovery and one-shot facade. It creates and closes a fresh native engine for each operation, so the facade itself has no close() method.
import 'package:merman/merman.dart';
const source = 'flowchart TD\nA[Hello] --> B[World]';
final merman = Merman.open();
final svg = merman.renderSvg(source);
print(svg.substring(0, 4)); // <svg
The generic API is available when an application needs to select an output at runtime. It returns a structured MermanOperationResult with the selected operation, media type, copied Dart bytes, and typed MermanOperationMetadata:
final output = merman.execute(MermanOperation.semanticJson, source);
final semantic = output.jsonObject;
print(output.metadata.runtimePolicy);
print(output.metadata.rawJson); // Includes additive fields from newer producers.
Convenience methods are projections over execute and cover all 13 generated ABI operations, including analysisFactsJson and svgPlanJson. renderPng, renderJpeg, and renderPdf retain their simple byte-returning forms; the matching renderPngResult, renderJpegResult, and renderPdfResult methods expose metadata and effective resource-limited output plans. Known raster and PDF plans have typed classes, while a future plan kind becomes MermanUnknownOutputPlan with preserved JSON.
The target assets provide SVG including math, semantic and layout JSON, Cytoscape and ELK layout,
ASCII, analysis, validation, and document analysis. PNG, JPEG, PDF and native runtime adapters
remain absent. The corresponding Dart methods remain part of the generated ABI facade
for a current-contract custom library loaded with Merman.openPath(...) or
Merman.fromDynamicLibrary(...); unavailable exporters raise MermanMissingCapabilityException
with capability png, jpeg, or pdf.
A native artifact can intentionally omit some outputs. Inspect merman.runtimeCatalog before enabling optional UI or export paths; an unavailable operation raises MermanUnsupportedOperationException rather than silently falling back. MermanUnknownOperationException identifies an ID outside the generated ABI vocabulary; MermanMissingCapabilityException.capabilityId identifies the backend absent from a valid native request.
Deadlines And Cancellation #
Create a reusable MermanOperationControl from the same Merman or MermanEngine instance and
attach it to execute. Resource and cancellation failures remain structured errors and never
return a partial document.
final engine = MermanEngine();
final control = engine.createOperationControl(
timeout: const Duration(milliseconds: 250),
);
try {
final result = engine.execute(
MermanOperation.svg,
source,
control: control,
);
print(result.utf8Text);
} on MermanCancelledException catch (error) {
print(error.cancellationDetails?.reason);
} finally {
control.release();
engine.close();
}
Execution is synchronous and the control is isolate-local. A Timer or message scheduled on the
same isolate cannot call cancel() while execute is blocking that isolate. The Dart facade
directly supports relative deadlines, cancellation before execution, and cancellation requested
from a synchronous host callback. Message-driven mid-render cancellation needs a host-owned native
or worker bridge that can call the native control concurrently; use a process boundary when
forceful termination is also required.
Parser and ASCII renderer failures may also expose MermanException.diagnosticDetails. Prefer its
stable code, optional byte span, field, and diagram type over parsing the human-facing message:
try {
merman.renderAscii(source);
} on MermanException catch (error) {
print(error.diagnosticDetails?.code);
print(error.diagnosticDetails?.span?.start);
}
Inspect Native Metadata #
The typed metadata APIs expose the loaded artifact's diagram, ASCII, parser/render, lint, Mermaid theme, and compiled-theme catalogs. Results are copied into Dart-owned immutable values and cached on the Merman instance. Decoders require the documented fields while tolerating additive JSON fields from a compatible newer producer. Theme preset and descriptor IDs remain open strings so compatible producers can add values without requiring Dart enum updates.
MermanThemePreset.previewColors exposes ordered picker swatches,
familyDesigns exposes curated family treatment, and applicationNotes contains typed
MermanThemePresetApplicationNote values with an open id, familyId, readable message, and
nullable recommendedConfig map. Use a matching artifact that provides this metadata; a package
version alone does not establish its availability for host-owned libraries loaded with
Merman.openPath(...). Missing additive arrays from older runtimes normalize to empty immutable
lists; malformed present fields are rejected. Recommendation maps
and their nested maps/lists are also copied and immutable. base_only is the shared base appearance with necessary family adaptations;
dedicated is an intentional family design, and absent or unknown treatments remain unreviewed.
Unknown values survive decoding. This metadata does not grant qualification or portability and
must not cause an implicit switch to a different preset when the diagram family changes.
Build the picker from the runtime inventory, using id for persistence and displayName for
labels. Ghibli is a normal preset with a dedicated Pie design; all current built-ins remain alpha
with empty qualification cells. Show applicable notes by familyId, preserving unknown IDs and
their fallback messages. Offer recommendedConfig as an explicit action that merges into the
host's Mermaid configuration while preserving unrelated nested values. Pass accepted settings
through site_config in the operation's options JSON; preset selection alone does not apply them.
Preview colors and application notes are curated visual guidance. Inspect the actual operation's
theme execution metadata for its rendering outcome and target admission.
final diagrams = merman.supportedDiagrams();
final ascii = merman.asciiCapabilities();
final families = merman.diagramFamilyCapabilities();
final lintRules = merman.lintRuleCatalog();
final themes = merman.supportedThemes();
final themeCatalog = merman.themeCatalog();
final rawCatalog = merman.metadataJson('supported-diagrams');
All six methods use the ABI 3 metadata_collect table slot. Discovery requires the current complete table before any engine or metadata API is exposed, including for Merman.openPath(...).
Select a discovered preset through Options JSON schema 3:
const pieSource = 'pie\n"A":35\n"B":65';
final themedSvg = merman.renderSvg(
pieSource,
optionsJson: '{"version":3,"theme":{"preset":"ghibli"}}',
);
For a reusable engine, omit theme to inherit its selection, use theme: null to clear it,
or supply a complete selection or recipe to replace it.
Flowchart glow and shadow effects require Classic look (site_config.flowchart.look: "classic");
selecting a preset does not change the look or layout engine. Fonts must be supplied by the
host and final SVG viewer; font-stack names do not embed fonts, and caller-provided font
resources in recipes are rejected. This Dart facade does not expose the native C/WASI
memory-font constructor. See the theme guide
for version-1 recipes, support discovery, and portability policy.
Options And Resource Limits #
One-shot Merman methods accept the complete schema-3 options document for that operation. MermanEngine accepts constructor options as a reusable baseline; method-level optionsJson values deeply override that baseline for one call while unspecified nested values remain inherited. Select runtime_policy only in the constructor options.
final engine = MermanEngine(
optionsJson: '''
{
"version": 3,
"resources": {"profile": "constrained"},
"svg": {"pipeline": "resvg-safe"}
}
''',
);
try {
final svg = engine.renderSvg(source);
} finally {
engine.close();
}
The packaged library is deterministic and does not include native clock, time-zone, or random adapters. A custom artifact may enable the atomic native-runtime feature and then select "runtime_policy":"native". The bundled artifact raises MermanUnsupportedOperationException when native policy is requested, and runtime discovery reports concrete adapter IDs only when they are present.
Use constrained for untrusted or multi-tenant input, interactive for cooperative local editing, and trusted-native for local native automation. MermanResourceOptionsBuilder produces the shared resource-options fragment. Its profile is optional: omit it for a reusable request that must inherit its constructor ceiling, and use MermanResourceOverrideId for limits. The runtime catalog is the source of truth for compiled capabilities, accepted option groups, constructor services, service limits, and enforced operation limits. See the options contract for the complete schema.
The default interactive profile admits SVG math. Explicit constrained policy rejects the
native math backend with MermanMissingCapabilityException and capability math; compiled
math does not remove the need for host execution and memory limits.
MermanResourceLimitId describes every catalog limit; MermanResourceOverrideId is the narrower option-construction ID set. Inspect runtimeCatalog.resourceLimits and runtimeCatalog.resourceProfiles for the loaded ABI 3 library's complete phase, description, minimum, hard-cap, applicable operation IDs, purpose, trust, recommendation, and nullable budget metadata. Those typed collections preserve additive IDs reported by a host-owned library; a null profile limit means unbounded, while hard caps are always finite.
Every current resource descriptor reports minimum_value; omitting it is a runtime-catalog contract error.
Reusable Engines And Constructor Services #
Use MermanEngine when options, icon packs, or host text measurement should be reused. MermanEngineServices is immutable constructor state; there are no post-construction mutators or callback-specialized constructors.
final engine = MermanEngine(
services: MermanEngineServices(
textMeasurer: (request) {
if (request.operation == MermanTextMeasurementOperation.measure) {
return MermanTextMeasureResult.metrics(
width: 42,
height: 18,
lineCount: 1,
);
}
return null; // Use the deterministic fallback for this operation.
},
),
);
try {
final svg = engine.renderSvg(source);
} finally {
engine.close();
}
The callback is isolate-local and synchronous. Create, render with, and close the measured engine on the same Dart isolate. Do not call back into that engine from the measurer. Precompute or cache WebView, platform-channel, and font results instead of blocking inside the callback. The host measurement guide describes result shapes and cache keys.
MermanIconPack accepts one in-memory IconifyJSON collection and an optional registration-name override. MermanIconPackSet.fromPacks enforces the fixed transport byte/count limits and snapshots packs into immutable UTF-8 buffers, so the source strings need not be retained. Flutter's C ABI has no separate native registry handle: those buffers are borrowed only during each MermanEngine constructor call, and the engine owns the parsed registry after construction returns. Native semantic validation is transactional at engine construction; a failure publishes no engine and exposes MermanException.iconRegistryDetails when available.
final iconPackSet = MermanIconPackSet.fromPacks([
MermanIconPack(
json: iconifyJson,
registrationName: 'product',
),
]);
final engine = MermanEngine(
services: MermanEngineServices(iconPackSet: iconPackSet),
);
try {
final svg = engine.renderSvg(source);
} finally {
engine.close();
}
Merman does not read files, fetch URLs, or trim icon collections. Hosts must acquire packs and pre-trim collections that exceed the fixed limits reported by runtimeCatalog.constructorServiceContracts. Icon bodies are XML-scoped and sanitized immediately before embedding under the effective render configuration, but SVG remains active document content: use a trusted WebView policy or an appropriate sanitizer/content-security boundary when displaying untrusted diagrams.
close() never waits. MermanBusyException means another operation is active, while MermanReentrantCallException means the same engine is inside its callback. Both failures retain the complete native engine and service graph so close can be retried. Only a confirmed native close releases the Dart callback registration; later closes are idempotent. Always close callback-owning engines explicitly because a callback may capture its engine and form a cycle.
Outputs are returned as owned Dart byte arrays. Internally, each written native result is released exactly once through its opaque ABI allocation token after the bytes and metadata are copied. The sole zero-token terminal case is native allocation-token exhaustion: INTERNAL_ERROR with the result otherwise untouched in its caller-initialized state. This keeps native pointers and allocators out of the public API.
SVG Display #
renderSvg returns SVG text; it intentionally does not choose a Flutter widget. Mermaid-compatible SVG can contain <style>, <marker>, and <foreignObject>. A WebView gives the closest browser behavior. Native SVG widgets and rasterizers can omit HTML labels, markers, or CSS features.
Choose the SVG pipeline for the final consumer:
parityis the default Mermaid-compatible output for browser/WebView use.readablefavors text fallbacks and inspectability.resvg-safeis the explicit choice for stricter SVG consumers, rasterizers, and PDF conversion.
Set the usual reusable pipeline in MermanEngine(optionsJson: ...). Override it for one call with renderSvg(source, optionsJson: ...), or pass the complete options document directly to a one-shot Merman.renderSvg call.
Migrating From Older Prerelease APIs #
These steps apply to older engine-owning prerelease APIs. Version 0.10.0-alpha.1 already uses the stateless facade and reusable-engine split; its alpha.2 migration requires matching assets and the JSON payload updates described above.
- Replace the engine-owning
Mermanusage with statelessMermanfor one-shot calls or directMermanEngine(...)construction for reuse. - Delete
MermanReusableEngine,Merman.reusableEngine(...),dispose(), and constructor-leveltextMeasurer:arguments. UseMermanEngineServicesandclose(). - Replace map access such as
result.metadata['runtime_policy']with typed fields such asresult.metadata.runtimePolicy; userawJsonfor additive fields. - Use
renderPngResult,renderJpegResult, orrenderPdfResultwhen effective output planning matters; byte-returning methods remain available. - Use
createOperationControl(timeout: ...)and pass the control toexecutefor cooperative deadlines. Do not rely on a same-isolateTimerto interrupt a synchronous call. - Treat runtime operation, resource-limit, option-group, and service IDs as discovered open vocabularies. Unknown runtime operations remain discoverable but require an updated generated SDK before numeric invocation.
Supported Platforms #
| Platform | Packaged native artifact |
|---|---|
| Android | armeabi-v7a, arm64-v8a, and x86_64 shared libraries |
| iOS | arm64 device plus arm64/x86_64 simulator dylibs |
| macOS | arm64 and x86_64 dylibs |
| Linux | arm64 and x86_64 shared libraries |
| Windows | x86_64 DLL |
Flutter Web is not supported because this package uses dart:ffi; use @mermanjs/web in browsers. Verify the release archive before deployment because native target availability is release-specific.
The build hook owns platform selection and Flutter owns final app bundling, framework assembly, install-name rewriting, and signing. There are no Flutter plugin registrars, CocoaPods podspecs, Swift packages, Gradle plugin modules, or CMake plugin wrappers. Android package slices use the flutter-android-native C ABI recipe from merman-ffi; the Kotlin AAR's JNI transport remains separate in merman-android-jni.
Local Development #
The checked-in low-level binding is generated with ffigen from the public C header. It validates
the size-tagged ABI 3 table and minimum-prefix digest, while release builds require the current
matching header/table contract. Application code uses merman.dart and never needs ABI pointers
or record definitions.
python3 platforms/flutter/build-native.py host
cd platforms/flutter
flutter pub get
dart run ffigen --config ffigen.yaml
flutter analyze
dart run tool/abi3_contract_test.dart
dart run tool/native_assets_contract_test.dart
dart run example/main.dart
dart run example/smoke.dart
dart run tool/theme_authoring_smoke.dart
CI regenerates the binding, rejects a stale checked-in result, runs analyzer and the ABI contract, then exercises the default Native Assets entry point against a real host library. build-native.py all-desktop assembles the complete Apple, Linux, and Windows release matrix on macOS; Android uses platforms/android/build-android.py --artifact-profile flutter-android-native. Native packaging is documented in the Flutter/Dart FFI guide.
Flutter release CI also qualifies the exact frozen thin package with
tool/qualify_packaged_app.py. It creates a Flutter macOS app outside the checkout, fetches only
the executing host's target through a local HTTP mirror, builds a release .app, removes the
temporary package and hook cache, and runs the relocated app with the server stopped. That app renders SVG math
and verifies that the three binary exporters remain unavailable. The uploaded qualification
receipt records the executed host; it does not establish execution on every target.
The repository-only theme authoring smoke compares light/dark materialization, full support discovery responses, and structured authoring/resource errors against shared cross-transport fixtures. It runs through the bundled Native Assets library using both one-shot and reusable engines in platform verification and Flutter release/preflight CI. It does not qualify final application bundles or visual output.
Documentation And Releases #
- Package changelog
- Flutter/Dart binding guide
- Diagram coverage
- Issue tracker
- Source repository
pub.dev is the supported registry channel. Native Assets is the only package-owned Flutter integration path.
License And Notices #
This package is available under MIT or Apache-2.0. See LICENSE, THIRD_PARTY_NOTICES.md, and THIRD_PARTY_LICENSES/ in the pub package.