Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add semantic mesh ranges and runtime project to solution

Yuechen Li0e5f30da74d7
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index e6341d5f..dff0d041 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -4,9 +4,11 @@ using Aetheris.Kernel.Core.Geometry;
namespace Aetheris.Kernel.Firmament.Assembly;
+public sealed record AssemblyDisplayMeshRange(int StartTriangle, int TriangleCount, string FaceId, string SemanticEntityId);
public sealed record AssemblyDisplayMeshDefinition(string Id, string Identity, double[] Positions, double[] Normals, int[] Indices,
- string MeshPipeline = "LegacyTessellator");
-public sealed record AssemblyDisplayMeshOccurrence(string Id, string Path, string? ParentId, string? DefinitionId, double[] Transform);
+ string MeshPipeline = "LegacyTessellator", IReadOnlyList<AssemblyDisplayMeshRange>? Ranges = null);
+public sealed record AssemblyDisplayMeshOccurrence(string Id, string Path, string? ParentId, string? DefinitionId, double[] Transform,
+ string? SemanticEntityId = null);
public sealed record AssemblyDisplayMeshDocument(string Schema, string Name, string Units,
IReadOnlyList<AssemblyDisplayMeshDefinition> Definitions, IReadOnlyList<AssemblyDisplayMeshOccurrence> Occurrences);
@@ -41,6 +43,7 @@ public static class AssemblyDisplayMeshExporter
if (!tessellation.IsSuccess || tessellation.Value.FacePatches.Count != body.Topology.Faces.Count())
throw new InvalidOperationException($"assembly-mesh-definition-failed:{identity}:" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ var ranges = new List<AssemblyDisplayMeshRange>();
foreach (var rawFace in tessellation.Value.FacePatches.OrderBy(p => p.FaceId.Value))
{
// SurfaceMeshIR already applies the B-rep face sense to both
@@ -50,14 +53,16 @@ public static class AssemblyDisplayMeshExporter
|| face.TriangleIndices.Count % 3 != 0 || face.TriangleIndices.Any(i => i < 0 || i >= face.Positions.Count))
throw new InvalidOperationException($"assembly-mesh-face-invalid:{identity}:{face.FaceId}:positions={face.Positions.Count};normals={face.Normals.Count};indices={face.TriangleIndices.Count};" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
var offset = positions.Count / 3;
+ var startTriangle = indices.Count / 3;
positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
indices.AddRange(face.TriangleIndices.Select(i => i + offset));
+ ranges.Add(new(startTriangle, face.TriangleIndices.Count / 3, $"face:{face.FaceId.Value}", ids[identity]));
}
if (positions.Concat(normals).Any(v => !double.IsFinite(v)))
throw new InvalidOperationException($"assembly-mesh-nonfinite:{identity}");
definitions.Add(new(ids[identity], identity, positions.ToArray(), normals.ToArray(), indices.ToArray(),
- tessellation.Value.MeshPipeline.ToString()));
+ tessellation.Value.MeshPipeline.ToString(), ranges));
}
var occurrences = compilation.Ir.Instances.OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
{
@@ -65,7 +70,7 @@ public static class AssemblyDisplayMeshExporter
? ids.GetValueOrDefault(instance.DefinitionIdentity) ?? throw new InvalidOperationException($"assembly-mesh-missing-definition:{instance.Path}") : null;
if (instance.ResolvedTransform is null || instance.ResolvedTransform.Matrix.Length != 16 || instance.ResolvedTransform.Matrix.Any(v => !double.IsFinite(v)))
throw new InvalidOperationException($"assembly-mesh-unresolved-transform:{instance.Path}");
- return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray());
+ return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray(), instance.StableId);
}).ToArray();
return new("aetheris/assembly-display-mesh/1", compilation.Ir.Name, "mm", definitions, occurrences);
}
diff --git a/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj
new file mode 100644
index 00000000..7a0911b5
--- /dev/null
+++ b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj
@@ -0,0 +1,17 @@
+<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
+ <WasmMainJSPath>bootstrap.js</WasmMainJSPath>
+ <InvariantGlobalization>true</InvariantGlobalization>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <JsonSerializerIsReflectionEnabledByDefault>true</JsonSerializerIsReflectionEnabledByDefault>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Description>Browser WebAssembly host for the public Aetheris CAD TypeScript SDK.</Description>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
new file mode 100644
index 00000000..6816df0d
--- /dev/null
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -0,0 +1,367 @@
+using System.Runtime.InteropServices.JavaScript;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Web.Runtime;
+
+public static partial class Program
+{
+ private const string ContractVersion = "aetheris/web-editor-contract/1";
+ private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
+ private static readonly Dictionary<string, WebModelSession> Sessions = new(StringComparer.Ordinal);
+ private static int _nextSession;
+
+ public static void Main() { }
+
+ [JSExport]
+ public static string Invoke(string requestJson)
+ {
+ try
+ {
+ var request = JsonSerializer.Deserialize<WebRequest>(requestJson, JsonOptions)
+ ?? throw new WebRuntimeException("invalid-request", "The runtime request was empty.");
+ object result = request.Operation switch
+ {
+ "info" => Info(),
+ "compile" => Compile(request),
+ "snapshot" => Session(request).Snapshot,
+ "setProperty" => SetProperty(request),
+ "setSource" => SetSource(request),
+ "rebuild" => Rebuild(request),
+ "exportStep" => ExportStep(request),
+ "disposeSession" => DisposeSession(request),
+ "disposeRuntime" => DisposeRuntime(),
+ _ => throw new WebRuntimeException("unknown-operation", $"Unknown runtime operation '{request.Operation}'.")
+ };
+ return JsonSerializer.Serialize(new { ok = true, result }, JsonOptions);
+ }
+ catch (WebRuntimeException exception)
+ {
+ return JsonSerializer.Serialize(new { ok = false, error = new { code = exception.Code, message = exception.Message } }, JsonOptions);
+ }
+ catch (Exception exception)
+ {
+ return JsonSerializer.Serialize(new { ok = false, error = new { code = "internal-error", message = "Aetheris could not complete the operation.", details = exception.Message } }, JsonOptions);
+ }
+ }
+
+ private static object Info() => new
+ {
+ packageVersion = "2.0.0-preview.3",
+ runtimeVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "2.0.0",
+ contractVersion = ContractVersion,
+ language = "Firmament",
+ capabilities = new
+ {
+ compile = true, solidModeling = true, assembly = true, displayMesh = true,
+ propertyInspection = true, parameterRebuild = true, stepExport = true,
+ sheetMetal = false, fea = false, externalStepImport = false, forgeSubprocess = false,
+ cancellation = false, worker = false
+ }
+ };
+
+ private static object Compile(WebRequest request)
+ {
+ if (string.IsNullOrWhiteSpace(request.Source))
+ throw new WebRuntimeException("source-required", "compile requires Firmament source text.");
+ var id = $"model-{++_nextSession}";
+ var session = new WebModelSession(id, request.Source, request.SourceName ?? "model.firmament");
+ var result = session.Rebuild();
+ if (result.Success) Sessions[id] = session;
+ return result;
+ }
+
+ private static object SetProperty(WebRequest request)
+ {
+ var session = Session(request);
+ if (string.IsNullOrWhiteSpace(request.PropertyId) || request.Value is null)
+ throw new WebRuntimeException("property-value-required", "setProperty requires propertyId and a typed value.");
+ session.SetProperty(request.PropertyId, request.Value);
+ return new { accepted = true, revision = session.Revision, dirty = true };
+ }
+
+ private static object SetSource(WebRequest request)
+ {
+ var session = Session(request);
+ if (request.Source is null) throw new WebRuntimeException("source-required", "setSource requires source text.");
+ session.SetSource(request.Source, request.SourceName);
+ return new { accepted = true, revision = session.Revision, dirty = true };
+ }
+
+ private static object Rebuild(WebRequest request) => Session(request).Rebuild();
+
+ private static object ExportStep(WebRequest request)
+ {
+ var session = Session(request);
+ if (session.StepText is null) throw new WebRuntimeException("model-not-built", "The model has no valid STEP artifact.");
+ return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(session.StepText)), revision = session.Revision };
+ }
+
+ private static object DisposeSession(WebRequest request)
+ {
+ if (request.SessionId is not null) Sessions.Remove(request.SessionId);
+ return new { disposed = true };
+ }
+
+ private static object DisposeRuntime()
+ {
+ Sessions.Clear();
+ return new { disposed = true };
+ }
+
+ private static WebModelSession Session(WebRequest request)
+ => request.SessionId is not null && Sessions.TryGetValue(request.SessionId, out var session)
+ ? session : throw new WebRuntimeException("session-not-found", "The model session was disposed or does not exist.");
+
+ private sealed record WebRequest(string Operation, string? SessionId = null, string? Source = null,
+ string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null);
+
+ private sealed class WebRuntimeException(string code, string message) : Exception(message)
+ {
+ public string Code { get; } = code;
+ }
+
+ private sealed class WebModelSession(string id, string source, string sourceName)
+ {
+ private string _source = source;
+ private string _sourceName = sourceName;
+ private IReadOnlyList<WebProperty> _properties = [];
+ private readonly Dictionary<string, WebPropertyValue> _overrides = new(StringComparer.Ordinal);
+ private object? _lastSnapshot;
+ public string Id { get; } = id;
+ public string Name => Path.GetFileNameWithoutExtension(_sourceName);
+ public int Revision { get; private set; }
+ public string? StepText { get; private set; }
+ public object Snapshot => _lastSnapshot ?? throw new WebRuntimeException("model-not-built", "The model has no valid snapshot.");
+
+ public void SetSource(string nextSource, string? nextSourceName)
+ {
+ _source = nextSource;
+ if (!string.IsNullOrWhiteSpace(nextSourceName)) _sourceName = nextSourceName;
+ _overrides.Clear();
+ }
+
+ public void SetProperty(string propertyId, WebPropertyValue value)
+ {
+ var property = _properties.SingleOrDefault(candidate => candidate.Id == propertyId)
+ ?? throw new WebRuntimeException("property-not-found", $"Editable property '{propertyId}' was not found.");
+ if (!property.Writable) throw new WebRuntimeException("property-readonly", $"Property '{propertyId}' is read-only.");
+ if (!double.IsFinite(value.Value)) throw new WebRuntimeException("property-value-invalid", "Property values must be finite.");
+ if (!string.Equals(value.Unit, property.Unit, StringComparison.Ordinal))
+ throw new WebRuntimeException("property-unit-mismatch", $"Property '{property.Name}' requires unit '{property.Unit}'.");
+ if (property.Type == "Length" && value.Value <= 0)
+ throw new WebRuntimeException("property-out-of-range", $"Property '{property.Name}' must be greater than zero.");
+ _overrides[propertyId] = value;
+ }
+
+ public WebBuildResult Rebuild()
+ {
+ var sourceProperties = ParameterInspector.Inspect(Id, _sourceName, _source);
+ var effective = ApplyOverrides(_source, sourceProperties, _overrides);
+ var nextProperties = sourceProperties;
+ foreach (var (propertyId, value) in _overrides)
+ {
+ var index = nextProperties.FindIndex(property => property.Id == propertyId);
+ if (index >= 0) nextProperties[index] = nextProperties[index] with { Value = value.Value };
+ }
+ var assembly = Regex.IsMatch(effective, @"(?m)^\s*Assembly\s+", RegexOptions.CultureInvariant);
+ var compiled = assembly ? CompileAssembly(effective, nextProperties) : CompilePart(effective, nextProperties);
+ if (!compiled.Success)
+ return compiled with { Revision = Revision, RetainedPreviousGeometry = _lastSnapshot is not null };
+
+ Revision++;
+ _properties = nextProperties;
+ StepText = compiled.StepText;
+ var changes = new
+ {
+ changedEntityIds = compiled.EntityIds,
+ addedEntityIds = Revision == 1 ? compiled.EntityIds : Array.Empty<string>(),
+ removedEntityIds = Array.Empty<string>(),
+ meshChanged = true,
+ diagnosticsChanged = false
+ };
+ _lastSnapshot = new
+ {
+ id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,
+ tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,
+ diagnostics = compiled.Diagnostics, changes, timings = compiled.Timings
+ };
+ return compiled with { Revision = Revision, Model = _lastSnapshot, Changes = changes, StepText = null };
+ }
+
+ private WebBuildResult CompilePart(string effective, List<WebProperty> properties)
+ {
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var build = FirmamentBuildAndExport.CompileSource(effective);
+ var compileMs = watch.Elapsed.TotalMilliseconds;
+ if (!build.IsSuccess || build.Value is null)
+ return WebBuildResult.Failed(Diagnostics(build.Diagnostics, _sourceName), compileMs);
+ var step = build.Value.StepText;
+ var import = Step242Importer.ImportBody(step);
+ if (!import.IsSuccess || import.Value is null)
+ return WebBuildResult.Failed(Diagnostics(import.Diagnostics, _sourceName), compileMs);
+ watch.Restart();
+ var definitionId = "definition:" + Sha(step)[..16].ToLowerInvariant();
+ var entityId = string.IsNullOrWhiteSpace(build.Value.ExportedFeatureId) ? Id + ":body" : build.Value.ExportedFeatureId;
+ var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, import.Value);
+ var meshMs = watch.Elapsed.TotalMilliseconds;
+ var featureNodes = (build.Value.EngineeringFeatures ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true, null)).ToArray();
+ var body = new WebTreeNode(entityId, build.Value.ExportedBodyCategory, Name, Id, featureNodes.Select(item => item.Id).ToArray(), true, SourceRef(_sourceName, 0, effective.Length));
+ var root = new WebTreeNode(Id, "Model", Name, null, [body.Id], true, SourceRef(_sourceName, 0, effective.Length));
+ var tree = new { rootId = root.Id, nodes = new[] { root, body }.Concat(featureNodes).ToArray() };
+ return WebBuildResult.Passed(step, tree, mesh, [Id, entityId, .. featureNodes.Select(item => item.Id)], compileMs, meshMs);
+ }
+
+ private WebBuildResult CompileAssembly(string effective, List<WebProperty> properties)
+ {
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var compilation = new AssemblyM1Pipeline().Compile(effective, _sourceName);
+ var compileMs = watch.Elapsed.TotalMilliseconds;
+ if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
+ return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", d.Code, d.Message, SourceRef(_sourceName, 0, effective.Length))).ToArray(), compileMs);
+ var step = AssemblyIrAp242Exporter.Export(compilation);
+ if (!step.IsSuccess) return WebBuildResult.Failed(Diagnostics(step.Diagnostics, _sourceName), compileMs);
+ watch.Restart();
+ var mesh = AssemblyDisplayMeshExporter.Export(compilation);
+ var meshMs = watch.Elapsed.TotalMilliseconds;
+ var nodes = compilation.Ir.Instances.OrderBy(instance => instance.Path.Segments.Count).Select(instance =>
+ new WebTreeNode(instance.StableId, instance.Kind.ToString(), instance.Path.Segments.Last(), instance.ParentStableId, instance.ChildrenStableIds, true, null)).ToArray();
+ var children = nodes.Where(node => node.ParentId == compilation.Ir.RootInstanceStableId).Select(node => node.Id).ToArray();
+ var root = new WebTreeNode(compilation.Ir.RootInstanceStableId, "Assembly", compilation.Ir.Name, null, children, true, SourceRef(_sourceName, 0, effective.Length));
+ var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };
+ return WebBuildResult.Passed(step.Value, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs);
+ }
+ }
+
+ private static string ApplyOverrides(string source, IReadOnlyList<WebProperty> properties, IReadOnlyDictionary<string, WebPropertyValue> overrides)
+ {
+ var edits = properties.Where(property => overrides.ContainsKey(property.Id)).OrderByDescending(property => property.Start).ToArray();
+ var result = source;
+ foreach (var property in edits)
+ {
+ var value = overrides[property.Id];
+ result = result[..property.Start] + value.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + value.Unit + result[(property.Start + property.Length)..];
+ }
+ return result;
+ }
+
+ private static IReadOnlyList<WebDiagnostic> Diagnostics(IEnumerable<KernelDiagnostic> diagnostics, string source)
+ => diagnostics.Select(diagnostic => new WebDiagnostic(
+ diagnostic.Severity switch { KernelDiagnosticSeverity.Error => "error", KernelDiagnosticSeverity.Warning => "warning", _ => "info" },
+ diagnostic.Code.ToString(), diagnostic.Message, SourceRef(source, 0, 0), diagnostic.Source)).ToArray();
+
+ private static WebSourceRef SourceRef(string source, int start, int length) => new(source, 1, 1, start, length);
+ private static string Sha(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
+}
+
+internal static class ParameterInspector
+{
+ private static readonly Regex Assignment = new(@"(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<literal>-?(?<number>\d+(?:\.\d+)?)\s*(?<unit>mm|cm|m|deg|rad))(?=\s*[,>\r\n])", RegexOptions.CultureInvariant);
+ private static readonly Regex BoxSize = new(@"\bSize\s*:\s*\[\s*(?<width>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*,\s*(?<height>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*,\s*(?<thickness>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*\]", RegexOptions.CultureInvariant);
+ private static readonly Regex HoleDiameter = new(@"\bDiameter\s*:\s*(?<diameter>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))", RegexOptions.CultureInvariant);
+
+ public static List<WebProperty> Inspect(string modelId, string sourceName, string source)
+ {
+ var specialization = Regex.Matches(source, @"=\s*[A-Za-z_][A-Za-z0-9_]*\s*<", RegexOptions.CultureInvariant).LastOrDefault();
+ if (specialization is null) return InspectDirectModel(modelId, sourceName, source);
+ var start = specialization.Index + specialization.Length;
+ var depth = 1; var end = start;
+ for (; end < source.Length && depth > 0; end++)
+ {
+ if (source[end] == '<') depth++;
+ else if (source[end] == '>') depth--;
+ }
+ if (depth != 0) return [];
+ var segment = source[start..(end - 1)];
+ return Assignment.Matches(segment).Select(match =>
+ {
+ var unit = match.Groups["unit"].Value;
+ var number = double.Parse(match.Groups["number"].Value, System.Globalization.CultureInfo.InvariantCulture);
+ var literal = match.Groups["literal"];
+ var absolute = start + literal.Index;
+ var (line, column) = LineColumn(source, absolute);
+ var name = match.Groups["name"].Value;
+ return new WebProperty($"{modelId}.parameter.{name}", modelId, name, unit is "deg" or "rad" ? "Angle" : "Length", unit, number, true, absolute, literal.Length, new(sourceName, line, column, absolute, literal.Length));
+ }).GroupBy(property => property.Name, StringComparer.Ordinal).Select(group => group.Last()).OrderBy(property => property.Name, StringComparer.Ordinal).ToList();
+ }
+
+ private static List<WebProperty> InspectDirectModel(string modelId, string sourceName, string source)
+ {
+ var result = new List<WebProperty>();
+ var size = BoxSize.Match(source);
+ if (size.Success)
+ {
+ Add("Width", size.Groups["width"]);
+ Add("Height", size.Groups["height"]);
+ Add("Thickness", size.Groups["thickness"]);
+ }
+ var diameter = HoleDiameter.Match(source);
+ if (diameter.Success) Add("HoleDiameter", diameter.Groups["diameter"]);
+ return result.OrderBy(property => property.Name, StringComparer.Ordinal).ToList();
+
+ void Add(string name, Group literal)
+ {
+ var parsed = Regex.Match(literal.Value, @"(?<number>-?\d+(?:\.\d+)?)\s*(?<unit>mm|cm|m)", RegexOptions.CultureInvariant);
+ var (line, column) = LineColumn(source, literal.Index);
+ result.Add(new($"{modelId}.parameter.{name}", modelId, name, "Length", parsed.Groups["unit"].Value,
+ double.Parse(parsed.Groups["number"].Value, System.Globalization.CultureInfo.InvariantCulture), true, literal.Index, literal.Length,
+ new(sourceName, line, column, literal.Index, literal.Length)));
+ }
+ }
+
+ private static (int Line, int Column) LineColumn(string source, int offset)
+ {
+ var line = 1; var column = 1;
+ for (var i = 0; i < offset; i++) { if (source[i] == '\n') { line++; column = 1; } else column++; }
+ return (line, column);
+ }
+}
+
+internal static class WebMeshBuilder
+{
+ public static object Build(string name, string definitionId, string entityId, BrepBody body)
+ {
+ // Browser WASM has no blocking monitor wait. Use the existing synchronous
+ // tessellator authority; the Worker transport supplies UI responsiveness.
+ var tessellation = BrepDisplayTessellator.Tessellate(body, new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64));
+ if (!tessellation.IsSuccess) throw new InvalidOperationException(string.Join("; ", tessellation.Diagnostics.Select(item => item.Message)));
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>(); var ranges = new List<object>();
+ foreach (var raw in tessellation.Value.FacePatches.OrderBy(face => face.FaceId.Value))
+ {
+ var face = DisplayMeshOrientation.Orient(body, raw); var vertexOffset = positions.Count / 3; var triangleStart = indices.Count / 3;
+ positions.AddRange(face.Positions.SelectMany(point => new[] { point.X, point.Y, point.Z }));
+ normals.AddRange(face.Normals.SelectMany(normal => new[] { normal.X, normal.Y, normal.Z }));
+ indices.AddRange(face.TriangleIndices.Select(index => index + vertexOffset));
+ ranges.Add(new { startTriangle = triangleStart, triangleCount = face.TriangleIndices.Count / 3, faceId = $"face:{face.FaceId.Value}", semanticEntityId = entityId });
+ }
+ return new
+ {
+ schema = "aetheris/display-mesh/1",
+ name,
+ units = "mm",
+ definitions = new[] { new { id = definitionId, identity = entityId, positions = positions.ToArray(), normals = normals.ToArray(), indices = indices.ToArray(), ranges } },
+ occurrences = new[] { new { id = entityId + ":occurrence", path = name, parentId = (string?)null, definitionId, semanticEntityId = entityId, transform = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 } } }
+ };
+ }
+}
+
+internal sealed record WebPropertyValue(double Value, string Unit);
+internal sealed record WebSourceRef(string Source, int Line, int Column, int Start, int Length);
+internal sealed record WebProperty(string Id, string OwnerEntityId, string Name, string Type, string Unit, double Value, bool Writable, int Start, int Length, WebSourceRef Source);
+internal sealed record WebTreeNode(string Id, string Kind, string Name, string? ParentId, IReadOnlyList<string> Children, bool Visible, WebSourceRef? Source);
+internal sealed record WebDiagnostic(string Severity, string Code, string Message, WebSourceRef? Source = null, string? Details = null);
+internal sealed record WebBuildResult(bool Success, int Revision, object? Model, IReadOnlyList<WebDiagnostic> Diagnostics, bool RetainedPreviousGeometry,
+ object? Tree = null, object? Mesh = null, IReadOnlyList<string>? EntityIds = null, object? Timings = null, object? Changes = null, string? StepText = null)
+{
+ public static WebBuildResult Failed(IReadOnlyList<WebDiagnostic> diagnostics, double compileMs) => new(false, 0, null, diagnostics, false, Timings: new { compileMilliseconds = compileMs });
+ public static WebBuildResult Passed(string step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step);
+}
diff --git a/Aetheris.Web.Runtime/bootstrap.js b/Aetheris.Web.Runtime/bootstrap.js
new file mode 100644
index 00000000..c36d0d3e
--- /dev/null
+++ b/Aetheris.Web.Runtime/bootstrap.js
@@ -0,0 +1,3 @@
+// The npm facade starts the runtime explicitly. This file is the SDK build entrypoint.
+import { dotnet } from './_framework/dotnet.js';
+await dotnet.create().then(runtime => runtime.runMain());
diff --git a/Aetheris.Web.Runtime/sdk/.gitignore b/Aetheris.Web.Runtime/sdk/.gitignore
new file mode 100644
index 00000000..6a34499b
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/.gitignore
@@ -0,0 +1,2 @@
+/dist/
+/*.tgz
diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.md
new file mode 100644
index 00000000..4937e67c
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/README.md
@@ -0,0 +1,15 @@
+# @aetheris/cad
+
+Browser-embeddable Aetheris CAD. The package includes the .NET WebAssembly runtime and uses the same Firmament, B-rep, tessellation, assembly, and AP242 authorities as native Aetheris.
+
+```js
+import { Aetheris } from '@aetheris/cad';
+const cad = await Aetheris.create();
+const { model, diagnostics } = await cad.compile(source, { sourceName: 'bracket.firmament' });
+```
+
+Vite projects add `aetherisCad()` from `@aetheris/cad/vite` to `vite.config.js`. The plugin serves the runtime during development and copies it into production builds.
+
+X1 runs on the page thread. `worker: true` fails with the typed `worker-unavailable` error; a qualified Worker transport is deferred rather than silently changing behavior.
+
+The preview package is AGPL-3.0-only. Contact the Aetheris project for commercial licensing; this statement is package metadata, not legal advice.
diff --git a/Aetheris.Web.Runtime/sdk/package.json b/Aetheris.Web.Runtime/sdk/package.json
new file mode 100644
index 00000000..ce37e911
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@aetheris/cad",
+ "version": "2.0.0-preview.3",
+ "description": "Browser-embeddable Aetheris semantic CAD runtime",
+ "type": "module",
+ "license": "AGPL-3.0-only",
+ "sideEffects": false,
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ },
+ "./vite": {
+ "types": "./dist/vite.d.ts",
+ "import": "./dist/vite.js"
+ }
+ },
+ "files": ["dist", "README.md"],
+ "scripts": {
+ "build": "node scripts/build.mjs",
+ "pack:local": "npm run build && npm pack"
+ },
+ "engines": { "node": ">=20" },
+ "keywords": ["cad", "wasm", "firmament", "step", "ap242"]
+}
diff --git a/Aetheris.Web.Runtime/sdk/scripts/build.mjs b/Aetheris.Web.Runtime/sdk/scripts/build.mjs
new file mode 100644
index 00000000..84213c4a
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/scripts/build.mjs
@@ -0,0 +1,23 @@
+import { cp, mkdir, rm, copyFile } from 'node:fs/promises';
+import { spawnSync } from 'node:child_process';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const sdk = resolve(here, '..');
+const runtime = resolve(sdk, '..');
+const repo = resolve(runtime, '..');
+const result = spawnSync('dotnet', ['build', join(runtime, 'Aetheris.Web.Runtime.csproj'), '-c', 'Release', '--nologo'], { cwd: repo, stdio: 'inherit' });
+if (result.status !== 0) process.exit(result.status ?? 1);
+const app = join(runtime, 'bin', 'Release', 'net10.0', 'wwwroot');
+const dist = join(sdk, 'dist');
+await rm(dist, { recursive: true, force: true });
+await mkdir(dist, { recursive: true });
+await cp(join(app, '_framework'), join(dist, 'runtime', '_framework'), { recursive: true });
+await copyFile(join(sdk, 'src', 'index.js'), join(dist, 'index.js'));
+await copyFile(join(sdk, 'src', 'worker.js'), join(dist, 'worker.js'));
+await copyFile(join(sdk, 'src', 'runtime.js'), join(dist, 'runtime.js'));
+await copyFile(join(sdk, 'src', 'index.d.ts'), join(dist, 'index.d.ts'));
+await copyFile(join(sdk, 'src', 'vite.js'), join(dist, 'vite.js'));
+await copyFile(join(sdk, 'src', 'vite.d.ts'), join(dist, 'vite.d.ts'));
+console.log(`Built @aetheris/cad at ${dist}`);
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
new file mode 100644
index 00000000..9255de02
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -0,0 +1,42 @@
+export type DiagnosticSeverity = 'info' | 'warning' | 'error';
+export type Unit = 'mm' | 'cm' | 'm' | 'deg' | 'rad';
+export interface SourceReference { readonly source: string; readonly line: number; readonly column: number; readonly start: number; readonly length: number }
+export interface Diagnostic { readonly severity: DiagnosticSeverity; readonly code: string; readonly message: string; readonly source?: SourceReference; readonly details?: string }
+export interface UnitValue { readonly value: number; readonly unit: Unit }
+export interface EditableProperty { readonly id: string; readonly ownerEntityId: string; readonly name: string; readonly type: 'Length' | 'Angle' | 'Integer' | 'Number' | 'Boolean' | 'Enum'; readonly unit: Unit; readonly value: number; readonly writable: boolean; readonly source: SourceReference }
+export interface ModelTreeNode { readonly id: string; readonly kind: string; readonly name: string; readonly parentId?: string; readonly children: readonly string[]; readonly visible: boolean; readonly source?: SourceReference }
+export interface ModelTree { readonly rootId: string; readonly nodes: readonly ModelTreeNode[] }
+export interface MeshRange { readonly startTriangle: number; readonly triangleCount: number; readonly faceId: string; readonly semanticEntityId: string }
+export interface DisplayMeshDefinition { readonly id: string; readonly identity: string; readonly positions: Float64Array; readonly normals: Float64Array; readonly indices: Uint32Array; readonly ranges: readonly MeshRange[] }
+export interface DisplayMeshOccurrence { readonly id: string; readonly path: string; readonly parentId?: string; readonly definitionId?: string; readonly semanticEntityId: string; readonly transform: readonly number[] }
+export interface DisplayMesh { readonly schema: 'aetheris/display-mesh/1' | 'aetheris/assembly-display-mesh/1'; readonly name: string; readonly units: 'mm'; readonly definitions: readonly DisplayMeshDefinition[]; readonly occurrences: readonly DisplayMeshOccurrence[] }
+export interface ChangeSet { readonly changedEntityIds: readonly string[]; readonly addedEntityIds: readonly string[]; readonly removedEntityIds: readonly string[]; readonly meshChanged: boolean; readonly diagnosticsChanged: boolean }
+export interface RebuildResult { readonly success: boolean; readonly revision: number; readonly diagnostics: readonly Diagnostic[]; readonly retainedPreviousGeometry: boolean; readonly changes?: ChangeSet }
+export interface RuntimeCapabilities { readonly compile: boolean; readonly solidModeling: boolean; readonly assembly: boolean; readonly displayMesh: boolean; readonly propertyInspection: boolean; readonly parameterRebuild: boolean; readonly stepExport: boolean; readonly sheetMetal: boolean; readonly fea: boolean; readonly externalStepImport: boolean; readonly forgeSubprocess: boolean; readonly cancellation: boolean; readonly worker: boolean }
+export interface RuntimeInfo { readonly packageVersion: string; readonly runtimeVersion: string; readonly contractVersion: 'aetheris/web-editor-contract/1'; readonly language: 'Firmament'; readonly capabilities: RuntimeCapabilities }
+export interface OperationOptions { readonly signal?: AbortSignal }
+export interface CompileOptions extends OperationOptions { readonly sourceName?: string }
+export interface AetherisOptions { readonly worker?: boolean; readonly wasmUrl?: string | URL; readonly diagnostics?: (diagnostics: readonly Diagnostic[]) => void }
+export class AetherisError extends Error { readonly code: string; readonly details?: string }
+export class Aetheris {
+ static create(options?: AetherisOptions): Promise<Aetheris>;
+ readonly runtimeInfo: RuntimeInfo;
+ info(): Promise<RuntimeInfo>;
+ capabilities(): Promise<RuntimeCapabilities>;
+ compile(source: string, options?: CompileOptions): Promise<{ model: ModelSession | null; diagnostics: readonly Diagnostic[] }>;
+ dispose(): Promise<void>;
+}
+export class ModelSession {
+ readonly id: string; readonly name: string; readonly revision: number; readonly source: string; readonly sourceName: string;
+ readonly tree: ModelTree; readonly properties: readonly EditableProperty[]; readonly mesh: DisplayMesh; readonly diagnostics: readonly Diagnostic[]; readonly changes: ChangeSet;
+ entity(id: string): ModelTreeNode | undefined;
+ property(id: string): EditableProperty | undefined;
+ setProperty(propertyId: string, value: UnitValue, options?: OperationOptions): Promise<RebuildResult>;
+ setSource(source: string, options?: CompileOptions): Promise<RebuildResult>;
+ rebuild(options?: OperationOptions): Promise<RebuildResult>;
+ resolveSelection(definitionId: string, triangleIndex: number, occurrenceId?: string): { semanticEntityId: string; faceId: string; occurrenceId: string; definitionId: string } | null;
+ selectionForEntity(entityId: string): { occurrenceIds: readonly string[]; ranges: readonly ({ definitionId: string } & MeshRange)[] };
+ exportSTEP(options?: OperationOptions): Promise<Uint8Array>;
+ exportSTEPBlob(options?: OperationOptions): Promise<Blob>;
+ dispose(): Promise<void>;
+}
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
new file mode 100644
index 00000000..72149ab6
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -0,0 +1,112 @@
+import { createRuntime } from './runtime.js';
+
+const defaultRuntimeBase = typeof __AETHERIS_RUNTIME_BASE__ !== 'undefined'
+ ? new URL(__AETHERIS_RUNTIME_BASE__, globalThis.location?.href)
+ : new URL('./runtime/', import.meta.url);
+
+export class AetherisError extends Error {
+ constructor(code, message, details) { super(message); this.name = 'AetherisError'; this.code = code; this.details = details; }
+}
+
+class DirectTransport {
+ constructor(runtimeBase) { this.runtimeBase = runtimeBase; this.queue = Promise.resolve(); }
+ async request(request) {
+ this.invoke ??= await createRuntime(this.runtimeBase);
+ const operation = this.queue.then(() => this.invoke(request));
+ this.queue = operation.catch(() => undefined);
+ return operation;
+ }
+ dispose() { return this.request({ operation: 'disposeRuntime' }); }
+}
+
+class WorkerTransport {
+ constructor(runtimeBase) {
+ this.runtimeBase = runtimeBase;
+ this.worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module', name: 'Aetheris CAD' });
+ this.pending = new Map(); this.nextId = 0;
+ this.worker.onmessage = ({ data }) => {
+ const pending = this.pending.get(data.id); if (!pending) return;
+ this.pending.delete(data.id);
+ data.error ? pending.reject(new AetherisError(data.error.code, data.error.message, data.error.details)) : pending.resolve(data.result);
+ };
+ this.worker.onerror = event => {
+ const error = new AetherisError('worker-error', event.message || 'The Aetheris worker failed to start.');
+ for (const pending of this.pending.values()) pending.reject(error);
+ this.pending.clear();
+ };
+ }
+ request(request) {
+ return new Promise((resolve, reject) => {
+ const id = ++this.nextId; this.pending.set(id, { resolve, reject });
+ this.worker.postMessage({ id, request, runtimeBase: this.runtimeBase?.href });
+ });
+ }
+ async dispose() { try { await this.request({ operation: 'disposeRuntime' }); } finally { this.worker.terminate(); } }
+}
+
+export class Aetheris {
+ static async create(options = {}) {
+ if (options.worker === true) throw new AetherisError('worker-unavailable', 'Worker-backed execution is not qualified in Web SDK X1. Use the default in-page runtime.');
+ const runtimeBase = options.wasmUrl ? new URL(options.wasmUrl, globalThis.location?.href) : defaultRuntimeBase;
+ const transport = new DirectTransport(runtimeBase);
+ const cad = new Aetheris(transport, options.diagnostics);
+ cad.runtimeInfo = await cad.info();
+ return cad;
+ }
+ constructor(transport, diagnostics) { this.transport = transport; this.diagnostics = diagnostics; }
+ info() { return this.transport.request({ operation: 'info' }); }
+ async capabilities() { return (await this.info()).capabilities; }
+ async compile(source, options = {}) {
+ throwIfAborted(options.signal);
+ const result = await this.transport.request({ operation: 'compile', source, sourceName: options.sourceName });
+ this.diagnostics?.(result.diagnostics);
+ return { model: result.success ? new ModelSession(this.transport, result.model) : null, diagnostics: result.diagnostics };
+ }
+ dispose() { return this.transport.dispose(); }
+}
+
+export class ModelSession {
+ constructor(transport, snapshot) { this.transport = transport; this.apply(snapshot); this.queue = Promise.resolve(); }
+ apply(snapshot) { Object.assign(this, snapshot); }
+ entity(id) { return this.tree.nodes.find(node => node.id === id); }
+ property(id) { return this.properties.find(property => property.id === id); }
+ async setProperty(propertyId, value, options = {}) {
+ return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setProperty', sessionId: this.id, propertyId, value }); return this.rebuild(options); });
+ }
+ async setSource(source, options = {}) {
+ return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setSource', sessionId: this.id, source, sourceName: options.sourceName }); return this.rebuild(options); });
+ }
+ async rebuild(options = {}) {
+ throwIfAborted(options.signal);
+ const result = await this.transport.request({ operation: 'rebuild', sessionId: this.id });
+ if (result.success) this.apply(result.model);
+ return result;
+ }
+ resolveSelection(definitionId, triangleIndex, occurrenceId) {
+ const definition = this.mesh.definitions.find(item => item.id === definitionId);
+ const occurrence = occurrenceId ? this.mesh.occurrences.find(item => item.id === occurrenceId) : this.mesh.occurrences.find(item => item.definitionId === definitionId);
+ const range = definition?.ranges?.find(item => triangleIndex >= item.startTriangle && triangleIndex < item.startTriangle + item.triangleCount);
+ return range && occurrence ? { semanticEntityId: occurrence.semanticEntityId ?? range.semanticEntityId, faceId: range.faceId, occurrenceId: occurrence.id, definitionId } : null;
+ }
+ selectionForEntity(entityId) {
+ const occurrences = this.mesh.occurrences.filter(item => item.semanticEntityId === entityId || item.definitionId === entityId);
+ const occurrenceIds = occurrences.map(item => item.id);
+ const definitionIds = new Set(occurrences.map(item => item.definitionId).filter(Boolean));
+ const ranges = this.mesh.definitions.flatMap(definition => (definition.ranges ?? []).filter(range => range.semanticEntityId === entityId || definitionIds.has(definition.id)).map(range => ({ definitionId: definition.id, ...range })));
+ return { occurrenceIds, ranges };
+ }
+ async exportSTEP(options = {}) {
+ throwIfAborted(options.signal);
+ const result = await this.transport.request({ operation: 'exportStep', sessionId: this.id });
+ const binary = atob(result.base64); const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+ }
+ async exportSTEPBlob(options = {}) { return new Blob([await this.exportSTEP(options)], { type: 'model/step' }); }
+ async dispose() { await this.transport.request({ operation: 'disposeSession', sessionId: this.id }); }
+ serial(operation) { const result = this.queue.then(operation); this.queue = result.catch(() => undefined); return result; }
+}
+
+function throwIfAborted(signal) {
+ if (signal?.aborted) throw new DOMException('The Aetheris operation was aborted before execution.', 'AbortError');
+}
diff --git a/Aetheris.Web.Runtime/sdk/src/runtime.js b/Aetheris.Web.Runtime/sdk/src/runtime.js
new file mode 100644
index 00000000..d7233517
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/runtime.js
@@ -0,0 +1,34 @@
+export function normalizeMesh(value) {
+ const mesh = value?.model?.mesh ?? value?.mesh;
+ if (!mesh?.definitions) return value;
+ for (const definition of mesh.definitions) {
+ if (!(definition.positions instanceof Float64Array)) definition.positions = Float64Array.from(definition.positions);
+ if (!(definition.normals instanceof Float64Array)) definition.normals = Float64Array.from(definition.normals);
+ if (!(definition.indices instanceof Uint32Array)) definition.indices = Uint32Array.from(definition.indices);
+ }
+ return value;
+}
+
+export function transferables(value) {
+ const result = [];
+ const mesh = value?.model?.mesh ?? value?.mesh;
+ for (const definition of mesh?.definitions ?? []) result.push(definition.positions.buffer, definition.normals.buffer, definition.indices.buffer);
+ return result;
+}
+
+export async function createRuntime(runtimeBase = new URL('./runtime/', import.meta.url)) {
+ const dotnetUrl = new URL('_framework/dotnet.js', runtimeBase);
+ const { dotnet } = await import(dotnetUrl.href);
+ const runtime = await dotnet.withApplicationArguments().create();
+ const exports = await runtime.getAssemblyExports('Aetheris.Web.Runtime.dll');
+ const invoke = exports.Aetheris.Web.Runtime.Program.Invoke;
+ return request => {
+ const envelope = JSON.parse(invoke(JSON.stringify(request)));
+ if (!envelope.ok) {
+ const error = new Error(envelope.error.message);
+ error.name = 'AetherisError'; error.code = envelope.error.code; error.details = envelope.error.details;
+ throw error;
+ }
+ return normalizeMesh(envelope.result);
+ };
+}
diff --git a/Aetheris.Web.Runtime/sdk/src/vite.d.ts b/Aetheris.Web.Runtime/sdk/src/vite.d.ts
new file mode 100644
index 00000000..ec9dda7a
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/vite.d.ts
@@ -0,0 +1,3 @@
+import type { Plugin } from 'vite';
+export declare function aetherisCad(): Plugin;
+export default aetherisCad;
diff --git a/Aetheris.Web.Runtime/sdk/src/vite.js b/Aetheris.Web.Runtime/sdk/src/vite.js
new file mode 100644
index 00000000..435dbc87
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/vite.js
@@ -0,0 +1,32 @@
+import { createReadStream, existsSync } from 'node:fs';
+import { cp, stat } from 'node:fs/promises';
+import { extname, join, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const runtimeDirectory = fileURLToPath(new URL('./runtime/', import.meta.url));
+const publicPath = '/aetheris-runtime/';
+const mime = new Map([['.js', 'text/javascript'], ['.json', 'application/json'], ['.wasm', 'application/wasm'], ['.pdb', 'application/octet-stream'], ['.dat', 'application/octet-stream']]);
+
+export function aetherisCad() {
+ let outputDirectory;
+ return {
+ name: 'aetheris-cad-runtime',
+ enforce: 'pre',
+ config: () => ({ define: { __AETHERIS_RUNTIME_BASE__: JSON.stringify(publicPath) }, optimizeDeps: { exclude: ['@aetheris/cad'] } }),
+ configResolved: config => { outputDirectory = config.build.outDir; },
+ configureServer(server) {
+ server.middlewares.use(publicPath, async (request, response, next) => {
+ const relative = decodeURIComponent((request.url ?? '').split('?')[0]).replace(/^\/+/, '');
+ const path = resolve(runtimeDirectory, relative);
+ const runtimeRoot = resolve(runtimeDirectory);
+ if (path !== runtimeRoot && !path.startsWith(runtimeRoot + sep)) return next();
+ if (!existsSync(path) || !(await stat(path)).isFile()) return next();
+ response.setHeader('Content-Type', mime.get(extname(path)) ?? 'application/octet-stream');
+ createReadStream(path).pipe(response);
+ });
+ },
+ async writeBundle() { await cp(runtimeDirectory, join(outputDirectory, 'aetheris-runtime'), { recursive: true }); }
+ };
+}
+
+export default aetherisCad;
diff --git a/Aetheris.Web.Runtime/sdk/src/worker.js b/Aetheris.Web.Runtime/sdk/src/worker.js
new file mode 100644
index 00000000..bf6313b7
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/src/worker.js
@@ -0,0 +1,13 @@
+import { createRuntime, transferables } from './runtime.js';
+
+let invoke;
+self.onmessage = async event => {
+ const { id, request, runtimeBase } = event.data;
+ try {
+ invoke ??= await createRuntime(runtimeBase ? new URL(runtimeBase) : undefined);
+ const result = invoke(request);
+ self.postMessage({ id, result }, { transfer: transferables(result) });
+ } catch (error) {
+ self.postMessage({ id, error: { name: error.name, code: error.code ?? 'internal-error', message: error.message, details: error.details } });
+ }
+};
diff --git a/Aetheris.slnx b/Aetheris.slnx
index c62736b4..ad4f3272 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -76,5 +76,6 @@
<Project Path="Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj" />
<Project Path="test-support/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj" />
<Project Path="test-support/Aetheris.TestForgePack.Duplicate/Aetheris.TestForgePack.Duplicate.csproj" />
+ <Project Path="Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj" />
<Project Path="demos/Aetheris.PmiInjectionDemo/Aetheris.PmiInjectionDemo.csproj" />
</Solution>
diff --git a/docs/public/web-sdk/api-reference.md b/docs/public/web-sdk/api-reference.md
new file mode 100644
index 00000000..80cdc102
--- /dev/null
+++ b/docs/public/web-sdk/api-reference.md
@@ -0,0 +1,17 @@
+# Web SDK API reference
+
+The stable preview contract is `aetheris/web-editor-contract/1`.
+
+- `Aetheris.create(options?)` initializes the runtime. Options: `worker` (only `false`/omitted in X1), `wasmUrl`, and a diagnostics callback.
+- `cad.info()` and `cad.capabilities()` report package/runtime/contract versions and support flags.
+- `cad.compile(source, { sourceName?, signal? })` returns `{ model, diagnostics }`; compiler failures are values, not thrown private exceptions.
+- `model.tree`, `properties`, `mesh`, `diagnostics`, `revision`, and `changes` are the current valid snapshot.
+- `model.entity(id)` and `model.property(id)` inspect public records.
+- `model.setProperty(id, { value, unit })` validates and rebuilds a source-backed scalar property.
+- `model.setSource(source)` replaces source and rebuilds transactionally.
+- `model.rebuild()` rebuilds the current source plus overrides.
+- `model.resolveSelection(...)` and `selectionForEntity(...)` translate selection in both directions.
+- `model.exportSTEP()` returns `Uint8Array`; `exportSTEPBlob()` returns a browser `Blob`.
+- `model.dispose()` and `cad.dispose()` release managed sessions.
+
+Unexpected failures throw `AetherisError` with stable `code`, safe `message`, and optional developer `details`. See the shipped `index.d.ts` for exact readonly record types.
diff --git a/docs/public/web-sdk/capability-matrix.md b/docs/public/web-sdk/capability-matrix.md
new file mode 100644
index 00000000..822aa2b0
--- /dev/null
+++ b/docs/public/web-sdk/capability-matrix.md
@@ -0,0 +1,21 @@
+# Web SDK X1 capability matrix
+
+| Capability | Native | Browser WASM X1 | Notes |
+|---|---:|---:|---|
+| Firmament V2 compile from memory | Yes | Yes | Same compiler/materializer |
+| Solid modeling | Yes | Yes | Qualified canonical box-with-hole fixture |
+| Assembly hierarchy and mesh | Yes | Yes | Same M1 assembly pipeline; external-file definitions excluded |
+| Display mesh | Yes | Yes | Same B-rep tessellator, synchronous browser route |
+| Face/semantic selection | Yes | Yes | Triangle ranges plus occurrence IDs |
+| Property inspection/edit | Yes | Bounded | Scalar template arguments and canonical box/hole properties |
+| Transactional rebuild | Yes | Yes | Last valid snapshot retained |
+| AP242 STEP export in memory | Yes | Yes | UTF-8 bytes; no temporary file |
+| Sheet metal | Yes | No | Not qualified in browser X1 |
+| FEA | Yes | No | Deferred |
+| SQLite materials | Yes | No | Native vararg calls are not browser-safe |
+| External STEP file import | Yes | No | Browser filesystem/resource abstraction deferred |
+| Forge process/subprocess operations | Yes | No | Browser host exposes editor operations only |
+| Web Worker | N/A | No | Transport initialization does not complete in Chromium; typed rejection |
+| Cancellation | Yes | Pre-start only | No mid-kernel cancellation |
+
+The browser package is currently large because it carries untrimmed transitive assemblies. Package-size optimization is deferred; capability claims do not depend on removing those assemblies.
diff --git a/docs/public/web-sdk/editor-integration.md b/docs/public/web-sdk/editor-integration.md
new file mode 100644
index 00000000..56dc81c3
--- /dev/null
+++ b/docs/public/web-sdk/editor-integration.md
@@ -0,0 +1,23 @@
+# Editor integration
+
+`compile` creates a transactional `ModelSession`. A successful snapshot contains a normalized tree, editable source-backed properties, display mesh, diagnostics, revision, and coarse changeset. A failed rebuild leaves the last successful snapshot and revision usable.
+
+Property editing is deliberately bounded. X1 recognizes scalar length arguments in a template specialization and the width, height, thickness, and first hole diameter of the canonical box-with-hole form. `setProperty` records an effective source-span override while deliberately leaving `model.source` unchanged, so a source editor and property grid can temporarily differ. Treat the property grid as the effective value view, or patch the editor text separately when immediate textual synchronization is required. `setSource` replaces the source and clears all property overrides; use it for arbitrary authoring changes.
+
+Each mesh definition contains `Float64Array` positions/normals, `Uint32Array` indices, and triangle ranges with B-rep face and semantic IDs. Occurrences preserve hierarchy and 4×4 transforms. Use `resolveSelection(definitionId, triangleIndex, occurrenceId?)` for viewport-to-model selection and `selectionForEntity(id)` for tree-to-viewport highlighting.
+
+For Three.js, create one `BufferGeometry` per definition and one `Mesh` per occurrence:
+
+```ts
+const geometry = new THREE.BufferGeometry();
+// The SDK preserves kernel precision with Float64Array. WebGL vertex attributes
+// require a supported GPU format, so convert at the renderer boundary.
+geometry.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(definition.positions), 3));
+geometry.setAttribute("normal", new THREE.BufferAttribute(Float32Array.from(definition.normals), 3));
+geometry.setIndex(new THREE.BufferAttribute(definition.indices, 1));
+const object = new THREE.Mesh(geometry, material);
+object.matrix.fromArray(occurrence.transform);
+object.matrixAutoUpdate = false;
+```
+
+`setProperty`, `setSource`, and `rebuild` are serialized per session. Abort signals reject before an operation begins; mid-kernel cancellation is not supported in X1. The Vite plugin copies runtime assets for offline deployment. CSP must allow same-origin WASM compilation and module scripts; no generated JavaScript or `eval` is used by the SDK.
diff --git a/docs/public/web-sdk/getting-started.md b/docs/public/web-sdk/getting-started.md
new file mode 100644
index 00000000..04b918a4
--- /dev/null
+++ b/docs/public/web-sdk/getting-started.md
@@ -0,0 +1,37 @@
+# Aetheris Web SDK getting started
+
+Install the preview package and configure Vite to copy and serve its self-contained runtime:
+
+```sh
+npm install @aetheris/cad
+```
+
+```js
+// vite.config.js
+import { defineConfig } from "vite";
+import { aetherisCad } from "@aetheris/cad/vite";
+export default defineConfig({ plugins: [aetherisCad()] });
+```
+
+```ts
+import { Aetheris } from "@aetheris/cad";
+
+const cad = await Aetheris.create();
+const source = `Model Plate {
+ Units: mm
+ Box Body { Size: [50mm, 40mm, 8mm] }
+ Modify Body { Hole<Shaft> Mount { On: +Z Center: Point2(0mm, 0mm) Diameter: 8mm End: ThroughAll } }
+}`;
+const { model, diagnostics } = await cad.compile(source, { sourceName: "plate.firmament" });
+if (!model) throw new Error(diagnostics.map(item => item.message).join("\n"));
+
+console.log(model.tree, model.properties, model.mesh);
+const width = model.properties.find(item => item.name === "Width")!;
+await model.setProperty(width.id, { value: 80, unit: "mm" });
+const step = await model.exportSTEP();
+const download = URL.createObjectURL(new Blob([step], { type: "model/step" }));
+```
+
+Call `model.dispose()` and `cad.dispose()` when finished. X1 runs on the page thread. `worker: true` is rejected with `worker-unavailable` until that transport is qualified.
+
+The package is AGPL-3.0-only in X1. Contact the Aetheris project about commercial licensing; obtain legal advice for your distribution model.
diff --git a/docs/public/web-sdk/troubleshooting.md b/docs/public/web-sdk/troubleshooting.md
new file mode 100644
index 00000000..f355d840
--- /dev/null
+++ b/docs/public/web-sdk/troubleshooting.md
@@ -0,0 +1,9 @@
+# Web SDK troubleshooting
+
+If Vite returns 404 for runtime files, add `aetherisCad()` from `@aetheris/cad/vite`. For another bundler, copy `dist/runtime` unchanged to a public URL and pass that directory as `wasmUrl`.
+
+Serve over HTTP(S), not `file://`. Preserve `.wasm` files and serve them as `application/wasm`. Runtime assets must remain same-origin unless the asset host supplies correct CORS headers.
+
+If `compile` returns `model: null`, render the structured diagnostics. Do not parse exception strings. If a rebuild fails, the session still exposes its prior valid mesh and revision.
+
+`worker: true` is intentionally unavailable in X1. Omit it or pass `false`. SQLite materials, external file import, sheet metal, and FEA are likewise outside the admitted browser capability set.
diff --git a/docs/release/WEB-SDK-X1.md b/docs/release/WEB-SDK-X1.md
new file mode 100644
index 00000000..308307e4
--- /dev/null
+++ b/docs/release/WEB-SDK-X1.md
@@ -0,0 +1,37 @@
+# WEB-SDK-X1 release report
+
+## Executive verdict
+
+**Accepted.** An external developer can install the local `@aetheris/cad` package and, through public TypeScript APIs and documentation alone, build a basic semantic browser CAD editor. The qualified path compiles in-memory Firmament parts and assemblies in Chromium, exposes model trees and editable properties, renders typed-array mesh data, maps selection in both directions, rebuilds transactionally, and exports STEP bytes. Worker execution remains unavailable and Firefox remains unqualified; both are reported limitations rather than hidden parity claims.
+
+## Runtime and parity audit
+
+The browser host invokes `FirmamentBuildAndExport.CompileSource`, `Step242Importer`, `BrepDisplayTessellator`, `AssemblyM1Pipeline`, `AssemblyDisplayMeshExporter`, and `AssemblyIrAp242Exporter`. It does not implement Firmament, B-rep, tessellation, or assembly semantics in JavaScript. Source, STEP, and mesh stay in memory. Browser tessellation uses the existing synchronous tessellator because its optional native timeout wrapper blocks on monitors, which browser WASM forbids.
+
+Core compilation, solid modeling, tessellation, and AP242 work in browser WASM. Filesystem-driven external parts, Forge subprocesses, SQLite material lookup, sheet metal, FEA, and mid-operation cancellation are excluded. The linked SQLite dependency reports unsupported native vararg entry points, so the public capability reports SQLite as unavailable.
+
+## Public editor contract
+
+The public surface is `Aetheris.create/info/capabilities/compile/dispose` and `ModelSession` snapshot, inspection, source/property editing, rebuild, bidirectional selection, STEP export, and disposal. Diagnostics and errors are normalized. Revisions are monotonic after successful builds; failed rebuilds retain the prior snapshot. Mesh definitions preserve sharing; occurrences carry hierarchy and transforms; face ranges map triangles to face and semantic identity.
+
+## Package and consumer evidence
+
+The reproducible command is `npm run build` in `Aetheris.Web.Runtime/sdk`. It builds browser WASM and copies runtime, ESM facade, Worker module, declarations, and Vite integration into `dist`; `npm pack` produces `@aetheris/cad` 2.0.0-preview.3. The final measured tarball is 33,072,478 bytes and unpacked package is 61,940,213 bytes across 446 entries. The runtime contains 202 WASM modules totaling 40,965,315 bytes; the largest are the 5,589,785-byte Firmament kernel, 4,869,913-byte core library, and 3,964,206-byte native runtime. Optimization is outstanding.
+
+A fresh project outside the checkout installed the tarball and Vite, built successfully with no repository-relative paths, and ran headless Chromium. Its direct-runtime witness initialized in 392.9 ms (warm local server/browser conditions), compiled the canonical bracket, exposed 2 tree nodes, 4 properties, 1 mesh definition, 1 occurrence, and 1,808 triangles, resolved triangle 0 to `face:1` / `Plate.CenterMount`, changed X bounds from ±25 mm to ±40 mm after Width 50→80 mm, and exported 7,294-byte STEP before and after editing. A zero-thickness source edit produced structured diagnostics and retained revision 2; recovery succeeded.
+
+Two independent fresh agents were given only the public web-SDK docs, packed tarball, and canonical Firmament fixture; neither inspected Aetheris internals or reference-editor source. One was asked for a distinct source-textarea frontend with viewport, parameter table, rebuild, and selection; it built a Vite/TypeScript editor with canvas projection, property table, bidirectional selection demonstration, and STEP export. Real Chromium WASM reached revision 4, selected `Plate.CenterMount` / `face:1`, and exported 7,338 bytes. The other received the mandatory model-tree, Three.js viewport, selection, property-inspector, width-edit, and STEP-download prompt. It built that editor independently; headless Edge passed with no console or page errors, selected `Plate.CenterMount`, rebuilt Width 50→72 at revision 2, and downloaded a valid 7,294-byte STEP file. Their friction findings tightened `EditableProperty.unit` to the public `Unit` union, documented property-override/source synchronization, and corrected the Three.js sample to convert kernel `Float64Array` coordinates to WebGL-compatible `Float32Array` at the rendering boundary.
+
+The browser assembly witness compiled `shared-block-assembly.firmament` through the assembly pipeline with no diagnostics. Its revision-1 snapshot used schema `aetheris/assembly-display-mesh/1`, exposed 3 tree nodes, 2 shared definitions, and 3 hierarchy occurrences, resolved a triangle to a semantic occurrence and B-rep face, and exported 7,532 STEP bytes.
+
+Native CLI build and browser WASM produced the identical baseline STEP SHA-256 `1AF5CD0E2A44F6FF509390DDD01E7C38943168522B9138AEA91C91B1AE7B3928`. Native reinspection found one enclosed-manifold body, 7 faces, 15 edges, 12 vertices, bounds `[-25,-20,0]` to `[25,20,8]` mm, six planes, and one cylinder. The edited browser STEP changed deterministically to SHA-256 `14C9BF8BF2FAA6CC3F2469D5E7D93F8F4EAED2ABFD766F13BD22DE040DA16FEA`.
+
+## Rebuild, disposal, and concurrency
+
+Session mutations are queued deterministically. The Chromium witness completed 100 repeated rebuilds, reached revision 103 after edit/failure/recovery, and then disposed the model and runtime. Observed `usedJSHeapSize` rose from 16,128,076 to 16,850,845 bytes (722,769 bytes, about 4.5%); this is bounded smoke evidence, not a cross-browser leak guarantee. Abort signals are honored before dispatch only. Worker initialization did not complete in Chromium, so `worker: true` now fails with `worker-unavailable` and capability discovery reports false.
+
+The full serial Release solution build passed. The full solution test command passed 3,606 tests across 18 discovered suites; `Aetheris.FrictionLab.Tests` currently contains no discoverable tests.
+
+## Licensing
+
+Package and WASM metadata use `AGPL-3.0-only`, consistent with repository defaults. Commercial-use implications require the Aetheris license owner and, where appropriate, legal counsel; this report makes no additional legal conclusion.
diff --git a/fixtures/Canonical/WebSdk/editable-bracket.firmament b/fixtures/Canonical/WebSdk/editable-bracket.firmament
new file mode 100644
index 00000000..d9a296d8
--- /dev/null
+++ b/fixtures/Canonical/WebSdk/editable-bracket.firmament
@@ -0,0 +1,7 @@
+Model WebBracket {
+ Units: mm
+ Box Plate { Size: [50mm, 40mm, 8mm] }
+ Modify Plate {
+ Hole<Shaft> CenterMount { On: +Z Center: Point2(0mm, 0mm) Diameter: 8mm End: ThroughAll }
+ }
+}
diff --git a/fixtures/Canonical/WebSdk/shared-block-assembly.firmament b/fixtures/Canonical/WebSdk/shared-block-assembly.firmament
new file mode 100644
index 00000000..73ed839d
--- /dev/null
+++ b/fixtures/Canonical/WebSdk/shared-block-assembly.firmament
@@ -0,0 +1,17 @@
+Units: mm
+
+Template < H: Length > Struct WebBlock {
+ Circle2 Circle { Center: [0mm,0mm] Radius: 4mm }
+ Profile Section { Loop Outer { Circle |> TraceLoop } }
+ Extrude Body { Profile: Section From: 0mm To: H }
+}
+
+Assembly WebBlockPair {
+ <Assembly WebBlockPair>
+ <Part Fixed = WebBlock<H: 10mm>></Part>
+ <Part Moving = WebBlock<H: 8mm>>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 20,0,0,1];
+ </Part>
+ </Assembly>
+ Anchor: WebBlockPair.Fixed;
+}