Bundle: redb-route / redb.Route.JsonTransform (redb.Route.JsonTransform.txt), 9 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.JsonTransform/JsonTransformCompilationException.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.JsonTransform/JsonTransformCompilationException.cs
----
namespace redb.Route.JsonTransform;
///
/// A JSONata specification could not be read or parsed. Raised while the route is compiled, so it
/// surfaces from RouteContext.Start() with the specification's name and the engine's message
/// (which carries the position of the error).
///
public sealed class JsonTransformCompilationException : Exception
{
/// Creates the exception.
public JsonTransformCompilationException(string specificationName, string message, Exception? inner = null)
: base($"JSON transform '{specificationName}': {message}", inner)
{
SpecificationName = specificationName;
}
/// Specification name as given in the DSL / XML (file path, resource locator, or <inline>).
public string SpecificationName { get; }
}
Path: redb-route/redb.Route.JsonTransform/JsonTransformDefinition.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.JsonTransform/JsonTransformDefinition.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.JsonTransform;
///
/// The <transformJson> node: applies a JSONata specification to the JSON body. The
/// specification is compiled at route build — a missing file or a syntax error fails Start()
/// with the specification name — and cached by source. Declarative on purpose: the XML form reads
/// and .
///
public sealed class JsonTransformDefinition : ProcessorDefinition
{
/// Creates the node.
public JsonTransformDefinition(TextSource specification, JsonTransformOutput output = JsonTransformOutput.String)
{
Specification = specification ?? throw new ArgumentNullException(nameof(specification));
Output = output;
}
/// Where the JSONata text comes from.
public TextSource Specification { get; }
/// JSON text or a JsonNode tree.
public JsonTransformOutput Output { get; }
///
public override IProcessor CreateProcessor(IRouteContext context)
{
// Context services first (UseJsonTransform), then the DI container (AddJsonTransform), then defaults.
var options = context.GetService()
?? context.GetServiceProvider()?.GetService(typeof(JsonTransformOptions)) as JsonTransformOptions
?? new JsonTransformOptions();
// Same lookup as the template step and the validator: context resolver, then base directory.
// A miss stays a specification failure, not an IO one — the step promises one exception type.
TextSource specification;
try
{
specification = ResourceResolution.Locate(context, Specification, options.BaseDirectory, "JSONata specification");
}
catch (FileNotFoundException ex)
{
throw new JsonTransformCompilationException(Specification.Name, ex.Message, ex);
}
var compiled = JsonTransformEngine.Compile(specification, options);
return new JsonTransformProcessor(compiled, Output, options);
}
}
Path: redb-route/redb.Route.JsonTransform/JsonTransformEngine.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.JsonTransform/JsonTransformEngine.cs
----
using System.Collections;
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Nodes;
using Jsonata.Net.Native;
using Jsonata.Net.Native.Json;
using StjBridge = Jsonata.Net.Native.SystemTextJson.JsonataExtensions;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.JsonTransform;
/// A parsed JSONata specification plus the source it came from.
internal sealed record CompiledJsonTransform(TextSource Source, JsonataQuery Query);
///
/// Compiles JSONata specifications once (cache keyed by source identity) and applies them per message.
/// Input: the body as JSON text, bytes, a System.Text.Json tree, or a POCO (serialized camelCase).
/// Bindings: $headers and $properties — the same names the payload templates use.
///
internal static class JsonTransformEngine
{
private static readonly ConcurrentDictionary> Cache = new(StringComparer.Ordinal);
private static readonly JsonSerializerOptions PocoOptions = new(JsonSerializerDefaults.Web);
/// Drops every cached specification (tests).
public static void ClearCache() => Cache.Clear();
public static CompiledJsonTransform Compile(TextSource source, JsonTransformOptions options)
{
// Keyed by the resolved file (path, size, write time): the cache is process-wide, and a relative
// name alone would make two base directories share one specification.
var key = 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
throw;
}
}
private static CompiledJsonTransform Parse(TextSource source, JsonTransformOptions options)
{
string text;
try
{
text = source.Read(options.BaseDirectory);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
throw new JsonTransformCompilationException(source.Name, ex.Message, ex);
}
try
{
return new CompiledJsonTransform(source, new JsonataQuery(text));
}
catch (JsonataException ex)
{
throw new JsonTransformCompilationException(source.Name, ex.Message, ex);
}
}
/// Applies the specification to the exchange body; null when the result is undefined.
public static JToken? Run(CompiledJsonTransform compiled, IExchange exchange)
{
JToken input;
try
{
input = ToJToken(exchange.In.Body);
}
catch (Exception ex) when (ex is JsonataException or Jsonata.Net.Native.Json.JsonParseException or System.Text.Json.JsonException
or FormatException or ArgumentException or NotSupportedException)
{
throw new InvalidOperationException($"JSON transform '{compiled.Source.Name}': the body is not JSON ({ex.Message}).", ex);
}
var environment = new EvaluationEnvironment();
environment.BindValue("headers", StjBridge.FromObjectViaSystemTextJson(Sanitize(exchange.In.Headers), PocoOptions));
environment.BindValue("properties", StjBridge.FromObjectViaSystemTextJson(Sanitize(exchange.Properties), PocoOptions));
JToken result;
try
{
result = compiled.Query.Eval(input, environment);
}
catch (JsonataException ex)
{
throw new InvalidOperationException($"JSON transform '{compiled.Source.Name}' failed: {ex.Message}", ex);
}
return result.Type == JTokenType.Undefined ? null : result;
}
private static JToken ToJToken(object? body) => body switch
{
null => JToken.Parse("null"),
JToken token => token,
string text => JToken.Parse(text),
byte[] bytes => JToken.Parse(System.Text.Encoding.UTF8.GetString(bytes)),
JsonNode node => StjBridge.FromSystemTextJson(node),
JsonElement element => StjBridge.FromSystemTextJson(element),
JsonDocument document => StjBridge.FromSystemTextJson(document),
Stream stream => JToken.Parse(ReadStream(stream)),
_ => StjBridge.FromObjectViaSystemTextJson(body, PocoOptions),
};
/// Reads a stream body from its position and leaves it there (a later step may need it); the stream stays open — it belongs to the exchange.
private static string ReadStream(Stream stream)
{
var position = stream.CanSeek ? stream.Position : -1;
using var reader = new StreamReader(stream, System.Text.Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true);
var text = reader.ReadToEnd();
if (position >= 0) stream.Position = position;
return text;
}
///
/// Headers and properties may hold anything (streams, DI scopes under __redb_scope:*); the
/// binding keeps JSON-friendly values as they are, recurses into dictionaries and lists, and
/// falls back to ToString() for the rest.
///
private static Dictionary Sanitize(IEnumerable> pairs)
{
var result = new Dictionary(StringComparer.Ordinal);
foreach (var (key, value) in pairs)
{
if (key.StartsWith("__", StringComparison.Ordinal)) continue;
result[key] = SanitizeValue(value, depth: 0);
}
return result;
}
private static object? SanitizeValue(object? value, int depth) => value switch
{
null => null,
string or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal => value,
DateTime or DateTimeOffset or Guid or TimeSpan => value.ToString(),
JsonNode node => node,
_ when depth > 8 => value.ToString(),
IDictionary dictionary => dictionary.Cast()
.ToDictionary(e => e.Key?.ToString() ?? string.Empty, e => SanitizeValue(e.Value, depth + 1)),
IEnumerable list => list.Cast