Bundle: redb-route / redb.Route.Templates (redb.Route.Templates.txt), 14 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Templates/MediaType.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/MediaType.cs ---- namespace redb.Route.Templates; /// /// Result type of a payload template. Decides how substituted values are escaped and which /// ContentType the produced body gets. Mandatory: without it a value containing a quote or /// an ampersand silently breaks the document (WSO2 PayloadFactory defaults to XML, which is a trap). /// public enum MediaType { /// JSON: ", \ and control characters in substituted strings are escaped; ContentType = application/json. Json, /// XML: &, <, >, ", ' in substituted strings are escaped; ContentType = application/xml. Xml, /// Plain text: no escaping; ContentType = text/plain. Text, } Path: redb-route/redb.Route.Templates/PayloadTemplateContext.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateContext.cs ---- using System.Globalization; using System.Text; using System.Text.Encodings.Web; using System.Xml; using Scriban; using Scriban.Parsing; using Scriban.Runtime; namespace redb.Route.Templates; /// /// A value the template author has marked as already safe for the result document /// ({{ fragment | raw }}); written verbatim, bypassing media-type escaping. /// public sealed class RawString { /// Wraps text that must not be escaped. public RawString(string? value) => Value = value ?? string.Empty; /// The text. public string Value { get; } /// public override string ToString() => Value; } /// /// How a value becomes text — shared by the Scriban and the Liquid context. Two steps, deliberately /// apart: is the culture-invariant conversion (dates as ISO 8601) Scriban applies /// wherever a value turns into a string inside the template (concatenation, filters), and /// adds the escaping for the of the result, applied /// exactly once, at the point a value is written to the output. Escaping inside ObjectToString /// instead would escape a value again for every operator it passed through. Template literals never /// come this way; is written verbatim. /// internal static class PayloadValueFormatter { /// Value → text, culture-invariant, no escaping. public static string ToText(object? value, Func fallback) => value switch { null => string.Empty, RawString raw => raw.Value, string s => s, bool b => b ? "true" : "false", DateTime dt => dt.ToString("o", CultureInfo.InvariantCulture), DateTimeOffset dto => dto.ToString("o", CultureInfo.InvariantCulture), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => fallback(), }; /// Value → output text: , then escaped once for the media type; a verbatim. public static string Format(object? value, MediaType mediaType, Func fallback) => value is RawString raw ? raw.Value : Escape(ToText(value, fallback), mediaType); public static void Configure(TemplateContext context, RouteTemplateOptions options) { context.MemberRenamer = member => member.Name; // body.OrderId, not body.order_id context.StrictVariables = options.StrictVariables; context.EnableRelaxedMemberAccess = !options.StrictVariables; context.LoopLimit = options.LoopLimit; context.TemplateLoader = null; // no include from arbitrary paths (README decision 4) } private static string Escape(string text, MediaType mediaType) => mediaType switch { MediaType.Json => JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode(text), MediaType.Xml => XmlEscape(text), _ => text, }; /// /// The five XML entities, plus a replacement character for what XML 1.0 cannot carry at all: /// control characters other than tab / LF / CR and lone surrogates. Left in, they would make the /// document unparseable; U+FFFD is the same choice the JSON encoder makes for a lone surrogate. /// private static string XmlEscape(string text) { var sb = new StringBuilder(text.Length + 16); for (var i = 0; i < text.Length; i++) { var c = text[i]; switch (c) { case '&': sb.Append("&"); break; case '<': sb.Append("<"); break; case '>': sb.Append(">"); break; case '"': sb.Append("""); break; case '\'': sb.Append("'"); break; default: if (char.IsHighSurrogate(c) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) sb.Append(c).Append(text[++i]); else if (char.IsSurrogate(c) || !XmlConvert.IsXmlChar(c)) sb.Append('�'); else sb.Append(c); break; } } return sb.ToString(); } } /// Scriban-syntax render context with media-type escaping (see ). internal sealed class PayloadTemplateContext : TemplateContext { private readonly MediaType _mediaType; public PayloadTemplateContext(MediaType mediaType, RouteTemplateOptions options) { _mediaType = mediaType; PayloadValueFormatter.Configure(this, options); } /// Invariant text for every in-template conversion (concatenation, filters); no escaping here. public override string ObjectToString(object? value, bool nested = false) => PayloadValueFormatter.ToText(value, () => base.ObjectToString(value, nested) ?? string.Empty); /// The one place a value meets the result document: escaped here, once, whatever operators or filters produced it. public override TemplateContext Write(SourceSpan span, object? textAsObject) { if (textAsObject is not null) Write(PayloadValueFormatter.Format(textAsObject, _mediaType, () => ObjectToString(textAsObject))); return this; } } /// Liquid-syntax render context (Liquid filters such as upcase registered) with the same escaping. internal sealed class LiquidPayloadTemplateContext : LiquidTemplateContext { private readonly MediaType _mediaType; public LiquidPayloadTemplateContext(MediaType mediaType, RouteTemplateOptions options) { _mediaType = mediaType; PayloadValueFormatter.Configure(this, options); } /// Invariant text for every in-template conversion (concatenation, filters); no escaping here. public override string ObjectToString(object? value, bool nested = false) => PayloadValueFormatter.ToText(value, () => base.ObjectToString(value, nested) ?? string.Empty); /// The one place a value meets the result document: escaped here, once, whatever operators or filters produced it. public override TemplateContext Write(SourceSpan span, object? textAsObject) { if (textAsObject is not null) Write(PayloadValueFormatter.Format(textAsObject, _mediaType, () => ObjectToString(textAsObject))); return this; } } Path: redb-route/redb.Route.Templates/PayloadTemplateDefinition.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Templates; /// Where the rendered text goes. public enum TemplateTarget { /// Message body (and ContentType from the media type). Body, /// A message header named by . Header, /// An exchange property named by . Property, } /// /// The <payload> node: renders a template into the body, a header or a property. /// Compiles the template at route build — a missing file or a syntax error fails Start() /// with the template name and position. Declarative on purpose: the XML form and Message History /// read , , and . /// public sealed class PayloadTemplateDefinition : ProcessorDefinition { /// Creates the node. public PayloadTemplateDefinition(TextSource source, MediaType mediaType, TemplateTarget target = TemplateTarget.Body, string? targetName = null, TemplateArgs? args = null) { Source = source ?? throw new ArgumentNullException(nameof(source)); MediaType = mediaType; Target = target; if (target != TemplateTarget.Body) ArgumentException.ThrowIfNullOrWhiteSpace(targetName); TargetName = targetName; Args = args; } /// Template text origin. public TextSource Source { get; } /// Result type: drives escaping and ContentType. public MediaType MediaType { get; } /// Body, header or property. public TemplateTarget Target { get; } /// Header / property name when is not the body. public string? TargetName { get; } /// Named arguments evaluated before the render; null when none. public TemplateArgs? Args { get; } /// public override IProcessor CreateProcessor(IRouteContext context) { // Context services first (UseTemplates), then the DI container (AddRouteTemplates), then defaults. var options = context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(RouteTemplateOptions)) as RouteTemplateOptions ?? new RouteTemplateOptions(); // A relative path is looked up as every other file reference is: the context resolver (a // package keeps its templates where only that resolver knows), then the base directory. // A miss stays a template failure, not an IO one — the step promises one exception type. TextSource source; try { source = ResourceResolution.Locate(context, Source, options.BaseDirectory, "Template"); } catch (FileNotFoundException ex) { throw new TemplateCompilationException(Source.Name, null, null, ex.Message, ex); } var compiled = TemplateEngine.Compile(source, options); return new PayloadTemplateProcessor(compiled, MediaType, Target, TargetName, Args, options); } } Path: redb-route/redb.Route.Templates/PayloadTemplateProcessor.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Templates; /// Runtime side of : renders and writes the result to its target. internal sealed class PayloadTemplateProcessor : IProcessor { private readonly CompiledTemplate _compiled; private readonly MediaType _mediaType; private readonly TemplateTarget _target; private readonly string? _targetName; private readonly TemplateArgs? _args; private readonly RouteTemplateOptions _options; public PayloadTemplateProcessor(CompiledTemplate compiled, MediaType mediaType, TemplateTarget target, string? targetName, TemplateArgs? args, RouteTemplateOptions options) { _compiled = compiled; _mediaType = mediaType; _target = target; _targetName = targetName; _args = args; _options = options; } public Task Process(IExchange exchange, CancellationToken ct = default) { var text = TemplateEngine.Render(_compiled, exchange, _mediaType, _args, _options); switch (_target) { case TemplateTarget.Header: exchange.In.Headers[_targetName!] = text; break; case TemplateTarget.Property: exchange.Properties[_targetName!] = text; break; default: exchange.In.Body = text; exchange.In.ContentType = ContentTypeOf(_mediaType); break; } return Task.CompletedTask; } /// Content type written to the message when the target is the body. public static string ContentTypeOf(MediaType mediaType) => mediaType switch { MediaType.Json => "application/json", MediaType.Xml => "application/xml", _ => "text/plain", }; } Path: redb-route/redb.Route.Templates/PayloadXmlContribution.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadXmlContribution.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Templates; /// /// The <payload> element: a Scriban /// template — referenced by a locator or inline in the content — rendered into the body (the /// default), a header or an exchange property; <arg name=… expr=…/> / /// <arg name=… value=…/> children feed the template model. /// public sealed class PayloadXmlContribution : IXmlElementContribution { /// public string Name => "payload"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => new(Name, Kind, [ new AttributeSpec("template", AttributeType.String) { Resource = true }, // The format spells the values lowercase (json/xml/text); parsing is case-insensitive. new AttributeSpec("mediaType", AttributeType.Enum, Required: true, EnumValues: ["json", "xml", "text"]), new AttributeSpec("target", AttributeType.String), ], [ElementSpec.Child("arg", false, new AttributeSpec("name", AttributeType.String, Required: true), new AttributeSpec("value", AttributeType.String), new AttributeSpec("expr", AttributeType.Expression))], AllowsTextContent: true); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { var locator = context.Attr(element, "template"); var inline = Text(element); if ((locator is null) == (inline is null)) { context.AddError(element, " takes either the template locator or inline template content, not both."); return current; } var mediaTypeName = context.RequiredAttr(element, "mediaType"); if (mediaTypeName is null) return current; if (!Enum.TryParse(mediaTypeName, ignoreCase: true, out var mediaType)) { context.AddError(element, $"'{mediaTypeName}' is not a media type ({string.Join(", ", Enum.GetNames())})."); return current; } var arguments = new List<(string Name, string? Expr, string? Value)>(); foreach (var child in element.Elements().Where(c => c.Name.LocalName == "arg")) { var name = context.RequiredAttr(child, "name"); var pick = context.ExactlyOneOf(child, "value", "expr"); if (name is null || pick is null) continue; arguments.Add((name, pick.Value.Name == "expr" ? pick.Value.Value : null, pick.Value.Name == "value" ? pick.Value.Value : null)); } Action? args = arguments.Count == 0 ? null : model => { foreach (var (name, expr, value) in arguments) { if (expr is not null) model.Set(name, expr); else model.SetValue(name, value); } }; var source = locator is null ? TextSource.Inline(inline!) : TextSource.FromLocator(locator); var target = context.Attr(element, "target") ?? "body"; if (target == "body") return current.SetBodyTemplate(source, mediaType, args); if (target.StartsWith("header:", StringComparison.Ordinal)) return current.SetHeaderTemplate(target["header:".Length..], source, mediaType, args); if (target.StartsWith("property:", StringComparison.Ordinal)) return current.SetPropertyTemplate(target["property:".Length..], source, mediaType, args); context.AddError(element, $"target='{target}' is not valid — body (default), header:Name or property:Name."); return current; } /// public void Print(XElement element, XmlCodeWriter code) { var source = element.Attribute("template")?.Value is { } locator ? $"TextSource.FromLocator({XmlCodeWriter.Str(locator)})" : $"TextSource.Inline({XmlCodeWriter.Str(Text(element) ?? "")})"; var mediaType = $"MediaType.{Enum.Parse(element.Attribute("mediaType")?.Value ?? "Json", true)}"; var argCalls = element.Elements().Where(c => c.Name.LocalName == "arg") .Select(c => c.Attribute("expr")?.Value is { } expr ? $".Set({XmlCodeWriter.Str(c.Attribute("name")?.Value ?? "")}, {XmlCodeWriter.Str(expr)})" : $".SetValue({XmlCodeWriter.Str(c.Attribute("name")?.Value ?? "")}, {XmlCodeWriter.Str(c.Attribute("value")?.Value ?? "")})") .ToList(); var args = argCalls.Count == 0 ? null : "a => a" + string.Concat(argCalls); var target = element.Attribute("target")?.Value ?? "body"; if (target == "body") code.Verb(element, "SetBodyTemplate", args is null ? [source, mediaType] : [source, mediaType, args]); else if (target.StartsWith("header:", StringComparison.Ordinal)) code.Verb(element, "SetHeaderTemplate", args is null ? [XmlCodeWriter.Str(target["header:".Length..]), source, mediaType] : [XmlCodeWriter.Str(target["header:".Length..]), source, mediaType, args]); else code.Verb(element, "SetPropertyTemplate", args is null ? [XmlCodeWriter.Str(target["property:".Length..]), source, mediaType] : [XmlCodeWriter.Str(target["property:".Length..]), source, mediaType, args]); } private static string? Text(XElement element) { var text = string.Concat(element.Nodes().OfType().Select(t => t.Value)); return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); } } Path: redb-route/redb.Route.Templates/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/README.md ---- # redb.Route.Templates > Documentation and articles: Build a payload from a template instead of concatenating strings: the analog of WSO2 PayloadFactory and Camel's templating components, on [Scriban](https://github.com/scriban/scriban). Templates live in files, embedded resources or inline; the result type is explicit so substituted values are escaped correctly for JSON or XML. ```csharp .SetBodyTemplate("Templates/order-confirm.json.sbn", MediaType.Json, a => a .Set("customer", "header.customerId") // route expression language .Set("total", "header.amount * header.qty") .SetValue("channel", "email")) // constant ``` ```scriban { "id": {{ headers.orderId }}, "customer": "{{ args.customer }}", "items": [ {{~ for i in body.items ~}} { "sku": "{{ i.sku }}", "qty": {{ i.qty }} }{{ if !for.last }},{{ end }} {{~ end ~}} ] } ``` ## Rules | Rule | Why | |---|---| | A `string` argument is a **locator**: a file path or `assembly:Name/Path/file.sbn`. Inline text is `TextSource.Inline("...")`. | A string never has to be guessed as "path or text" — the same rule the route expression language follows. | | A relative path is looked up by the context's `IRouteResourceResolver` first, then by `RouteTemplateOptions.BaseDirectory` (default `AppContext.BaseDirectory`). A miss names both places. | One lookup order for the whole framework: the same one `validateXsd`, `xslt` and the XML context files use. A route inside a `.tpkg` keeps its template in `resources/`, which only the package resolver knows about — the base directory stays the worker's. | | `MediaType` is mandatory: `Json`, `Xml`, `Text`. | It decides escaping of substituted values (`"`/`\`/control characters for JSON; `& < > " '` for XML) and the `ContentType` of the produced body. Template literals are never escaped — only values. `{{ x \| raw }}` writes a value verbatim. | | Numbers and dates render culture-invariant; dates as ISO 8601. | A payload must not depend on the server locale. | | Compiled at route build, cached by source. | A missing file or a syntax error fails `Start()` with the template name and `(line,column)`. | | Sandbox: no `include`, no context objects, .NET objects expose public properties and fields only. | Templates are data, not code. A method call on a body object fails the render, and so does one inside `expr(...)` or an argument expression: those run under `ExpressionSandbox`, where the expression engine refuses reflection calls (its built-in helpers such as `contains`, `substring`, `length` keep working). | ## Data model in a template | Name | What | |---|---| | `body` | JSON text → object tree (`body.order.id`); XML text → navigable tree (`body.order.item[0].sku`, attributes and child elements as members, repeated children as arrays, element text under `text`); POCO → its public members with their C# names; dictionaries → members | | `headers.name`, `headers["Content-Type"]` | message headers | | `properties.name` | exchange properties | | `exception.message`, `.type`, `.stackTrace` | current exception or `null` | | `args.name` | named arguments of the step | | `expr("header.amount * header.qty")` | any route-language expression, evaluated by the same engine as `${...}` | | `raw(value)` / `{{ value \| raw }}` | skip escaping for this value | ## Options ```csharp services.AddRouteTemplates(o => { o.BaseDirectory = "/etc/acme/templates"; o.Liquid = false; }); // or, without DI: context.UseTemplates(o => o.StrictVariables = true); ``` `Liquid = true` switches to Scriban's Liquid-compatible syntax. `StrictVariables` makes a missing variable a render error instead of an empty string. `LoopLimit` (default 10 000) bounds loops. ## Targets `SetBodyTemplate` (body + `ContentType`), `SetHeaderTemplate(name, ...)`, `SetPropertyTemplate(key, ...)`. ## XML form The same node in an XML route ([redb.Route.Xml](../redb.Route.Xml/README.md)): ```xml ]]> ``` Path: redb-route/redb.Route.Templates/RouteTemplateOptions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/RouteTemplateOptions.cs ---- namespace redb.Route.Templates; /// /// Package-wide settings, registered with services.AddRouteTemplates(...) or /// context.UseTemplates(...); defaults apply when neither was called. /// public sealed class RouteTemplateOptions { /// Directory relative template paths are resolved against. Default: . public string BaseDirectory { get; set; } = AppContext.BaseDirectory; /// Parse templates with Scriban's Liquid-compatible syntax instead of the native {{ }} syntax. Default: false. public bool Liquid { get; set; } /// Fail a render when the template reads a variable that does not exist (Scriban StrictVariables). Default: false — a missing value renders empty. public bool StrictVariables { get; set; } /// Upper bound on loop iterations per render, a guard against a runaway template. Default: 10 000. public int LoopLimit { get; set; } = 10_000; } Path: redb-route/redb.Route.Templates/TemplateArgs.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateArgs.cs ---- using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Templates; /// /// Named arguments of a payload step — the analog of WSO2 PayloadFactory <arg>, but by /// name instead of position: args.Set("customer", "header.customerId") is read in the template /// as {{ args.customer }}. Argument expressions are the route expression language and are /// evaluated on the message before rendering, which keeps the template itself an almost /// static document a non-programmer can edit. /// public sealed class TemplateArgs { private readonly Dictionary _expressions = new(StringComparer.Ordinal); private readonly Dictionary _constants = new(StringComparer.Ordinal); /// Argument computed from a route-language expression ("header.amount * header.qty"); the expression is compiled now, so a typo fails at Start(). public TemplateArgs Set(string name, string expression) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentException.ThrowIfNullOrWhiteSpace(expression); return Set(name, new StringExpression(expression)); } /// Argument computed from an . public TemplateArgs Set(string name, IExpression expression) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(expression); _constants.Remove(name); _expressions[name] = expression; return this; } /// Constant argument (XML form <arg name="channel" value="email"/>). public TemplateArgs SetValue(string name, object? value) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _expressions.Remove(name); _constants[name] = value; return this; } /// Argument names, for diagnostics. public IEnumerable Names => _expressions.Keys.Concat(_constants.Keys); /// Evaluates every argument against the exchange. internal Dictionary Evaluate(IExchange exchange) { var result = new Dictionary(_constants, StringComparer.Ordinal); foreach (var (name, expression) in _expressions) result[name] = expression.Evaluate(exchange); return result; } } Path: redb-route/redb.Route.Templates/TemplateCompilationException.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateCompilationException.cs ---- namespace redb.Route.Templates; /// /// A template could not be read or parsed. Raised while the route is compiled, so it surfaces from /// RouteContext.Start() with the template name and the first error's line and column. /// public sealed class TemplateCompilationException : Exception { /// Creates the exception. public TemplateCompilationException(string templateName, int? line, int? column, string message, Exception? inner = null) : base(Format(templateName, line, column, message), inner) { TemplateName = templateName; Line = line; Column = column; } /// Template name as given in the DSL / XML (file path, resource locator, or <inline>). public string TemplateName { get; } /// 1-based line of the first error, when known. public int? Line { get; } /// 1-based column of the first error, when known. public int? Column { get; } private static string Format(string name, int? line, int? column, string message) => line is null ? $"Template '{name}': {message}" : $"Template '{name}' ({line},{column}): {message}"; } Path: redb-route/redb.Route.Templates/TemplateEngine.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateEngine.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using Scriban; using Scriban.Parsing; namespace redb.Route.Templates; /// A parsed template plus the source it came from. internal sealed record CompiledTemplate(TextSource Source, Template Template); /// /// Compiles templates once (cache keyed by source identity and syntax) and renders them per message. /// Compilation errors become with the template name and /// the first error's position; they are raised at route build, i.e. from Start(). /// internal static class TemplateEngine { private static readonly ConcurrentDictionary> Cache = new(StringComparer.Ordinal); private static int _compileCount; /// Number of actual parses so far — lets a test prove the cache (two routes, one file, one parse). public static int CompileCount => Volatile.Read(ref _compileCount); /// Drops every cached template (tests). public static void ClearCache() => Cache.Clear(); public static CompiledTemplate Compile(TextSource source, RouteTemplateOptions options) { // Keyed by the resolved file (path, size, write time) and the syntax: the cache is process-wide, // and a relative name alone would make two base directories share one template. var key = (options.Liquid ? "liquid|" : "scriban|") + source.ResolveCacheKey(options.BaseDirectory); var lazy = Cache.GetOrAdd(key, _ => new Lazy(() => Parse(source, options), LazyThreadSafetyMode.ExecutionAndPublication)); try { return lazy.Value; } catch { Cache.TryRemove(key, out _); // do not cache a failure: the file may be fixed and the context restarted throw; } } private static CompiledTemplate Parse(TextSource source, RouteTemplateOptions options) { string text; try { text = source.Read(options.BaseDirectory); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { throw new TemplateCompilationException(source.Name, null, null, ex.Message, ex); } Interlocked.Increment(ref _compileCount); var template = options.Liquid ? Template.ParseLiquid(text, source.Name) : Template.Parse(text, source.Name); if (template.HasErrors) { var first = template.Messages.FirstOrDefault(m => m.Type == ParserMessageType.Error) ?? template.Messages.First(); var all = string.Join("; ", template.Messages.Select(m => m.Message)); throw new TemplateCompilationException(source.Name, first.Span.Start.Line + 1, first.Span.Start.Column + 1, all); } return new CompiledTemplate(source, template); } public static string Render(CompiledTemplate compiled, IExchange exchange, MediaType mediaType, TemplateArgs? args, RouteTemplateOptions options) { TemplateContext context = options.Liquid ? new LiquidPayloadTemplateContext(mediaType, options) : new PayloadTemplateContext(mediaType, options); // Arguments and expr() evaluate route-language expressions written as data: inside the sandbox // they read members but can never invoke a method on the objects they reach. using var sandbox = redb.Route.Expressions.ExpressionSandbox.Enter(); var evaluatedArgs = args?.Evaluate(exchange) ?? new Dictionary(); context.PushGlobal(TemplateModel.Build(exchange, evaluatedArgs)); return compiled.Template.Render(context); } } Path: redb-route/redb.Route.Templates/TemplateModel.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateModel.cs ---- using System.Collections; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using Scriban.Runtime; namespace redb.Route.Templates; /// /// The data a template sees — one model for the DSL and the XML form: /// body (JSON text parsed to an object tree, XML text to a navigable tree, a POCO as-is with /// its public members), headers.name / headers["Content-Type"], properties.name, /// exception.message, args.name, and two functions: expr("header.a * 2") /// (the route expression language, same engine as ${...}) and raw (skip escaping). /// No exchange, no context, no methods (README decision 4). /// internal static class TemplateModel { public static ScriptObject Build(IExchange exchange, IReadOnlyDictionary args) { var model = new ScriptObject { ["body"] = ConvertBody(exchange.In.Body, exchange.In.ContentType), ["headers"] = ToScriptObject(exchange.In.Headers), // Framework bookkeeping (__redb_scope:* holds live DI scopes) is not data; same rule as JsonTransform. ["properties"] = ToScriptObject(exchange.Properties.Where(p => !p.Key.StartsWith("__", StringComparison.Ordinal))), ["exception"] = exchange.Exception is { } ex ? new ScriptObject { ["message"] = ex.Message, ["type"] = ex.GetType().Name, ["stackTrace"] = ex.StackTrace } : null, ["args"] = ToScriptObject(args), }; model.Import("expr", new Func(expression => ExpressionResolver.ResolveExpression(expression, exchange))); model.Import("raw", new Func(value => new RawString(value?.ToString()))); return model; } /// JSON / XML text (by content type or first significant character) becomes a tree; anything else is passed through. internal static object? ConvertBody(object? body, string? contentType) { switch (body) { case null: return null; case byte[] bytes: return ConvertBody(Encoding.UTF8.GetString(bytes), contentType); case JsonNode node: return FromJson(node); case JsonElement element: return FromJson(JsonSerializer.SerializeToNode(element)); case JsonDocument document: return FromJson(JsonSerializer.SerializeToNode(document.RootElement)); case XDocument xdoc: return xdoc.Root is null ? null : new ScriptObject { [xdoc.Root.Name.LocalName] = FromXml(xdoc.Root) }; case XElement xel: return new ScriptObject { [xel.Name.LocalName] = FromXml(xel) }; case string text: return ConvertText(text, contentType); case IDictionary dict: return ToScriptObject(dict); default: return body; } } private static object? ConvertText(string text, string? contentType) { var trimmed = text.AsSpan().TrimStart(); var isJson = contentType?.Contains("json", StringComparison.OrdinalIgnoreCase) == true || (trimmed.Length > 0 && (trimmed[0] == '{' || trimmed[0] == '[')); if (isJson) { try { return FromJson(JsonNode.Parse(text)); } catch (JsonException) { return text; } } var isXml = contentType?.Contains("xml", StringComparison.OrdinalIgnoreCase) == true || (trimmed.Length > 0 && trimmed[0] == '<'); if (isXml) { try { var root = SafeXml.Parse(text).Root; return root is null ? text : new ScriptObject { [root.Name.LocalName] = FromXml(root) }; } catch (System.Xml.XmlException) { return text; } } return text; } private static object? FromJson(JsonNode? node) => node switch { null => null, JsonObject obj => ObjectFromJson(obj), JsonArray arr => ArrayFromJson(arr), JsonValue value => ScalarFromJson(value), _ => node.ToJsonString(), }; private static ScriptObject ObjectFromJson(JsonObject obj) { var result = new ScriptObject(); foreach (var (key, value) in obj) result[key] = FromJson(value); return result; } private static ScriptArray ArrayFromJson(JsonArray arr) { var result = new ScriptArray(); foreach (var item in arr) result.Add(FromJson(item)); return result; } private static object? ScalarFromJson(JsonValue value) { var element = value.GetValue(); switch (element.ValueKind) { case JsonValueKind.String: return element.GetString(); case JsonValueKind.True: return true; case JsonValueKind.False: return false; case JsonValueKind.Null: return null; case JsonValueKind.Number: if (element.TryGetInt32(out var i)) return i; if (element.TryGetInt64(out var l)) return l; if (element.TryGetDecimal(out var m)) return m; return element.GetDouble(); default: return element.GetRawText(); } } /// /// Element → object: attributes and child elements become members (repeated child names become an /// array); a leaf element becomes its text; an element with children keeps its own text under /// text. So <order id="7"><item sku="a"/><item sku="b"/></order> reads as /// body.order.id, body.order.item[1].sku. /// private static object? FromXml(XElement element) { if (!element.HasElements && !element.HasAttributes) return element.Value; var result = new ScriptObject(); foreach (var attribute in element.Attributes().Where(a => !a.IsNamespaceDeclaration)) result[attribute.Name.LocalName] = attribute.Value; foreach (var group in element.Elements().GroupBy(e => e.Name.LocalName)) { var items = group.ToList(); if (items.Count == 1) result[group.Key] = FromXml(items[0]); else { var array = new ScriptArray(); foreach (var item in items) array.Add(FromXml(item)); result[group.Key] = array; } } var text = string.Concat(element.Nodes().OfType().Select(t => t.Value)).Trim(); if (text.Length > 0) result["text"] = text; return result; } private static ScriptObject ToScriptObject(IEnumerable> pairs) { var result = new ScriptObject(); foreach (var (key, value) in pairs) result[key] = value is IDictionary nested ? ToScriptObject(nested) : value; return result; } } Path: redb-route/redb.Route.Templates/TemplateRegistrationExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateRegistrationExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; namespace redb.Route.Templates; /// /// Registers . Optional: without a registration the defaults apply /// (templates relative to , Scriban syntax). /// public static class TemplateRegistrationExtensions { /// DI registration: services.AddRouteTemplates(o => o.BaseDirectory = "/etc/acme/templates"). public static IServiceCollection AddRouteTemplates(this IServiceCollection services, Action? configure = null) { ArgumentNullException.ThrowIfNull(services); var options = new RouteTemplateOptions(); configure?.Invoke(options); services.TryAddSingleton(options); return services; } /// Registration on a context built without DI: context.UseTemplates(o => o.Liquid = true). public static IRouteContext UseTemplates(this IRouteContext context, Action? configure = null) { ArgumentNullException.ThrowIfNull(context); var options = new RouteTemplateOptions(); configure?.Invoke(options); context.AddService(typeof(RouteTemplateOptions), options); return context; } } Path: redb-route/redb.Route.Templates/TemplateRouteDefinitionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateRouteDefinitionExtensions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Templates; /// /// DSL of the payload template step. A string argument is a locator (file path relative /// to , or assembly:Name/path); inline text is /// written as TextSource.Inline("..."). /// /// /// .SetBodyTemplate("Templates/order-confirm.json.sbn", MediaType.Json) /// .SetBodyTemplate(TextSource.Inline("""{"id": {{ headers.orderId }}}"""), MediaType.Json) /// .SetBodyTemplate("Templates/notify.xml.sbn", MediaType.Xml, a => a /// .Set("customer", "header.customerId") /// .Set("total", "header.amount * header.qty") /// .SetValue("channel", "email")) /// .SetHeaderTemplate("X-Summary", TextSource.Inline("{{ body.items | array.size }} items"), MediaType.Text) /// /// /// public static class TemplateRouteDefinitionExtensions { /// Renders the template into the message body; ContentType follows . public static IRouteDefinition SetBodyTemplate(this IRouteDefinition route, string locator, MediaType mediaType, Action? args = null) => SetBodyTemplate(route, TextSource.FromLocator(locator), mediaType, args); /// Renders the template into the message body; ContentType follows . public static IRouteDefinition SetBodyTemplate(this IRouteDefinition route, TextSource source, MediaType mediaType, Action? args = null) => Append(route, new PayloadTemplateDefinition(source, mediaType, TemplateTarget.Body, null, BuildArgs(args))); /// Renders the template into header . public static IRouteDefinition SetHeaderTemplate(this IRouteDefinition route, string name, string locator, MediaType mediaType, Action? args = null) => SetHeaderTemplate(route, name, TextSource.FromLocator(locator), mediaType, args); /// Renders the template into header . public static IRouteDefinition SetHeaderTemplate(this IRouteDefinition route, string name, TextSource source, MediaType mediaType, Action? args = null) => Append(route, new PayloadTemplateDefinition(source, mediaType, TemplateTarget.Header, name, BuildArgs(args))); /// Renders the template into exchange property . public static IRouteDefinition SetPropertyTemplate(this IRouteDefinition route, string key, string locator, MediaType mediaType, Action? args = null) => SetPropertyTemplate(route, key, TextSource.FromLocator(locator), mediaType, args); /// Renders the template into exchange property . public static IRouteDefinition SetPropertyTemplate(this IRouteDefinition route, string key, TextSource source, MediaType mediaType, Action? args = null) => Append(route, new PayloadTemplateDefinition(source, mediaType, TemplateTarget.Property, key, BuildArgs(args))); private static TemplateArgs? BuildArgs(Action? configure) { if (configure is null) return null; var args = new TemplateArgs(); configure(args); return args; } /// Appends the node to the current scope — the public tree API, identical to ProcessorDefinition.AddOutput. private static IRouteDefinition Append(IRouteDefinition route, PayloadTemplateDefinition definition) { ArgumentNullException.ThrowIfNull(route); definition.Parent = route; route.Outputs.Add(definition); return route; } } Path: redb-route/redb.Route.Templates/redb.Route.Templates.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/redb.Route.Templates.csproj ---- redb.Route.Templates Payload templates for redb.Route (WSO2 PayloadFactory / Camel templating analog): Scriban templates from files, embedded resources or inline text, media-type aware escaping (JSON / XML / text), named arguments from route expressions. esb;messaging;template;scriban;payload;redb README.md