Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Replace legacy Firmament frontend with the unified V2 pipeline

Yuechen Lib05cca40ec3e
diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index c3d90219..eb43bfac 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -24,6 +24,11 @@ jobs:
with:
dotnet-version: 10.0.x
+ - name: Setup Node for pinned drawing browser assets
+ uses: actions/setup-node@v4
+ with:
+ node-version: 24
+
- name: Prepare managed WGSL dependency
uses: ./.github/actions/prepare-managed-wgsl
@@ -48,9 +53,23 @@ jobs:
- name: Build solution
run: dotnet build Aetheris.slnx --configuration Release --no-restore -m:1
+ - name: Install optional PDF renderer for interoperability tests
+ run: sudo apt-get update && sudo apt-get install -y poppler-utils
+
- name: Test full solution
+ env:
+ AETHERIS_TEST_PDFTOPPM: /usr/bin/pdftoppm
run: dotnet test Aetheris.slnx --configuration Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+ - name: Qualify portable CLI package
+ shell: pwsh
+ run: |
+ dotnet pack Aetheris.CLI -c Release --no-build -m:1 -nr:false -o artifacts/local/portable-cli
+ if ($LASTEXITCODE -ne 0) { throw 'CLI pack failed' }
+ $packages = @(Get-ChildItem artifacts/local/portable-cli/Aetheris.CLI.*.nupkg)
+ if ($packages.Count -ne 1) { throw 'Expected one core CLI package' }
+ ./scripts/Test-CoreCliPayload.ps1 -PackagePath $packages[0].FullName
+
public-library-build:
if: github.event_name == 'workflow_dispatch'
runs-on: windows-latest
diff --git a/.gitignore b/.gitignore
index 0a2c430b..f3d83d55 100644
--- a/.gitignore
+++ b/.gitignore
@@ -354,6 +354,13 @@ FakesAssemblies/
.ntvs_analysis.dat
node_modules/
+# PDF.js is restored from Aetheris.Drawing/Web/package-lock.json, not vendored.
+/Aetheris.Drawing/Web/pdfjs/
+/Aetheris.Drawing/Web/pdfjs-dist/
+/Aetheris.Drawing/Web/package/
+/Aetheris.Drawing/Web/*.tgz
+/Aetheris.Drawing/Web/*.zip
+
# Visual Studio 6 build log
*.plg
diff --git a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
index cdd0a777..6c07b058 100644
--- a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
+++ b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
@@ -13,6 +13,8 @@
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
+ <ItemGroup><ProjectReference Include="../Aetheris.ThreeDm/Aetheris.ThreeDm.csproj" /></ItemGroup>
+
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
diff --git a/Aetheris.CLI.Tests/DrawingNotesCliTests.cs b/Aetheris.CLI.Tests/DrawingNotesCliTests.cs
index a4933ce6..f9d27598 100644
--- a/Aetheris.CLI.Tests/DrawingNotesCliTests.cs
+++ b/Aetheris.CLI.Tests/DrawingNotesCliTests.cs
@@ -5,16 +5,37 @@ namespace Aetheris.CLI.Tests;
public sealed class DrawingNotesCliTests
{
[Fact]
- public void InspectRenderAndCrop_UseCoherentDrawingFamily()
+ public void InspectAndNotes_NeedNoRendererAndMissingRasterizerFailsClearly()
{
using var temp = new TempDirectory();
var inspect = Run(["drawing", "inspect", Fixture(), "--json"]);
Assert.Equal(0, inspect.Exit); Assert.Equal(string.Empty, inspect.Error);
using (var json = JsonDocument.Parse(inspect.Output)) Assert.Equal(1, json.RootElement.GetProperty("document").GetProperty("pageCount").GetInt32());
var page = Path.Combine(temp.Path, "page.png"); var crop = Path.Combine(temp.Path, "detail.png");
- Assert.Equal(0, Run(["drawing", "render", Fixture(), "--page", "1", "--out", page, "--dpi", "96", "--json"]).Exit);
- Assert.Equal(0, Run(["drawing", "crop", Fixture(), "--page", "1", "--bounds", "465,60,180,200", "--name", "DetailD", "--out", crop, "--dpi", "96", "--json"]).Exit);
- Assert.True(File.Exists(page)); Assert.True(File.Exists(crop)); Assert.True(File.Exists(Path.ChangeExtension(crop, ".crop.json")));
+ var render = Run(["drawing", "render", Fixture(), "--page", "1", "--out", page, "--dpi", "96", "--json"]);
+ Assert.NotEqual(0, render.Exit); Assert.Contains("drawing-renderer-required", render.Error + render.Output);
+ using (var json = JsonDocument.Parse(render.Output))
+ {
+ Assert.False(json.RootElement.GetProperty("success").GetBoolean());
+ var diagnostic = json.RootElement.GetProperty("diagnostics")[0];
+ Assert.Equal("drawing-renderer-required", diagnostic.GetProperty("code").GetString());
+ Assert.Equal("error", diagnostic.GetProperty("severity").GetString());
+ Assert.Contains("--renderer", diagnostic.GetProperty("message").GetString());
+ }
+ var cropped = Run(["drawing", "crop", Fixture(), "--page", "1", "--bounds", "465,60,180,200", "--name", "DetailD", "--out", crop, "--dpi", "96", "--json"]);
+ Assert.NotEqual(0, cropped.Exit); Assert.Contains("drawing-renderer-required", cropped.Error + cropped.Output);
+ Assert.False(File.Exists(page)); Assert.False(File.Exists(crop)); Assert.False(File.Exists(Path.ChangeExtension(crop, ".crop.json")));
+ }
+
+ [Theory]
+ [InlineData("inspect-3dm")]
+ [InlineData("recover-3dm")]
+ public void CoreCli_ExplainsOptionalThreeDmTool(string command)
+ {
+ var result = Run([command, "source.3dm"]);
+ Assert.NotEqual(0, result.Exit);
+ Assert.Contains("aetheris-3dm-required", result.Error);
+ Assert.Contains("Aetheris.ThreeDm.CLI", result.Error);
}
[Fact]
diff --git a/Aetheris.CLI/Aetheris.CLI.csproj b/Aetheris.CLI/Aetheris.CLI.csproj
index e7733828..ab95d74c 100644
--- a/Aetheris.CLI/Aetheris.CLI.csproj
+++ b/Aetheris.CLI/Aetheris.CLI.csproj
@@ -23,8 +23,7 @@
<ItemGroup>
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />
- <ProjectReference Include="..\Aetheris.ThreeDm\Aetheris.ThreeDm.csproj" />
- <ProjectReference Include="..\Aetheris.Firmament.FrictionLab\Aetheris.Firmament.FrictionLab.csproj" />
+ <ProjectReference Include="..\Aetheris.Firmament.FrictionLab\Aetheris.Firmament.FrictionLab.csproj" GlobalPropertiesToRemove="SelfContained" />
<ProjectReference Include="..\Aetheris.FEA\Aetheris.FEA.csproj" />
<ProjectReference Include="..\Aetheris.Modules.BuiltIn\Aetheris.Modules.BuiltIn.csproj" />
<ProjectReference Include="..\Aetheris.Reconstruction\Aetheris.Reconstruction.csproj" />
@@ -38,12 +37,12 @@
<ItemGroup>
<None Include="..\docs\release\Aetheris.CLI.README.md" Pack="true" PackagePath="\" Link="Aetheris.CLI.README.md" />
</ItemGroup>
- <!-- Native packages such as SkiaSharp ship ~90 MB debug symbols per Windows RID. They are
- not needed at run time and push the tool package past nuget.org's 250 MB limit. -->
- <Target Name="ExcludeNativeDebugSymbols" AfterTargets="ResolvePackageAssets">
+ <!-- Fail at the dependency owner, before packing or RID publishing. -->
+ <Target Name="RejectThirdPartyNativeAssets" AfterTargets="ResolvePackageAssets">
<ItemGroup>
- <RuntimeTargetsCopyLocalItems Remove="@(RuntimeTargetsCopyLocalItems)" Condition="'%(Extension)' == '.pdb'" />
- <NativeCopyLocalItems Remove="@(NativeCopyLocalItems)" Condition="'%(Extension)' == '.pdb'" />
+ <_ThirdPartyNative Include="@(NativeCopyLocalItems)" Condition="!$([System.String]::Copy('%(NuGetPackageId)').StartsWith('Microsoft.NETCore.App.Runtime.'))" />
+ <_ThirdPartyNative Include="@(RuntimeTargetsCopyLocalItems)" Condition="'%(AssetType)' == 'native' and !$([System.String]::Copy('%(NuGetPackageId)').StartsWith('Microsoft.NETCore.App.Runtime.'))" />
</ItemGroup>
+ <Error Condition="'@(_ThirdPartyNative)' != ''" Text="The default Aetheris CLI must not bundle third-party native assets: @(_ThirdPartyNative). Move native interoperability to an optional tool." />
</Target>
</Project>
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 1c343980..f86c09e0 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -190,6 +190,12 @@ public static class CliRunner
public static int Run(string[] args, TextWriter stdout, TextWriter stderr)
=> Run(args, stdout, stderr, new SystemCadmataProcessLauncher(), AppContext.BaseDirectory);
+ private static int MissingThreeDmTool(TextWriter stderr)
+ {
+ stderr.WriteLine("aetheris-3dm-required: 3DM interoperability is an optional tool. Install with 'dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease', then use 'aetheris-3dm inspect' or 'aetheris-3dm recover'.");
+ return 1;
+ }
+
internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, ICadmataProcessLauncher cadmataLauncher, string cliBaseDirectory)
{
if (args.Length == 0)
@@ -224,8 +230,8 @@ public static class CliRunner
"lock" => DependencyLockCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),
"measure" => FirmamentMeasureCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
- "inspect-3dm" => ThreeDmCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
- "recover-3dm" => ThreeDmCli.Recover(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
+ "inspect-3dm" => MissingThreeDmTool(stderr),
+ "recover-3dm" => MissingThreeDmTool(stderr),
"inspect-profile" => RunInspectProfile(args.Skip(1).ToArray(), stdout, stderr),
"inspect-spans" => RunInspectSpans(args.Skip(1).ToArray(), stdout, stderr),
"inspect-compose" => RunInspectCompose(args.Skip(1).ToArray(), stdout, stderr),
@@ -5346,8 +5352,7 @@ Model CanonicalPanel {
stdout.WriteLine(" lock Generate or explicitly update firmament.lock.toml dependency receipts.");
stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");
stdout.WriteLine(" measure Measure a compiled part and print assertion templates without claiming its assertions passed.");
- stdout.WriteLine(" inspect-3dm Inventory local Rhino 3DM geometry and import blockers.");
- stdout.WriteLine(" recover-3dm Measure Rhino recovery candidates or bind qualified BReps to STEP.");
+ stdout.WriteLine(" 3DM interop Optional aetheris-3dm tool: inspect/recover Rhino geometry and bind qualified BReps to STEP.");
stdout.WriteLine(" analyze Analyze STEP topology and analytic surfaces.");
stdout.WriteLine(" fea Compile and solve a Firmament linear-elastic analysis and export Abaqus verification input.");
stdout.WriteLine(" drawing Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");
diff --git a/Aetheris.CLI/DrawingNotesCli.cs b/Aetheris.CLI/DrawingNotesCli.cs
index 161e7aa4..588abd2f 100644
--- a/Aetheris.CLI/DrawingNotesCli.cs
+++ b/Aetheris.CLI/DrawingNotesCli.cs
@@ -10,8 +10,8 @@ internal static class DrawingNotesCli
internal const string Usage = """
Usage:
aetheris drawing inspect <drawing.pdf> [--json]
- aetheris drawing render <drawing.pdf> --page <N> --out <page.png> [--dpi <N>] [--json]
- aetheris drawing crop <drawing.pdf> --page <N> --bounds <x,y,width,height> --name <name> --out <crop.png> [--dpi <N>] [--json]
+ aetheris drawing render <drawing.pdf> --page <N> --out <page.png> [--dpi <N>] --renderer <path-to-pdftoppm> [--json]
+ aetheris drawing crop <drawing.pdf> --page <N> --bounds <x,y,width,height> --name <name> --out <crop.png> [--dpi <N>] --renderer <path-to-pdftoppm> [--json]
aetheris drawing notes create <drawing.pdf> --out <directory> [--name <name>] [--title <title>] [--visible-date <date>] [--sheets <id,...>] [--json]
aetheris drawing notes add-region <drawing-notes.json> --id <id> --name <name> --page <N> --bounds <x,y,width,height> --type <type> [--parent <id>] [--confidence <level>] [--json]
aetheris drawing notes add-note <drawing-notes.json> --id <id> --label <label> --category <category> --page <N> --bounds <x,y,width,height> [--region <id>] [--note <text>] [--original-text <text>] [--aliases <a,b>] [--tags <a,b>] [--class <class>] [--confidence <level>] [--pass <id>] [--json]
@@ -33,14 +33,24 @@ Confidence: High, Medium, Low, Unresolved. Classification: ProductGeometry, Acce
public static int Run(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0 || IsHelp(args[0])) { stdout.WriteLine(Usage); return 0; }
- return args[0] switch
+ try
{
- "inspect" => Inspect(args[1..], stdout, stderr),
- "render" => Render(args[1..], stdout, stderr),
- "crop" => Crop(args[1..], stdout, stderr),
- "notes" => Notes(args[1..], stdout, stderr),
- _ => Fail(stderr, $"Unknown drawing command '{args[0]}'.")
- };
+ return args[0] switch
+ {
+ "inspect" => Inspect(args[1..], stdout, stderr),
+ "render" => Render(args[1..], stdout, stderr),
+ "crop" => Crop(args[1..], stdout, stderr),
+ "notes" => Notes(args[1..], stdout, stderr),
+ _ => Fail(stderr, $"Unknown drawing command '{args[0]}'.")
+ };
+ }
+ catch (DrawingNotesException e)
+ {
+ if (args.Contains("--json", StringComparer.Ordinal))
+ stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = new[] { new { code = e.Code, severity = "error", message = e.Message } } }, CliRunner.JsonOptions));
+ else stderr.WriteLine($"{e.Code}: {e.Message}");
+ return 1;
+ }
}
private static int Inspect(string[] args, TextWriter stdout, TextWriter stderr)
@@ -63,19 +73,23 @@ Confidence: High, Medium, Low, Unresolved. Classification: ProductGeometry, Acce
var options = Options(args[1..]);
if (!Int(options, "--page", out var page) || !Required(options, "--out", out var output)) return Fail(stderr, Usage);
var dpi = OptionalInt(options, "--dpi", 200);
- DrawingPdf.RenderPage(args[0], page, output, dpi);
- var report = new { success = true, source = Path.GetFullPath(args[0]), page, output = Path.GetFullPath(output), dpi, renderer = DrawingPdf.RendererVersion };
+ var renderer = Renderer(options);
+ DrawingPdf.RenderPage(args[0], page, output, dpi, renderer);
+ var report = new { success = true, source = Path.GetFullPath(args[0]), page, output = Path.GetFullPath(output), dpi, renderer = renderer?.Version };
Write(stdout, options, report, $"Rendered page {page} to {Path.GetFullPath(output)}.");
return 0;
}
+ private static IDrawingPdfRasterizer? Renderer(Dictionary<string, string?> options) =>
+ Value(options, "--renderer") is { } path ? new PopplerPdfRasterizer(path) : null;
+
private static int Crop(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0) return Fail(stderr, Usage);
var options = Options(args[1..]);
if (!Int(options, "--page", out var page) || !Bounds(options, out var bounds) || !Required(options, "--name", out var name) || !Required(options, "--out", out var output)) return Fail(stderr, Usage);
var dpi = OptionalInt(options, "--dpi", 300);
- var metadata = DrawingPdf.Crop(args[0], page, bounds, name, output, dpi);
+ var metadata = DrawingPdf.Crop(args[0], page, bounds, name, output, dpi, Renderer(options));
Write(stdout, options, new { success = true, output = Path.GetFullPath(output), metadata }, $"Exported source-linked crop '{name}' to {Path.GetFullPath(output)}.");
return 0;
}
diff --git a/Aetheris.Drawing.Tests/DrawingNotesTests.cs b/Aetheris.Drawing.Tests/DrawingNotesTests.cs
index f4af99d1..c756f75c 100644
--- a/Aetheris.Drawing.Tests/DrawingNotesTests.cs
+++ b/Aetheris.Drawing.Tests/DrawingNotesTests.cs
@@ -6,7 +6,7 @@ namespace Aetheris.Drawing.Tests;
public sealed class DrawingNotesTests
{
[Fact]
- public void SyntheticPdf_InspectsAndRendersDeterministically()
+ public void SyntheticPdf_InspectsWithoutNativeRenderer()
{
var pdf = Fixture();
var document = DrawingPdf.Inspect(pdf, "Synthetic Fixture", sheets: ["SHEET 1 OF 1"]);
@@ -15,9 +15,9 @@ public sealed class DrawingNotesTests
Assert.Equal(612, document.Pages[0].HeightPoints);
Assert.Equal(64, document.Sha256.Length);
using var temp = new TempDirectory();
- var first = Path.Combine(temp.Path, "first.png"); var second = Path.Combine(temp.Path, "second.png");
- DrawingPdf.RenderPage(pdf, 1, first, 120); DrawingPdf.RenderPage(pdf, 1, second, 120);
- Assert.Equal(SHA256.HashData(File.ReadAllBytes(first)), SHA256.HashData(File.ReadAllBytes(second)));
+ var first = Path.Combine(temp.Path, "first.png");
+ Assert.Equal("drawing-renderer-required", Assert.Throws<DrawingNotesException>(() => DrawingPdf.RenderPage(pdf, 1, first, 120)).Code);
+ Assert.False(File.Exists(first));
}
[Fact]
@@ -98,13 +98,22 @@ public sealed class DrawingNotesTests
Assert.Contains("Unknown leader", unresolved); Assert.DoesNotContain("Body width", unresolved);
}
- [Fact]
+ [ExternalPdfRendererFact]
public void CropCarriesSourceMetadataAndIsDeterministic()
{
using var temp = new TempDirectory(); var output = Path.Combine(temp.Path, "detail.png");
- var metadata = DrawingPdf.Crop(Fixture(), 1, new(465, 60, 180, 200), "Detail D", output, 120);
+ var renderer = new PopplerPdfRasterizer(Environment.GetEnvironmentVariable("AETHERIS_TEST_PDFTOPPM")!);
+ var metadata = DrawingPdf.Crop(Fixture(), 1, new(465, 60, 180, 200), "Detail D", output, 120, renderer);
Assert.True(File.Exists(output)); Assert.True(File.Exists(Path.ChangeExtension(output, ".crop.json")));
Assert.Equal(DrawingPdf.Hash(Fixture()), metadata.DocumentSha256); Assert.Equal(1, metadata.Page);
+ Assert.StartsWith("pdftoppm version ", metadata.RendererVersion);
+ var first = File.ReadAllBytes(output);
+ DrawingPdf.Crop(Fixture(), 1, metadata.Bounds, "Detail D", output, 120, renderer);
+ Assert.Equal(first, File.ReadAllBytes(output));
+ DrawingPdf.RenderPage(Fixture(), 1, output, 120, renderer);
+ var rendered = SHA256.HashData(File.ReadAllBytes(output));
+ DrawingPdf.RenderPage(Fixture(), 1, output, 120, renderer);
+ Assert.Equal(rendered, SHA256.HashData(File.ReadAllBytes(output)));
}
[Fact]
@@ -114,14 +123,67 @@ public sealed class DrawingNotesTests
DrawingNotesPersistence.Save(path, project); DrawingNotesUi.WriteAssets(Path.Combine(temp.Path, "ui"));
Assert.Equal(project.Document.Sha256, DrawingNotesPersistence.Load(path).Document.Sha256);
var html = File.ReadAllText(Path.Combine(temp.Path, "ui", "index.html"));
- Assert.Contains("/api/project", html); Assert.Contains("Fit page", html); Assert.Contains("Drag highlight", html); Assert.Contains("Shift-drag pan", html); Assert.Contains("/api/thumb/", html);
+ Assert.Contains("/api/project", html); Assert.Contains("Fit page", html); Assert.Contains("Drag highlight", html); Assert.Contains("Shift-drag pan", html);
+ Assert.True(File.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "build", "pdf.mjs")));
+ Assert.True(File.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "build", "pdf.worker.mjs")));
+ Assert.Contains("/api/source.pdf", html);
+ var assets = Directory.GetFiles(Path.Combine(temp.Path, "ui", "pdfjs"), "*", SearchOption.AllDirectories);
+ Assert.DoesNotContain(assets, x => x.EndsWith(".map", StringComparison.OrdinalIgnoreCase));
+ Assert.DoesNotContain(assets, x => x.EndsWith("package.json", StringComparison.OrdinalIgnoreCase));
+ Assert.DoesNotContain(assets, x => x.EndsWith(".node", StringComparison.OrdinalIgnoreCase));
+ Assert.False(Directory.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "legacy")));
+ Assert.False(Directory.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "web")));
+ Assert.True(File.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "LICENSE")));
+ Assert.True(File.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "cmaps", "LICENSE")));
+ Assert.True(File.Exists(Path.Combine(temp.Path, "ui", "pdfjs", "standard_fonts", "LICENSE_FOXIT")));
+ }
+
+ [Fact]
+ public void PageCoordinates_UseRotatedVisibleCropAndPhysicalUserUnits()
+ {
+ var document = DrawingPdf.Inspect(Fixture("page-coordinates.pdf"));
+ Assert.Equal(4, document.PageCount);
+ Assert.Equal([400d, 200d, 400d, 200d], document.Pages.Select(x => x.WidthPoints));
+ Assert.Equal([200d, 400d, 200d, 400d], document.Pages.Select(x => x.HeightPoints));
+ Assert.Equal([0, 90, 180, 270], document.Pages.Select(x => x.RotationDegrees));
+ Assert.All(document.Pages, p => Assert.Equal(2, p.UserUnit));
}
- private static string Fixture()
+ [ExternalPdfRendererFact]
+ public void ExternalRenderer_RejectsWrongDimensionsAndHonorsRotatedCrop()
+ {
+ using var temp = new TempDirectory();
+ var pdf = Fixture("page-coordinates.pdf");
+ var renderer = new PopplerPdfRasterizer(Environment.GetEnvironmentVariable("AETHERIS_TEST_PDFTOPPM")!);
+ foreach (var page in DrawingPdf.Inspect(pdf).Pages)
+ {
+ var output = Path.Combine(temp.Path, $"p{page.Number}.png");
+ DrawingPdf.RenderPage(pdf, page.Number, output, 72, renderer);
+ DrawingPdf.Crop(pdf, page.Number, new(20, 20, 60, 40), "crop", output, 72, renderer);
+ // The adapter checks actual PNG pixel dimensions, rather than trusting process exit.
+ Assert.True(new FileInfo(output).Length > 24);
+ }
+ }
+
+ [Fact]
+ public void InvalidInputAndBounds_FailBeforeRendererOrOutput()
+ {
+ using var temp = new TempDirectory();
+ var path = Path.Combine(temp.Path, "bad.pdf");
+ File.WriteAllText(path, "not a PDF");
+ Assert.Equal("drawing-pdf-inspection-failed", Assert.Throws<DrawingNotesException>(() => DrawingPdf.Inspect(path)).Code);
+ var output = Path.Combine(temp.Path, "out.png");
+ Assert.Equal("drawing-page-invalid", Assert.Throws<DrawingNotesException>(() => DrawingPdf.RenderPage(Fixture(), 99, output)).Code);
+ Assert.Equal("drawing-render-dpi-invalid", Assert.Throws<DrawingNotesException>(() => DrawingPdf.Crop(Fixture(), 1, new(0, 0, 10, 10), "crop", output, 1)).Code);
+ Assert.Equal("drawing-bounds-outside-page", Assert.Throws<DrawingNotesException>(() => DrawingPdf.Crop(Fixture(), 1, new(790, 0, 10, 10), "crop", output)).Code);
+ Assert.False(File.Exists(output));
+ }
+
+ private static string Fixture(string name = "synthetic-engineering-drawing.pdf")
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
- return Path.Combine(directory?.FullName ?? throw new InvalidOperationException("Repository root not found."), "fixtures", "DrawingNotes", "synthetic-engineering-drawing.pdf");
+ return Path.Combine(directory?.FullName ?? throw new InvalidOperationException("Repository root not found."), "fixtures", "DrawingNotes", name);
}
private sealed class TempDirectory : IDisposable
@@ -131,3 +193,12 @@ public sealed class DrawingNotesTests
public void Dispose() { if (Directory.Exists(Path)) Directory.Delete(Path, true); }
}
}
+
+public sealed class ExternalPdfRendererFactAttribute : FactAttribute
+{
+ public ExternalPdfRendererFactAttribute()
+ {
+ if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("AETHERIS_TEST_PDFTOPPM")))
+ Skip = "Optional external renderer: set AETHERIS_TEST_PDFTOPPM to the pdftoppm executable to qualify headless rasterization.";
+ }
+}
diff --git a/Aetheris.Drawing/Aetheris.Drawing.csproj b/Aetheris.Drawing/Aetheris.Drawing.csproj
index 41e9b37a..17014a06 100644
--- a/Aetheris.Drawing/Aetheris.Drawing.csproj
+++ b/Aetheris.Drawing/Aetheris.Drawing.csproj
@@ -3,11 +3,33 @@
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
- <NoWarn>$(NoWarn);CA1416</NoWarn>
- <Description>Source-traceable engineering drawing notes, PDF rendering, and deterministic LLM handoff artifacts.</Description>
+ <Description>Source-traceable engineering drawing notes, managed PDF inspection, and browser rendering.</Description>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="PDFtoImage" Version="5.4.0" />
+ <PackageReference Include="PdfPig" Version="0.1.16" />
+ <None Remove="Web/node_modules/**/*;Web/pdfjs/**/*;Web/pdfjs-dist/**/*;Web/package/**/*" />
</ItemGroup>
+
+ <Target Name="RestoreDrawingBrowserAssets"
+ Inputs="Web/package.json;Web/package-lock.json"
+ Outputs="Web/node_modules/.package-lock.json;Web/node_modules/pdfjs-dist/build/pdf.min.mjs;Web/node_modules/pdfjs-dist/build/pdf.worker.min.mjs">
+ <Exec Command="npm ci --ignore-scripts --omit=optional --no-audit --no-fund"
+ WorkingDirectory="$(MSBuildProjectDirectory)/Web" />
+ </Target>
+
+ <!-- Register after restore, so a fresh checkout needs no pre-existing vendor files.
+ Explicit runtime inputs also keep extra upstream builds/maps/viewers out of packages. -->
+ <Target Name="IncludeDrawingBrowserAssets" BeforeTargets="AssignTargetPaths" DependsOnTargets="RestoreDrawingBrowserAssets">
+ <ItemGroup>
+ <EmbeddedResource Include="Web/node_modules/pdfjs-dist/build/pdf.min.mjs" LogicalName="pdfjs/build/pdf.mjs" />
+ <EmbeddedResource Include="Web/node_modules/pdfjs-dist/build/pdf.worker.min.mjs" LogicalName="pdfjs/build/pdf.worker.mjs" />
+ <_DrawingPdfJsRuntimeAsset Include="Web/node_modules/pdfjs-dist/cmaps/*.bcmap;Web/node_modules/pdfjs-dist/cmaps/LICENSE" RuntimeDirectory="cmaps" />
+ <_DrawingPdfJsRuntimeAsset Include="Web/node_modules/pdfjs-dist/standard_fonts/*.pfb;Web/node_modules/pdfjs-dist/standard_fonts/*.ttf;Web/node_modules/pdfjs-dist/standard_fonts/LICENSE*" RuntimeDirectory="standard_fonts" />
+ <_DrawingPdfJsRuntimeAsset Include="Web/node_modules/pdfjs-dist/wasm/*.wasm;Web/node_modules/pdfjs-dist/wasm/*_nowasm_fallback.js;Web/node_modules/pdfjs-dist/wasm/quickjs-eval.js;Web/node_modules/pdfjs-dist/wasm/LICENSE*" RuntimeDirectory="wasm" />
+ <_DrawingPdfJsRuntimeAsset Include="Web/node_modules/pdfjs-dist/iccs/*.icc;Web/node_modules/pdfjs-dist/iccs/LICENSE*" RuntimeDirectory="iccs" />
+ <EmbeddedResource Include="@(_DrawingPdfJsRuntimeAsset)" LogicalName="pdfjs/%(_DrawingPdfJsRuntimeAsset.RuntimeDirectory)/%(_DrawingPdfJsRuntimeAsset.Filename)%(_DrawingPdfJsRuntimeAsset.Extension)" />
+ <EmbeddedResource Include="Web/node_modules/pdfjs-dist/LICENSE" LogicalName="pdfjs/LICENSE" />
+ </ItemGroup>
+ </Target>
</Project>
diff --git a/Aetheris.Drawing/DrawingNotesUi.cs b/Aetheris.Drawing/DrawingNotesUi.cs
index 6b7a3fe2..970e4054 100644
--- a/Aetheris.Drawing/DrawingNotesUi.cs
+++ b/Aetheris.Drawing/DrawingNotesUi.cs
@@ -1,15 +1,28 @@
using System.Net;
using System.Text;
using System.Text.Json;
+using System.Security.Cryptography;
namespace Aetheris.Drawing;
public static class DrawingNotesUi
{
+ private static readonly IReadOnlyDictionary<string, string> Assets = typeof(DrawingNotesUi).Assembly.GetManifestResourceNames()
+ .Where(x => x.StartsWith("pdfjs/", StringComparison.Ordinal))
+ .ToDictionary(x => "/" + x.Replace('\\', '/'), x => x, StringComparer.Ordinal);
+
public static void WriteAssets(string outputDirectory)
{
Directory.CreateDirectory(outputDirectory);
File.WriteAllText(Path.Combine(outputDirectory, "index.html"), Html, new UTF8Encoding(false));
+ foreach (var (url, resource) in Assets)
+ {
+ var target = Path.Combine(outputDirectory, url.TrimStart('/'));
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ using var input = typeof(DrawingNotesUi).Assembly.GetManifestResourceStream(resource)!;
+ using var output = File.Create(target);
+ input.CopyTo(output);
+ }
}
public static async Task ServeAsync(string projectPath, string pdfPath, int port, TextWriter log, CancellationToken cancellationToken)
@@ -40,6 +53,30 @@ public static class DrawingNotesUi
private static async Task HandleAsync(HttpListenerContext context, string projectPath, string pdfPath, CancellationToken cancellationToken)
{
var path = context.Request.Url?.AbsolutePath ?? "/";
+ context.Response.Headers["Cache-Control"] = "no-store";
+ if (context.Request.HttpMethod == "GET" && Assets.TryGetValue(path, out var resource))
+ {
+ using var stream = typeof(DrawingNotesUi).Assembly.GetManifestResourceStream(resource)!;
+ context.Response.ContentType = Path.GetExtension(path) switch
+ {
+ ".mjs" or ".js" => "text/javascript", ".wasm" => "application/wasm", ".ttf" => "font/ttf", _ => "application/octet-stream"
+ };
+ await stream.CopyToAsync(context.Response.OutputStream, cancellationToken);
+ context.Response.Close();
+ return;
+ }
+ if (context.Request.HttpMethod == "GET" && path == "/api/source.pdf")
+ {
+ var bytes = await File.ReadAllBytesAsync(pdfPath, cancellationToken);
+ var expected = DrawingNotesPersistence.Load(projectPath).Document.Sha256;
+ if (!string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected, StringComparison.OrdinalIgnoreCase))
+ throw new DrawingNotesException("drawing-source-hash-mismatch", "The PDF changed since this notebook was created. Reconcile its source before rendering.");
+ context.Response.ContentType = "application/pdf";
+ context.Response.ContentLength64 = bytes.Length;
+ await context.Response.OutputStream.WriteAsync(bytes, cancellationToken);
+ context.Response.Close();
+ return;
+ }
if (context.Request.HttpMethod == "GET" && path == "/")
{
await WriteText(context.Response, Html, "text/html; charset=utf-8", cancellationToken);
@@ -67,25 +104,6 @@ public static class DrawingNotesUi
await WriteText(context.Response, DrawingNotesMarkdown.Export(DrawingNotesPersistence.Load(projectPath)), "text/markdown; charset=utf-8", cancellationToken);
return;
}
- var isPage = path.StartsWith("/api/page/", StringComparison.Ordinal);
- var isThumbnail = path.StartsWith("/api/thumb/", StringComparison.Ordinal);
- if (context.Request.HttpMethod == "GET" && (isPage || isThumbnail) && path.EndsWith(".png", StringComparison.Ordinal))
- {
- var token = path[(isThumbnail ? 11 : 10)..^4];
- if (!int.TryParse(token, out var page)) { context.Response.StatusCode = 404; context.Response.Close(); return; }
- var temporary = Path.Combine(Path.GetTempPath(), $"aetheris-drawing-ui-{Guid.NewGuid():N}.png");
- try
- {
- DrawingPdf.RenderPage(pdfPath, page, temporary, isThumbnail ? 36 : 180);
- var bytes = await File.ReadAllBytesAsync(temporary, cancellationToken);
- context.Response.ContentType = "image/png";
- context.Response.ContentLength64 = bytes.Length;
- await context.Response.OutputStream.WriteAsync(bytes, cancellationToken);
- context.Response.Close();
- }
- finally { if (File.Exists(temporary)) File.Delete(temporary); }
- return;
- }
context.Response.StatusCode = 404;
context.Response.Close();
}
@@ -106,34 +124,83 @@ public static class DrawingNotesUi
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Aetheris Drawing Notes</title>
<style>
-:root{font:14px Inter,Segoe UI,sans-serif;color:#dfe7ef;background:#111820}*{box-sizing:border-box}body{margin:0;height:100vh;display:grid;grid-template-rows:48px 1fr;background:#111820}header{display:flex;align-items:center;gap:12px;padding:8px 14px;background:#18232e;border-bottom:1px solid #314354}header strong{color:#fff}button,input,select,textarea{font:inherit;color:inherit;background:#22313e;border:1px solid #425768;border-radius:4px;padding:6px}button{cursor:pointer}button:hover{background:#2e4658}.app{display:grid;grid-template-columns:240px minmax(420px,1fr) 320px;min-height:0}.pane{overflow:auto;border-right:1px solid #314354;padding:10px}.right{border-right:0;border-left:1px solid #314354}.page{display:flex;width:100%;text-align:left;margin:5px 0;align-items:center;gap:8px}.page img{width:72px;height:47px;object-fit:cover;background:white}.region{padding:5px;margin:2px 0;border-left:3px solid #55a7d9;cursor:pointer}.viewer{position:relative;overflow:hidden;background:#39434c;touch-action:none}.stage{position:absolute;transform-origin:0 0}.stage img{display:block;user-select:none;-webkit-user-drag:none}.overlay{position:absolute;inset:0;width:100%;height:100%;overflow:visible}.box{fill:#4bc0ff22;stroke:#4bc0ff;stroke-width:1.2;vector-effect:non-scaling-stroke}.box.Dimension{fill:#ffc85730;stroke:#ffc857}.box.Datum{fill:#67d39133;stroke:#67d391}.box.Keepout{fill:#ff6b6b28;stroke:#ff6b6b}.box.related{stroke:#f6f8fa;stroke-width:2}.box.selected{stroke:#fff;stroke-width:3}.draft{fill:#fff2;stroke:#fff;stroke-dasharray:5 3}.form{display:grid;gap:7px}.form label{display:grid;gap:3px;color:#9fb2c2}.form textarea{min-height:76px}.muted{color:#91a3b3;font-size:12px}.status{margin-left:auto;color:#8ed39d}.tree,pre{font-family:ui-monospace,Consolas,monospace;white-space:pre-wrap;background:#0d141a;padding:8px;border-radius:4px}.empty{padding:12px;color:#91a3b3}@media(max-width:900px){.app{grid-template-columns:180px 1fr}.right{position:absolute;right:0;top:48px;bottom:0;width:300px;background:#111820;z-index:3}}
+:root{font:14px Inter,Segoe UI,sans-serif;color:#dfe7ef;background:#111820}*{box-sizing:border-box}body{margin:0;height:100vh;display:grid;grid-template-rows:48px 1fr;background:#111820}header{display:flex;align-items:center;gap:12px;padding:8px 14px;background:#18232e;border-bottom:1px solid #314354}header strong{color:#fff}button,input,select,textarea{font:inherit;color:inherit;background:#22313e;border:1px solid #425768;border-radius:4px;padding:6px}button{cursor:pointer}button:hover{background:#2e4658}.app{display:grid;grid-template-columns:240px minmax(420px,1fr) 320px;min-height:0}.pane{overflow:auto;border-right:1px solid #314354;padding:10px}.right{border-right:0;border-left:1px solid #314354}.page{display:flex;width:100%;text-align:left;margin:5px 0;align-items:center;gap:8px}.page img{width:72px;height:47px;object-fit:cover;background:white}.region{padding:5px;margin:2px 0;border-left:3px solid #55a7d9;cursor:pointer}.viewer{position:relative;overflow:hidden;background:#39434c;touch-action:none}.stage{position:absolute;transform-origin:0 0}.stage canvas{display:block;user-select:none;-webkit-user-drag:none}.overlay{position:absolute;inset:0;width:100%;height:100%;overflow:visible}.box{fill:#4bc0ff22;stroke:#4bc0ff;stroke-width:1.2;vector-effect:non-scaling-stroke}.box.Dimension{fill:#ffc85730;stroke:#ffc857}.box.Datum{fill:#67d39133;stroke:#67d391}.box.Keepout{fill:#ff6b6b28;stroke:#ff6b6b}.box.related{stroke:#f6f8fa;stroke-width:2}.box.selected{stroke:#fff;stroke-width:3}.draft{fill:#fff2;stroke:#fff;stroke-dasharray:5 3}.form{display:grid;gap:7px}.form label{display:grid;gap:3px;color:#9fb2c2}.form textarea{min-height:76px}.muted{color:#91a3b3;font-size:12px}.status{margin-left:auto;color:#8ed39d}.tree,pre{font-family:ui-monospace,Consolas,monospace;white-space:pre-wrap;background:#0d141a;padding:8px;border-radius:4px}.empty{padding:12px;color:#91a3b3}@media(max-width:900px){.app{grid-template-columns:180px 1fr}.right{position:absolute;right:0;top:48px;bottom:0;width:300px;background:#111820;z-index:3}}
</style>
</head>
<body>
-<header><strong>Aetheris Drawing Notes</strong><button id="fit">Fit page</button><button id="width">Fit width</button><button id="minus">-</button><span id="zoom">100%</span><button id="plus">+</button><button id="preview">Markdown</button><span class="muted">Drag highlight · Shift-drag pan · D dimension · V view · Q question</span><span class="status" id="status">Loading…</span></header>
-<main class="app"><aside class="pane"><h3>Pages / regions</h3><div id="pages"></div><h3>Relationship tree</h3><div id="tree" class="tree"></div></aside><section class="viewer" id="viewer"><div class="stage" id="stage"><img id="pageImage" alt="PDF page"><svg class="overlay" id="overlay"></svg></div></section><aside class="pane right"><h3>Selected note</h3><div id="editor" class="empty">Drag a rectangle or select an overlay.</div></aside></main>
-<script>
+<header><strong>Aetheris Drawing Notes</strong><button id="fit">Fit page</button><button id="width">Fit width</button><button id="minus">-</button><span id="zoom">100%</span><button id="plus">+</button><button id="preview">Markdown</button><button id="crop">Export crop</button><span class="muted">Drag highlight · Shift-drag pan · D dimension · V view · Q question</span><span class="status" id="status">Loading…</span></header>
+<main class="app"><aside class="pane"><h3>Pages / regions</h3><div id="pages"></div><h3>Relationship tree</h3><div id="tree" class="tree"></div></aside><section class="viewer" id="viewer"><div class="stage" id="stage"><canvas id="pageImage" aria-label="PDF page"></canvas><svg class="overlay" id="overlay"></svg></div></section><aside class="pane right"><h3>Selected note</h3><div id="editor" class="empty">Drag a rectangle or select an overlay.</div></aside></main>
+<script type="module">
+import * as pdfjs from '/pdfjs/build/pdf.mjs';
+pdfjs.GlobalWorkerOptions.workerSrc='/pdfjs/build/pdf.worker.mjs';
+let pdf,renderSequence=0,renderedPage=null;
+const thumbnails=new Map();
+function error(e){$('status').textContent='Error: '+e.message;console.error(e)}
+async function request(url){const r=await fetch(url);if(!r.ok)throw new Error(await r.text());return r}
+async function renderPage(number,dpi){
+ const p=project.document.pages.find(x=>x.number===number),source=await pdf.getPage(number),v=source.getViewport({scale:1});
+ if(Math.abs(v.width-p.widthPoints)>.01||Math.abs(v.height-p.heightPoints)>.01)throw new Error(`Page ${number} coordinates differ from the notebook. Reconcile page metadata before annotating.`);
+ const viewport=source.getViewport({scale:dpi/72}),canvas=document.createElement('canvas');
+ canvas.width=Math.ceil(viewport.width);canvas.height=Math.ceil(viewport.height);
+ await source.render({canvasContext:canvas.getContext('2d'),viewport,background:'rgb(255,255,255)'}).promise;
+ return canvas;
+}
+async function thumbnail(number){if(!thumbnails.has(number))thumbnails.set(number,renderPage(number,36).then(c=>c.toDataURL('image/png')));return thumbnails.get(number)}
+
let project,page=1,scale=1,pan={x:20,y:20},selected=null,draft=null,start=null,panStart=null;
const $=id=>document.getElementById(id),viewer=$('viewer'),stage=$('stage'),img=$('pageImage'),svg=$('overlay');
const enums={category:['Datum','Dimension','Feature','View','Section','Keepout','Note','Relationship','Uncertain','Question'],confidence:['High','Medium','Low','Unresolved'],semantic:['ProductGeometry','AccessoryKeepout','SensorKeepout','MaterialRestriction','CosmeticReference','FunctionalReference','Unknown'],dimension:['Overall','Offset','Diameter','Radius','Depth','Thickness','Angle','Coordinate','Keepout','AllAround','Unknown']};
-async function load(){project=await (await fetch('/api/project')).json();page=project.document.pages[0].number;showPage();renderLists();$('status').textContent='Saved';}
-function showPage(){img.src=`/api/page/${page}.png`;img.onload=()=>{const p=project.document.pages.find(x=>x.number===page);img.width=p.widthPoints*2.5;img.height=p.heightPoints*2.5;svg.setAttribute('viewBox',`0 0 ${p.widthPoints} ${p.heightPoints}`);svg.style.width=img.width+'px';svg.style.height=img.height+'px';draw();fit();};}
+async function load(){
+ project=await (await request('/api/project')).json();
+ const bytes=new Uint8Array(await (await request('/api/source.pdf')).arrayBuffer());
+ const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),n=>n.toString(16).padStart(2,'0')).join('');
+ if(hash!==project.document.sha256.toLowerCase())throw new Error('PDF source hash mismatch');
+ pdf=await pdfjs.getDocument({data:bytes,cMapUrl:'/pdfjs/cmaps/',cMapPacked:true,standardFontDataUrl:'/pdfjs/standard_fonts/',wasmUrl:'/pdfjs/wasm/',iccUrl:'/pdfjs/iccs/',isEvalSupported:false}).promise;
+ if(pdf.numPages!==project.document.pageCount)throw new Error('PDF page count differs from notebook');
+ page=project.document.pages[0].number;await showPage();renderLists();$('status').textContent='Saved';
+}
+async function showPage(){
+ draft=null;start=null;
+ if(find(selected)?.page!==page){selected=null;$('editor').className='empty';$('editor').textContent='Drag a rectangle or select an overlay.'}
+ const sequence=++renderSequence,number=page;renderedPage=null;$('status').textContent='Rendering…';
+ try{
+ const canvas=await renderPage(number,180);if(sequence!==renderSequence)return;
+ const p=project.document.pages.find(x=>x.number===number);img.width=canvas.width;img.height=canvas.height;img.getContext('2d').drawImage(canvas,0,0);
+ svg.setAttribute('viewBox',`0 0 ${p.widthPoints} ${p.heightPoints}`);svg.style.width=img.width+'px';svg.style.height=img.height+'px';renderedPage=number;draw();fit();$('status').textContent='Saved';
+ }catch(e){if(sequence===renderSequence){img.width=0;img.height=0;svg.innerHTML='';error(e)}}
+}
function apply(){stage.style.transform=`translate(${pan.x}px,${pan.y}px) scale(${scale})`;$('zoom').textContent=Math.round(scale*100)+'%';}
function fit(){scale=Math.min((viewer.clientWidth-30)/img.width,(viewer.clientHeight-30)/img.height);pan={x:15,y:15};apply()}
function fitWidth(){scale=(viewer.clientWidth-30)/img.width;pan={x:15,y:15};apply()}
function point(e){const r=svg.getBoundingClientRect(),p=project.document.pages.find(x=>x.number===page);return{x:(e.clientX-r.left)/r.width*p.widthPoints,y:(e.clientY-r.top)/r.height*p.heightPoints}}
function draw(){svg.innerHTML='';const related=new Set(project.relations.filter(r=>r.fromId===selected||r.toId===selected).flatMap(r=>[r.fromId,r.toId]));const all=[...project.regions.filter(x=>x.page===page).map(x=>({...x,category:x.type,_kind:'region'})),...project.annotations.filter(x=>x.page===page).map(x=>({...x,_kind:'annotation'}))];for(const x of all){const r=document.createElementNS('http://www.w3.org/2000/svg','rect');for(const [k,v] of Object.entries({x:x.bounds.x,y:x.bounds.y,width:x.bounds.width,height:x.bounds.height}))r.setAttribute(k,v);r.setAttribute('class',`box ${x.category} ${related.has(x.id)?'related':''} ${selected===x.id?'selected':''}`);r.onclick=e=>{e.stopPropagation();selected=x.id;edit(x);draw()};svg.appendChild(r)}if(draft){const r=document.createElementNS('http://www.w3.org/2000/svg','rect');for(const [k,v] of Object.entries(draft))r.setAttribute(k,v);r.setAttribute('class','draft');svg.appendChild(r)}}
-function renderLists(){$('pages').innerHTML=project.document.pages.map(p=>`<button class="page" data-page="${p.number}"><img src="/api/thumb/${p.number}.png" alt="Page ${p.number} thumbnail"><span>Page ${p.number}</span></button>${project.regions.filter(r=>r.page===p.number).map(r=>`<div class="region" data-id="${r.id}">${esc(r.name)}</div>`).join('')}`).join('');document.querySelectorAll('[data-page]').forEach(x=>x.onclick=()=>{page=+x.dataset.page;showPage()});document.querySelectorAll('[data-id]').forEach(x=>x.onclick=()=>{selected=x.dataset.id;const item=find(selected);page=item.page;showPage();edit(item)});$('tree').textContent=project.relations.map(r=>`${r.fromId}\n └─ ${r.kind} -> ${r.toId}`).join('\n')||'No relationships yet.'}
+function renderLists(){$('pages').innerHTML=project.document.pages.map(p=>`<button class="page" data-page="${p.number}"><img data-thumb="${p.number}" alt="Page ${p.number} thumbnail"><span>Page ${p.number}</span></button>${project.regions.filter(r=>r.page===p.number).map(r=>`<div class="region" data-id="${r.id}">${esc(r.name)}</div>`).join('')}`).join('');document.querySelectorAll('[data-thumb]').forEach(x=>thumbnail(+x.dataset.thumb).then(url=>x.src=url).catch(error));document.querySelectorAll('[data-page]').forEach(x=>x.onclick=()=>{page=+x.dataset.page;showPage()});document.querySelectorAll('[data-id]').forEach(x=>x.onclick=()=>{selected=x.dataset.id;const item=find(selected);page=item.page;showPage();edit(item)});$('tree').textContent=project.relations.map(r=>`${r.fromId}\n └─ ${r.kind} -> ${r.toId}`).join('\n')||'No relationships yet.'}
function find(id){return project.regions.find(x=>x.id===id)||project.annotations.find(x=>x.id===id)}
function esc(v){return String(v??'').replace(/[&<>\"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]))}
function options(values,current){return values.map(x=>`<option ${x===current?'selected':''}>${x}</option>`).join('')}
function edit(item){const region=item._kind==='region'||project.regions.includes(item);$('editor').className='form';$('editor').innerHTML=`<label>ID<input id="e-id" value="${esc(item.id)}" disabled></label><label>Label<input id="e-label" value="${esc(item.label||item.name)}"></label>${region?`<label>Type<select id="e-category">${options(['View','Detail','Section','NoteBlock','DimensionCluster','Keepout','DatumArea','Other'],item.type)}</select></label>`:`<label>Category<select id="e-category">${options(enums.category,item.category)}</select></label><label>Classification<select id="e-semantic">${options(enums.semantic,item.semanticClass)}</select></label>`}<label>Confidence<select id="e-confidence">${options(enums.confidence,item.confidence)}</select></label><label>Note<textarea id="e-note">${esc(item.note||item.notes)}</textarea></label>${!region&&item.category==='Dimension'?`<label>Value text<input id="e-value" value="${esc(item.dimension?.valueText)}"></label><label>Dimension type<select id="e-dtype">${options(enums.dimension,item.dimension?.type||'Unknown')}</select></label>`:''}<button id="save">Save</button><hr><label>Relation target<select id="rel-target">${[...project.regions,...project.annotations].filter(x=>x.id!==item.id).map(x=>`<option value="${x.id}">${esc(x.id)}</option>`).join('')}</select></label><label>Relation kind<select id="rel-kind">${options(['Targets','ReferencedFrom','LocatedIn','DetailOf','SectionOf','KeepoutFor','CoordinateIn','RelatedTo'],'RelatedTo')}</select></label><button id="add-rel">Add relation</button>`;$('save').onclick=async()=>{if(region){item.name=$('e-label').value;item.type=$('e-category').value;item.notes=$('e-note').value}else{item.label=$('e-label').value;item.category=$('e-category').value;item.semanticClass=$('e-semantic').value;item.note=$('e-note').value;if(item.category==='Dimension')item.dimension={valueText:$('e-value')?.value||'?',parsedValue:null,units:null,type:$('e-dtype')?.value||'Unknown',axis:null,datumId:null,sourceFeatureId:null,targetFeatureId:null,interpretation:null}}item.confidence=$('e-confidence').value;await save();draw();renderLists()};$('add-rel').onclick=async()=>{const to=$('rel-target').value;if(!to)return;project.relations.push({id:`rel-${item.id}-${to}-${project.relations.length+1}`,fromId:item.id,toId:to,kind:$('rel-kind').value,note:null,confidence:'High'});await save();renderLists()}}
async function save(){$('status').textContent='Saving…';const r=await fetch('/api/project',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(project)});if(!r.ok){$('status').textContent='Save failed';throw new Error(await r.text())}project=await r.json();$('status').textContent='Saved'}
-function create(kind){if(!draft)return;const prefix=kind==='View'?'View':kind;let ordinal=1,id=`${prefix}.p${page}.${ordinal}`;while(find(id))id=`${prefix}.p${page}.${++ordinal}`;const label=id;if(kind==='View')project.regions.push({id,name:label,page,bounds:draft,type:'View',parentRegionId:null,notes:null,confidence:'High',cropFile:null});else project.annotations.push({id,label,category:kind,page,bounds:draft,regionId:null,note:null,originalText:null,confidence:kind==='Question'?'Unresolved':'High',semanticClass:'Unknown',tags:[],aliases:[],dimension:kind==='Dimension'?{valueText:'?',parsedValue:null,units:null,type:'Unknown',axis:null,datumId:null,sourceFeatureId:null,targetFeatureId:null,interpretation:null}:null,pass:null});draft=null;selected=id;save().then(()=>{draw();renderLists();edit(find(id));$('e-label')?.focus()})}
-svg.onpointerdown=e=>{if(e.shiftKey){panStart={x:e.clientX,y:e.clientY,pan:{...pan}};return}start=point(e);draft={x:start.x,y:start.y,width:0.1,height:0.1};draw()};svg.onpointermove=e=>{if(panStart){pan={x:panStart.pan.x+e.clientX-panStart.x,y:panStart.pan.y+e.clientY-panStart.y};apply();return}if(!start)return;const p=point(e);draft={x:Math.min(start.x,p.x),y:Math.min(start.y,p.y),width:Math.max(.1,Math.abs(p.x-start.x)),height:Math.max(.1,Math.abs(p.y-start.y))};draw()};svg.onpointerup=()=>{if(panStart){panStart=null;$('status').textContent='Panned';return}start=null;$('status').textContent='Press D for dimension, V for view, or Q for question'};
+function create(kind){if(!draft||renderedPage!==page)return;const prefix=kind==='View'?'View':kind;let ordinal=1,id=`${prefix}.p${page}.${ordinal}`;while(find(id))id=`${prefix}.p${page}.${++ordinal}`;const label=id;if(kind==='View')project.regions.push({id,name:label,page,bounds:draft,type:'View',parentRegionId:null,notes:null,confidence:'High',cropFile:null});else project.annotations.push({id,label,category:kind,page,bounds:draft,regionId:null,note:null,originalText:null,confidence:kind==='Question'?'Unresolved':'High',semanticClass:'Unknown',tags:[],aliases:[],dimension:kind==='Dimension'?{valueText:'?',parsedValue:null,units:null,type:'Unknown',axis:null,datumId:null,sourceFeatureId:null,targetFeatureId:null,interpretation:null}:null,pass:null});draft=null;selected=id;save().then(()=>{draw();renderLists();edit(find(id));$('e-label')?.focus()})}
+svg.onpointerdown=e=>{if(renderedPage!==page)return;if(e.shiftKey){panStart={x:e.clientX,y:e.clientY,pan:{...pan}};return}start=point(e);draft={x:start.x,y:start.y,width:0.1,height:0.1};draw()};svg.onpointermove=e=>{if(panStart){pan={x:panStart.pan.x+e.clientX-panStart.x,y:panStart.pan.y+e.clientY-panStart.y};apply();return}if(!start)return;const p=point(e);draft={x:Math.min(start.x,p.x),y:Math.min(start.y,p.y),width:Math.max(.1,Math.abs(p.x-start.x)),height:Math.max(.1,Math.abs(p.y-start.y))};draw()};svg.onpointerup=()=>{if(panStart){panStart=null;$('status').textContent='Panned';return}start=null;$('status').textContent='Press D for dimension, V for view, or Q for question'};
viewer.onwheel=e=>{e.preventDefault();scale=Math.max(.1,Math.min(5,scale*(e.deltaY<0?1.12:.89)));apply()};
document.onkeydown=e=>{if(['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName))return;if(e.key.toLowerCase()==='d')create('Dimension');if(e.key.toLowerCase()==='v')create('View');if(e.key.toLowerCase()==='q')create('Question')};
-$('fit').onclick=fit;$('width').onclick=fitWidth;$('plus').onclick=()=>{scale=Math.min(5,scale*1.2);apply()};$('minus').onclick=()=>{scale=Math.max(.1,scale/1.2);apply()};$('preview').onclick=async()=>{$('editor').className='';$('editor').innerHTML=`<pre>${esc(await (await fetch('/api/export.md')).text())}</pre>`};load();
+function download(blob,name){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000)}
+$('crop').onclick=async()=>{
+ try{
+ if(renderedPage!==page)throw new Error('Wait for the page to finish rendering');
+ const number=page,item=find(selected),bounds=structuredClone(draft||item?.bounds);if(!bounds)throw new Error('Select a note or drag a crop rectangle first');
+ const p=project.document.pages.find(x=>x.number===number);
+ if(![bounds.x,bounds.y,bounds.width,bounds.height].every(Number.isFinite)||bounds.x<0||bounds.y<0||bounds.width<=0||bounds.height<=0||bounds.x+bounds.width>p.widthPoints||bounds.y+bounds.height>p.heightPoints)throw new Error('Crop is outside the page');
+ const dpi=300,source=await renderPage(number,dpi),x=Math.floor(bounds.x*dpi/72),y=Math.floor(bounds.y*dpi/72),canvas=document.createElement('canvas');
+ canvas.width=Math.ceil((bounds.x+bounds.width)*dpi/72)-x;canvas.height=Math.ceil((bounds.y+bounds.height)*dpi/72)-y;
+ canvas.getContext('2d').drawImage(source,x,y,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
+ const name=(item?.id||`page-${number}-crop`).replace(/[^a-z0-9_.-]/gi,'_'),fileName=name+'.png';
+ const metadata={page:number,bounds,documentSha256:project.document.sha256,rendererVersion:'PDF.js-'+pdfjs.version,dpi,fileName};
+ const blob=await new Promise(resolve=>canvas.toBlob(resolve,'image/png'));if(!blob)throw new Error('PNG encoding failed');
+ download(blob,fileName);download(new Blob([JSON.stringify(metadata,null,2)+'\n'],{type:'application/json'}),name+'.crop.json');$('status').textContent='Crop exported (PNG and source metadata)';
+ }catch(e){error(e)}
+};
+$('fit').onclick=fit;$('width').onclick=fitWidth;$('plus').onclick=()=>{scale=Math.min(5,scale*1.2);apply()};$('minus').onclick=()=>{scale=Math.max(.1,scale/1.2);apply()};$('preview').onclick=async()=>{$('editor').className='';$('editor').innerHTML=`<pre>${esc(await (await fetch('/api/export.md')).text())}</pre>`};load().catch(error);
</script>
</body></html>
""";
diff --git a/Aetheris.Drawing/DrawingPdf.cs b/Aetheris.Drawing/DrawingPdf.cs
index 69150e24..82ef0a7b 100644
--- a/Aetheris.Drawing/DrawingPdf.cs
+++ b/Aetheris.Drawing/DrawingPdf.cs
@@ -1,13 +1,16 @@
-using System.Drawing;
using System.Security.Cryptography;
using System.Text.Json;
-using PDFtoImage;
+using UglyToad.PdfPig;
+using UglyToad.PdfPig.Tokens;
+using UglyToad.PdfPig.Content;
+using UglyToad.PdfPig.Parser.Parts;
namespace Aetheris.Drawing;
public static class DrawingPdf
{
- public const string RendererVersion = "PDFtoImage-5.4.0/PDFium";
+ public const string RendererVersion = "PDF.js-6.4.299";
+ public const string InspectorVersion = "PdfPig-0.1.16";
public static string Hash(string pdfPath) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(pdfPath))).ToLowerInvariant();
@@ -15,43 +18,108 @@ public static class DrawingPdf
{
RequirePdf(pdfPath);
var bytes = File.ReadAllBytes(pdfPath);
- var count = Conversion.GetPageCount(bytes);
- var sizes = Conversion.GetPageSizes(bytes);
- var pages = sizes.Select((size, index) => new DrawingPage(index + 1, size.Width, size.Height)).ToArray();
- if (pages.Length != count) throw new DrawingNotesException("drawing-pdf-page-metadata-mismatch", "PDF renderer returned inconsistent page metadata.");
- return new(Path.GetFileName(pdfPath), Hash(pdfPath), count, pages, title, visibleDate, visibleRevision, sheets, "PDFium", RendererVersion);
+ try
+ {
+ using var pdf = PdfDocument.Open(bytes);
+ var pages = pdf.GetPages().Select(page =>
+ {
+ // Read the page-tree boxes explicitly: PdfPig 0.1.16's Page.Width
+ // loses an inherited CropBox. Its tokenizer remains the PDF authority.
+ var unit = 1d;
+ if (page.Dictionary.TryGet(NameToken.Create("UserUnit"), out var token))
+ {
+ var number = Resolve<NumericToken>(pdf, token, page.Number);
+ if (!double.IsFinite(number.Double) || number.Double <= 0)
+ throw new DrawingNotesException("drawing-pdf-user-unit-unsupported", $"Page {page.Number} has an unsupported UserUnit. A positive number is required.");
+ unit = number.Double;
+ }
+ var (w, h) = VisibleSize(pdf, page);
+ var width = w * unit;
+ var height = h * unit;
+ if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0)
+ throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has invalid visible bounds.");
+ return new DrawingPage(page.Number, width, height, page.Rotation.Value, unit);
+ }).ToArray();
+ if (pages.Length == 0) throw new DrawingNotesException("drawing-pdf-empty", "PDF has no pages.");
+ return new(Path.GetFileName(pdfPath), Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(), pages.Length, pages, title, visibleDate, visibleRevision, sheets, "PDF.js", RendererVersion, "PdfPig", InspectorVersion);
+ }
+ catch (Exception e) when (e is not DrawingNotesException && (e is UglyToad.PdfPig.Core.PdfDocumentFormatException or InvalidOperationException or ArgumentException or NotSupportedException))
+ {
+ throw new DrawingNotesException("drawing-pdf-inspection-failed", $"Cannot inspect PDF '{Path.GetFileName(pdfPath)}': {e.Message}");
+ }
}
+ private static (double Width, double Height) VisibleSize(PdfDocument pdf, Page page)
+ {
+ var media = Box(NameToken.MediaBox) ?? throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has no MediaBox.");
+ var crop = Box(NameToken.CropBox) ?? media;
+ var width = Math.Min(media[2], crop[2]) - Math.Max(media[0], crop[0]);
+ var height = Math.Min(media[3], crop[3]) - Math.Max(media[1], crop[1]);
+ if (width <= 0 || height <= 0) throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has an empty visible CropBox.");
+ return page.Rotation.Value is 90 or 270 ? (height, width) : (width, height);
+
+ double[]? Box(NameToken key)
+ {
+ var dictionary = page.Dictionary;
+ var visited = new HashSet<DictionaryToken>();
+ while (visited.Add(dictionary))
+ {
+ if (dictionary.TryGet(key, out var token))
+ {
+ var array = Resolve<ArrayToken>(pdf, token, page.Number);
+ if (array.Length != 4) throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has an invalid {key.Data}.");
+ var values = array.Data.Select(t => Resolve<NumericToken>(pdf, t, page.Number).Double).ToArray();
+ if (values.Any(x => !double.IsFinite(x)) || values[2] <= values[0] || values[3] <= values[1])
+ throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has invalid {key.Data} coordinates.");
+ return values;
+ }
+ if (!dictionary.TryGet(NameToken.Parent, out var parent)) return null;
+ dictionary = Resolve<DictionaryToken>(pdf, parent, page.Number);
+ }
+ throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page.Number} has a cyclic page tree.");
+ }
+ }
+
+ private static T Resolve<T>(PdfDocument pdf, IToken token, int page) where T : class, IToken =>
+ DirectObjectFinder.Get<T>(token, pdf.Structure.TokenScanner)
+ ?? throw new DrawingNotesException("drawing-pdf-page-invalid", $"Page {page} contains a missing or invalid {typeof(T).Name} in its page metadata.");
+
public static DrawingNotesProject CreateProject(string pdfPath, string? name = null, string? title = null, string? visibleDate = null, string? visibleRevision = null, IReadOnlyList<string>? sheets = null)
{
var document = Inspect(pdfPath, title, visibleDate, visibleRevision, sheets);
return new DrawingNotesProject { Name = name ?? Path.GetFileNameWithoutExtension(pdfPath) + " — Drawing Notes", Document = document };
}
- public static void RenderPage(string pdfPath, int page, string outputPng, int dpi = 200)
+ public static void RenderPage(string pdfPath, int page, string outputPng, int dpi = 200, IDrawingPdfRasterizer? rasterizer = null)
{
var document = Inspect(pdfPath);
- RequirePage(document, page);
- if (dpi is < 36 or > 1200) throw new DrawingNotesException("drawing-render-dpi-invalid", "Render DPI must be between 36 and 1200.");
- Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPng))!);
- Conversion.SavePng(outputPng, File.ReadAllBytes(pdfPath), page - 1, options: new RenderOptions(Dpi: dpi, WithAnnotations: true, UseTiling: dpi >= 300));
+ var metadata = RequirePage(document, page);
+ RequireDpi(dpi);
+ RequireRasterizer(rasterizer).Render(pdfPath, metadata, outputPng, dpi, null);
}
- public static DrawingCropMetadata Crop(string pdfPath, int page, DrawingBounds bounds, string name, string outputPng, int dpi = 300)
+ public static DrawingCropMetadata Crop(string pdfPath, int page, DrawingBounds bounds, string name, string outputPng, int dpi = 300, IDrawingPdfRasterizer? rasterizer = null)
{
var document = Inspect(pdfPath);
var pageMetadata = RequirePage(document, page);
+ RequireDpi(dpi);
bounds.Validate(name);
- if (bounds.Right > pageMetadata.WidthPoints + 0.01 || bounds.Bottom > pageMetadata.HeightPoints + 0.01)
+ if (bounds.Right > pageMetadata.WidthPoints || bounds.Bottom > pageMetadata.HeightPoints)
throw new DrawingNotesException("drawing-bounds-outside-page", $"Crop {bounds} exceeds page {page}.");
- Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPng))!);
- var clip = new RectangleF((float)bounds.X, (float)bounds.Y, (float)bounds.Width, (float)bounds.Height);
- Conversion.SavePng(outputPng, File.ReadAllBytes(pdfPath), page - 1, options: new RenderOptions(Dpi: dpi, Bounds: clip, DpiRelativeToBounds: true, WithAnnotations: true));
- var metadata = new DrawingCropMetadata(page, bounds, document.Sha256, RendererVersion, dpi, Path.GetFileName(outputPng));
+ var renderer = RequireRasterizer(rasterizer);
+ renderer.Render(pdfPath, pageMetadata, outputPng, dpi, bounds);
+ var metadata = new DrawingCropMetadata(page, bounds, document.Sha256, renderer.Version, dpi, Path.GetFileName(outputPng));
File.WriteAllText(Path.ChangeExtension(outputPng, ".crop.json"), JsonSerializer.Serialize(metadata, DrawingNotesPersistence.JsonOptions) + "\n");
return metadata;
}
+ private static IDrawingPdfRasterizer RequireRasterizer(IDrawingPdfRasterizer? renderer) => renderer ?? throw new DrawingNotesException("drawing-renderer-required", "PNG rendering requires an explicitly selected renderer. Use the Drawing Notes browser UI (PDF.js), or pass --renderer <path-to-pdftoppm> for headless rendering. No native renderer is bundled.");
+
+ private static void RequireDpi(int dpi)
+ {
+ if (dpi is < 36 or > 1200) throw new DrawingNotesException("drawing-render-dpi-invalid", "Render DPI must be between 36 and 1200.");
+ }
+
private static DrawingPage RequirePage(DrawingSourceDocument document, int page) => document.Pages.SingleOrDefault(x => x.Number == page)
?? throw new DrawingNotesException("drawing-page-invalid", $"Page {page} is outside 1..{document.PageCount}.");
diff --git a/Aetheris.Drawing/Model.cs b/Aetheris.Drawing/Model.cs
index 0d84f40e..1214fc8f 100644
--- a/Aetheris.Drawing/Model.cs
+++ b/Aetheris.Drawing/Model.cs
@@ -31,7 +31,7 @@ public sealed record DrawingBounds(double X, double Y, double Width, double Heig
public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{X:0.##},{Y:0.##},{Width:0.##},{Height:0.##}]");
}
-public sealed record DrawingPage(int Number, double WidthPoints, double HeightPoints);
+public sealed record DrawingPage(int Number, double WidthPoints, double HeightPoints, int RotationDegrees = 0, double UserUnit = 1);
public sealed record DrawingSourceDocument(
string FileName,
@@ -42,8 +42,10 @@ public sealed record DrawingSourceDocument(
string? VisibleDate = null,
string? VisibleRevision = null,
IReadOnlyList<string>? SheetIdentifiers = null,
- string Renderer = "PDFium",
- string RendererVersion = "PDFtoImage-5.4.0");
+ string Renderer = "PDF.js",
+ string RendererVersion = DrawingPdf.RendererVersion,
+ string? Inspector = null,
+ string? InspectorVersion = null);
public sealed record DrawingRegion(
string Id,
diff --git a/Aetheris.Drawing/PopplerPdfRasterizer.cs b/Aetheris.Drawing/PopplerPdfRasterizer.cs
new file mode 100644
index 00000000..38f8e1b6
--- /dev/null
+++ b/Aetheris.Drawing/PopplerPdfRasterizer.cs
@@ -0,0 +1,82 @@
+using System.Buffers.Binary;
+using System.Diagnostics;
+using System.Globalization;
+
+namespace Aetheris.Drawing;
+
+public interface IDrawingPdfRasterizer
+{
+ string Version { get; }
+ void Render(string pdfPath, DrawingPage page, string outputPng, int dpi, DrawingBounds? bounds);
+}
+
+/// <summary>An opt-in external executable, never installed or bundled by Aetheris.</summary>
+public sealed class PopplerPdfRasterizer : IDrawingPdfRasterizer
+{
+ private readonly string executable;
+ public string Version { get; }
+
+ public PopplerPdfRasterizer(string executablePath)
+ {
+ executable = Path.GetFullPath(executablePath);
+ if (!File.Exists(executable)) throw new DrawingNotesException("drawing-renderer-missing", $"pdftoppm executable was not found: {executable}");
+ var version = Run(["-v"]).Trim().Split('\n')[0].Trim();
+ if (!version.StartsWith("pdftoppm version ", StringComparison.Ordinal))
+ throw new DrawingNotesException("drawing-renderer-invalid", "The selected executable must be Poppler pdftoppm.");
+ Version = version;
+ }
+
+ public void Render(string pdfPath, DrawingPage page, string outputPng, int dpi, DrawingBounds? bounds)
+ {
+ // Explicit pixel dimensions preserve physical UserUnit and rotated CropBox
+ // semantics even on Poppler versions with different default page sizing.
+ var width = checked((int)Math.Ceiling(page.WidthPoints * dpi / 72));
+ var height = checked((int)Math.Ceiling(page.HeightPoints * dpi / 72));
+ var temporary = Path.Combine(Path.GetTempPath(), $"aetheris-pdf-{Guid.NewGuid():N}");
+ Directory.CreateDirectory(temporary);
+ try
+ {
+ var prefix = Path.Combine(temporary, "page");
+ // pdftoppm scales before rotating. Crop coordinates apply afterwards.
+ var swapped = page.RotationDegrees is 90 or 270;
+ var args = new List<string> { "-png", "-singlefile", "-f", N(page.Number), "-l", N(page.Number), "-cropbox", "-scale-to-x", N(swapped ? height : width), "-scale-to-y", N(swapped ? width : height) };
+ if (bounds is not null)
+ {
+ var x = (int)Math.Floor(bounds.X * dpi / 72);
+ var y = (int)Math.Floor(bounds.Y * dpi / 72);
+ width = (int)Math.Ceiling(bounds.Right * dpi / 72) - x;
+ height = (int)Math.Ceiling(bounds.Bottom * dpi / 72) - y;
+ args.AddRange(["-x", N(x), "-y", N(y), "-W", N(width), "-H", N(height)]);
+ }
+ args.Add(Path.GetFullPath(pdfPath));
+ args.Add(prefix);
+ Run(args);
+ var bytes = File.ReadAllBytes(prefix + ".png");
+ if (bytes.Length < 24 || !bytes.AsSpan(0, 8).SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }) ||
+ BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(16, 4)) != width || BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(20, 4)) != height)
+ throw new DrawingNotesException("drawing-render-output-invalid", "Renderer did not return a PNG with the requested page/crop dimensions.");
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPng))!);
+ File.WriteAllBytes(outputPng, bytes);
+ }
+ finally { Directory.Delete(temporary, recursive: true); }
+ }
+
+ private string Run(IEnumerable<string> args)
+ {
+ var info = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true };
+ foreach (var arg in args) info.ArgumentList.Add(arg);
+ using var process = Process.Start(info) ?? throw new DrawingNotesException("drawing-renderer-start-failed", "Could not start pdftoppm.");
+ var stdout = process.StandardOutput.ReadToEndAsync();
+ var stderr = process.StandardError.ReadToEndAsync();
+ if (!process.WaitForExit(60_000))
+ {
+ process.Kill(entireProcessTree: true);
+ process.WaitForExit();
+ throw new DrawingNotesException("drawing-renderer-timeout", "pdftoppm exceeded the 60 second render limit.");
+ }
+ var output = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
+ if (process.ExitCode != 0) throw new DrawingNotesException("drawing-renderer-failed", $"pdftoppm exited {process.ExitCode}: {output.Trim()}");
+ return output;
+ }
+ private static string N(int value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/Aetheris.Drawing/Web/README.md b/Aetheris.Drawing/Web/README.md
new file mode 100644
index 00000000..28216ea1
--- /dev/null
+++ b/Aetheris.Drawing/Web/README.md
@@ -0,0 +1,21 @@
+# Drawing Notes browser dependency
+
+`package.json` and `package-lock.json` pin PDF.js and its integrity hash. Build
+restores it automatically with `npm ci --ignore-scripts --omit=optional` when
+missing or when the manifests change. Source builds require Node/npm; published
+tools do not. The optional native Node canvas package is never installed.
+
+The downloaded `node_modules/` distribution and the former `pdfjs/` vendor folder
+are ignored by Git. Do not commit downloaded distributions or archives here.
+
+The project explicitly embeds only the minified browser module and worker,
+runtime CMaps/fonts/decoders/ICC profiles, and their licenses. It excludes source
+maps, legacy builds, viewers, examples, types, package metadata and Node tooling.
+The two modules retain their existing `/pdfjs/build/pdf.mjs` and
+`/pdfjs/build/pdf.worker.mjs` URLs. All runtime assets are served locally, with no
+CDN requests. Browser WebAssembly decoders are portable assets, not OS libraries.
+
+Update both manifests and `DrawingPdf.RendererVersion` together when upgrading.
+After a Release CLI build, run `node scripts/test-drawing-notes-browser.mjs` to
+check the real PDF, annotations and crop exports. Set `AETHERIS_PLAYWRIGHT_MODULE`
+and `AETHERIS_BROWSER_PATH` if needed for local Playwright/browser installations.
diff --git a/Aetheris.Drawing/Web/package-lock.json b/Aetheris.Drawing/Web/package-lock.json
new file mode 100644
index 00000000..5cc37c0f
--- /dev/null
+++ b/Aetheris.Drawing/Web/package-lock.json
@@ -0,0 +1,292 @@
+{
+ "name": "aetheris-drawing-browser-assets",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "aetheris-drawing-browser-assets",
+ "version": "1.0.0",
+ "dependencies": {
+ "pdfjs-dist": "6.4.299"
+ }
+ },
+ "node_modules/@napi-rs/canvas": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.13.tgz",
+ "integrity": "sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==",
+ "license": "MIT",
+ "optional": true,
+ "workspaces": [
+ "e2e/*"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "optionalDependencies": {
+ "@napi-rs/canvas-android-arm64": "1.0.13",
+ "@napi-rs/canvas-darwin-arm64": "1.0.13",
+ "@napi-rs/canvas-darwin-x64": "1.0.13",
+ "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.13",
+ "@napi-rs/canvas-linux-arm64-gnu": "1.0.13",
+ "@napi-rs/canvas-linux-arm64-musl": "1.0.13",
+ "@napi-rs/canvas-linux-riscv64-gnu": "1.0.13",
+ "@napi-rs/canvas-linux-x64-gnu": "1.0.13",
+ "@napi-rs/canvas-linux-x64-musl": "1.0.13",
+ "@napi-rs/canvas-win32-arm64-msvc": "1.0.13",
+ "@napi-rs/canvas-win32-x64-msvc": "1.0.13"
+ }
+ },
+ "node_modules/@napi-rs/canvas-android-arm64": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.13.tgz",
+ "integrity": "sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-darwin-arm64": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.13.tgz",
+ "integrity": "sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-darwin-x64": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.13.tgz",
+ "integrity": "sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.13.tgz",
+ "integrity": "sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.13.tgz",
+ "integrity": "sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm64-musl": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.13.tgz",
+ "integrity": "sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.13.tgz",
+ "integrity": "sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==",
+ "cpu": [
+ "riscv64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-x64-gnu": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.13.tgz",
+ "integrity": "sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-x64-musl": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.13.tgz",
+ "integrity": "sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-win32-arm64-msvc": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.13.tgz",
+ "integrity": "sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-win32-x64-msvc": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.13.tgz",
+ "integrity": "sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/pdfjs-dist": {
+ "version": "6.4.299",
+ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.4.299.tgz",
+ "integrity": "sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=22.13.0 || >=24"
+ },
+ "optionalDependencies": {
+ "@napi-rs/canvas": "^1.0.10"
+ }
+ }
+ }
+}
diff --git a/Aetheris.Drawing/Web/package.json b/Aetheris.Drawing/Web/package.json
new file mode 100644
index 00000000..53a8ec73
--- /dev/null
+++ b/Aetheris.Drawing/Web/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "aetheris-drawing-browser-assets",
+ "private": true,
+ "version": "1.0.0",
+ "description": "Build-time browser PDF assets; no Node renderer or native canvas dependency.",
+ "dependencies": {
+ "pdfjs-dist": "6.4.299"
+ }
+}
diff --git a/Aetheris.Firmament.FrictionLab/Aetheris.Firmament.FrictionLab.csproj b/Aetheris.Firmament.FrictionLab/Aetheris.Firmament.FrictionLab.csproj
index 416d92d0..7b3527ec 100644
--- a/Aetheris.Firmament.FrictionLab/Aetheris.Firmament.FrictionLab.csproj
+++ b/Aetheris.Firmament.FrictionLab/Aetheris.Firmament.FrictionLab.csproj
@@ -1,6 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
+ <!-- Invoked through dotnet or the main CLI; do not transitively ship an OS apphost. -->
+ <UseAppHost Condition="'$(SelfContained)' != 'true'">false</UseAppHost>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
diff --git a/Aetheris.Kernel.StandardLibrary.Tests/Aetheris.Kernel.StandardLibrary.Tests.csproj b/Aetheris.Kernel.StandardLibrary.Tests/Aetheris.Kernel.StandardLibrary.Tests.csproj
index 4330806b..2b64b73d 100644
--- a/Aetheris.Kernel.StandardLibrary.Tests/Aetheris.Kernel.StandardLibrary.Tests.csproj
+++ b/Aetheris.Kernel.StandardLibrary.Tests/Aetheris.Kernel.StandardLibrary.Tests.csproj
@@ -3,4 +3,5 @@
<ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" /><PackageReference Include="xunit" Version="2.9.2" /><PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" /></ItemGroup>
<ItemGroup><Using Include="Xunit" /></ItemGroup>
<ItemGroup><ProjectReference Include="..\Aetheris.Kernel.StandardLibrary\Aetheris.Kernel.StandardLibrary.csproj" /></ItemGroup>
+ <ItemGroup><ProjectReference Include="../Aetheris.Materials.Sqlite/Aetheris.Materials.Sqlite.csproj" /></ItemGroup>
</Project>
diff --git a/Aetheris.Kernel.StandardLibrary.Tests/MaterialCatalogTests.cs b/Aetheris.Kernel.StandardLibrary.Tests/MaterialCatalogTests.cs
index 5c5b473b..60b278c6 100644
--- a/Aetheris.Kernel.StandardLibrary.Tests/MaterialCatalogTests.cs
+++ b/Aetheris.Kernel.StandardLibrary.Tests/MaterialCatalogTests.cs
@@ -1,6 +1,6 @@
using Aetheris.Kernel.StandardLibrary.Materials;
using Aetheris.Kernel.StandardLibrary.Materials.Database;
-using Microsoft.EntityFrameworkCore;
+using System.Text.Json;
namespace Aetheris.Kernel.StandardLibrary.Tests;
@@ -32,7 +32,7 @@ public sealed class MaterialCatalogTests
MaterialCatalogDatabase.Recreate(path);
MaterialCatalogDatabase.Recreate(secondPath);
Assert.Equal(File.ReadAllBytes(path), File.ReadAllBytes(secondPath));
- using var catalog = new MaterialCatalog(path);
+ using var catalog = SqliteMaterialCatalog.Open(path);
Assert.Equal(MaterialCatalog.ExpectedSeedMaterialCount, catalog.Materials.Count());
Assert.NotNull(catalog.GetById("standard", "aluminum/5052-h32"));
}
@@ -43,6 +43,19 @@ public sealed class MaterialCatalogTests
}
}
+ [Fact]
+ public void ManagedDefault_PreservesEverySqliteValueIdentityAndProvenance()
+ {
+ using var managed = MaterialCatalog.OpenDefault();
+ using var legacy = SqliteMaterialCatalog.Open(MaterialCatalogDatabase.DefaultDatabasePath);
+ foreach (var item in legacy.Materials)
+ {
+ var expected = legacy.GetById(item.CatalogId, item.StableId);
+ var actual = managed.GetById(item.CatalogId, item.StableId);
+ Assert.Equal(JsonSerializer.Serialize(expected), JsonSerializer.Serialize(actual));
+ }
+ }
+
[Fact]
public void LinqAndResolver_PreserveAlloyTemperDistinctionsAndTypedSiProperties()
{
diff --git a/Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj b/Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj
index db10a835..48ee5bea 100644
--- a/Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj
+++ b/Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj
@@ -1,29 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
- <ImplicitUsings>enable</ImplicitUsings>
- <Nullable>enable</Nullable>
- <InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors</InterceptorsNamespaces>
- <Description>Standard Forge Templates and the versioned engineering material catalog for Aetheris.</Description>
+ <Description>Standard Forge Templates and the versioned managed engineering material catalog for Aetheris.</Description>
</PropertyGroup>
-
<ItemGroup>
- <ProjectReference Include="..\Aetheris.Forge\Aetheris.Forge.csproj" />
- <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
- <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
- </ItemGroup>
-
- <ItemGroup>
- <Content Include="Materials\Database\aetheris-materials-x1.sqlite"
- Condition="Exists('Materials\Database\aetheris-materials-x1.sqlite')"
- CopyToOutputDirectory="PreserveNewest"
- CopyToPublishDirectory="PreserveNewest"
- Pack="true"
- PackagePath="contentFiles/any/any/Materials/aetheris-materials-x1.sqlite"
- PackageCopyToOutput="true"
- Link="Materials\aetheris-materials-x1.sqlite" />
- <None Include="build\Aetheris.Kernel.StandardLibrary.targets"
- Pack="true"
- PackagePath="buildTransitive\Aetheris.Kernel.StandardLibrary.targets" />
+ <ProjectReference Include="../Aetheris.Forge/Aetheris.Forge.csproj" />
+ <InternalsVisibleTo Include="Aetheris.Materials.Sqlite" />
</ItemGroup>
</Project>
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalog.EFInterceptors.MaterialCatalogDbContext.cs b/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalog.EFInterceptors.MaterialCatalogDbContext.cs
deleted file mode 100644
index 9d87d969..00000000
--- a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalog.EFInterceptors.MaterialCatalogDbContext.cs
+++ /dev/null
@@ -1,361 +0,0 @@
-// <auto-generated />
-
-using Aetheris.Kernel.StandardLibrary.Materials;
-using Aetheris.Kernel.StandardLibrary.Materials.Database;
-using System;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
-using Microsoft.EntityFrameworkCore.Diagnostics;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
-using Microsoft.EntityFrameworkCore.Internal;
-using Microsoft.EntityFrameworkCore.Metadata;
-using Microsoft.EntityFrameworkCore.Query;
-using Microsoft.EntityFrameworkCore.Query.Internal;
-using Microsoft.EntityFrameworkCore.Storage;
-using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Data.Common;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
-
-#pragma warning disable EF9100 // Precompiled query is experimental
-#pragma warning disable CS9270 // EF 10 tooling emits the supported legacy location form.
-
-namespace Microsoft.EntityFrameworkCore.GeneratedInterceptors
-{
- file static class EntityFrameworkCoreInterceptors
- {
- #region Query1
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 41, 58)]
- public static global::System.Linq.IQueryable<TEntity> Query1_AsNoTracking1<TEntity>(this global::System.Linq.IQueryable<TEntity> source)
- where TEntity : class
- {
- var precompiledQueryContext = new PrecompiledQueryContext<TEntity>(((IInfrastructure<DbContext>)source).Instance);
- return precompiledQueryContext;
- }
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 41, 73)]
- public static TSource Query1_Single2<TSource>(this global::System.Linq.IQueryable<TSource> source, global::System.Linq.Expressions.Expression<global::System.Func<TSource,global::System.Boolean>> predicate)
- {
- var precompiledQueryContext = (PrecompiledQueryContext<TSource>)source;
- var queryContext = precompiledQueryContext.QueryContext;
- Query1_Executor ??= Query1_GenerateExecutor(precompiledQueryContext.DbContext, precompiledQueryContext.QueryContext);
- return ((Func<QueryContext, TSource>)(Query1_Executor))(queryContext);
- }
-
- private static object Query1_GenerateExecutor(DbContext dbContext, QueryContext queryContext)
- {
- var relationalModel = dbContext.Model.GetRelationalModel();
- var relationalTypeMappingSource = dbContext.GetService<IRelationalTypeMappingSource>();
- var materializerLiftableConstantContext = new RelationalMaterializerLiftableConstantContext(
- dbContext.GetService<ShapedQueryCompilingExpressionVisitorDependencies>(),
- dbContext.GetService<RelationalShapedQueryCompilingExpressionVisitorDependencies>(),
- dbContext.GetService<RelationalCommandBuilderDependencies>());
- var relationalCommandTemplate = ((IRelationalCommandTemplate)(new RelationalCommand(materializerLiftableConstantContext.CommandBuilderDependencies, "SELECT \"c\".\"Id\", \"c\".\"CatalogId\", \"c\".\"SchemaVersion\", \"c\".\"SeedVersion\"\r\nFROM \"CatalogMetadata\" AS \"c\"\r\nWHERE \"c\".\"CatalogId\" = 'standard'\r\nLIMIT 2", "SELECT \"c\".\"Id\", \"c\".\"CatalogId\", \"c\".\"SchemaVersion\", \"c\".\"SeedVersion\"\r\nFROM \"CatalogMetadata\" AS \"c\"\r\nWHERE \"c\".\"CatalogId\" = 'standard'\r\nLIMIT 2", new IRelationalParameter[] { })));
- var emptyValueBuffer = ValueBuffer.Empty;
- var emptySnapshot = Snapshot.Empty;
- var materialCatalogMetadataEntityEntityType = materializerLiftableConstantContext.Dependencies.Model.FindEntityType("Aetheris.Kernel.StandardLibrary.Materials.Database.MaterialCatalogMetadataEntity");
- var materialCatalogMetadataEntityEntityType0 = ((RuntimeEntityType)(materialCatalogMetadataEntityEntityType));
- var materialCatalogMetadataEntityPrimaryKeyProperties = materialCatalogMetadataEntityEntityType.FindPrimaryKey().Properties;
- return MaterialCatalogMetadataEntity (QueryContext queryContext) => SingleQueryingEnumerable.Create(((RelationalQueryContext)(queryContext)), IRelationalCommandTemplate (Dictionary<string, object> parameters) => relationalCommandTemplate, (ReaderColumn[])(null), MaterialCatalogMetadataEntity (QueryContext queryContext, DbDataReader dataReader, ResultContext resultContext, SingleQueryResultCoordinator resultCoordinator) =>
-{
- IEntityType entityType1 = default(IEntityType);
- var materializationContext1 = new MaterializationContext(in emptyValueBuffer, queryContext.Context);
- var instance1 = default(MaterialCatalogMetadataEntity);
- if (((object)(dataReader.GetInt32(0))) != null)
- {
- var shadowSnapshot1 = emptySnapshot;
- entityType1 = materialCatalogMetadataEntityEntityType;
- if (entityType1 == materialCatalogMetadataEntityEntityType)
- {
- var instance = UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_Ctor();
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_Id_Set(instance) = dataReader.GetInt32(0);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_CatalogId_Set(instance) = dataReader.GetString(1);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_SchemaVersion_Set(instance) = dataReader.GetInt32(2);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_SeedVersion_Set(instance) = dataReader.GetString(3);
- if (instance is IInjectableService)
- {
- ((IInjectableService)(instance)).Injected(materializationContext1.Context, instance, QueryTrackingBehavior.NoTracking, materialCatalogMetadataEntityEntityType0);
- }
-
- instance1 = instance;
- }
- else
- {
- instance1 = default(MaterialCatalogMetadataEntity);
- }
- }
- else
- {
- var keyValues1 = new object[]
- {
- ((object)(dataReader.GetInt32(0)))
- };
- ShapedQueryCompilingExpressionVisitor.CreateNullKeyValueInNoTrackingQuery(materialCatalogMetadataEntityEntityType, materialCatalogMetadataEntityPrimaryKeyProperties, keyValues1);
- }
-
- var entity = instance1;
- return entity;
-}, typeof(MaterialCatalogDbContext), false, false, true).Single();
- }
-
- private static object Query1_Executor;
-
- #endregion Query1
- #region Query2
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 65, 62)]
- public static global::System.Linq.IQueryable<TEntity> Query2_AsNoTracking1<TEntity>(this global::System.Linq.IQueryable<TEntity> source)
- where TEntity : class
- {
- var precompiledQueryContext = new PrecompiledQueryContext<TEntity>(((IInfrastructure<DbContext>)source).Instance);
- return precompiledQueryContext;
- }
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 66, 10)]
- public static global::Microsoft.EntityFrameworkCore.Query.IIncludableQueryable<TEntity,TProperty> Query2_Include2<TEntity, TProperty>(this global::System.Linq.IQueryable<TEntity> source, global::System.Linq.Expressions.Expression<global::System.Func<TEntity,TProperty>> navigationPropertyPath)
- where TEntity : class
- {
- var precompiledQueryContext = (PrecompiledQueryContext<TEntity>)source;
- return precompiledQueryContext.ToIncludable<TProperty>();
- }
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 67, 10)]
- public static global::System.Linq.IOrderedQueryable<TSource> Query2_OrderBy3<TSource, TKey>(this global::System.Linq.IQueryable<TSource> source, global::System.Linq.Expressions.Expression<global::System.Func<TSource,TKey>> keySelector)
- {
- var precompiledQueryContext = (PrecompiledQueryContext<TSource>)source;
- return precompiledQueryContext;
- }
-
- [InterceptsLocation(@"/_/Aetheris/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs", 68, 10)]
- public static TSource[] Query2_ToArray4<TSource>(this global::System.Collections.Generic.IEnumerable<TSource> source)
- {
- var precompiledQueryContext = (PrecompiledQueryContext<TSource>)source;
- var queryContext = precompiledQueryContext.QueryContext;
- Query2_Executor ??= Query2_GenerateExecutor(precompiledQueryContext.DbContext, precompiledQueryContext.QueryContext);
- var queryingEnumerable = ((Func<QueryContext, IEnumerable<TSource>>)(Query2_Executor))(queryContext);
- return queryingEnumerable.ToArray();
- }
-
- private static object Query2_GenerateExecutor(DbContext dbContext, QueryContext queryContext)
- {
- var relationalModel = dbContext.Model.GetRelationalModel();
- var relationalTypeMappingSource = dbContext.GetService<IRelationalTypeMappingSource>();
- var materializerLiftableConstantContext = new RelationalMaterializerLiftableConstantContext(
- dbContext.GetService<ShapedQueryCompilingExpressionVisitorDependencies>(),
- dbContext.GetService<RelationalShapedQueryCompilingExpressionVisitorDependencies>(),
- dbContext.GetService<RelationalCommandBuilderDependencies>());
- var relationalCommandTemplate = ((IRelationalCommandTemplate)(new RelationalCommand(materializerLiftableConstantContext.CommandBuilderDependencies, "SELECT \"m\".\"Id\", \"m\".\"CatalogId\", \"m\".\"ConstitutiveClass\", \"m\".\"Designation\", \"m\".\"DisplayName\", \"m\".\"Family\", \"m\".\"FirmamentPath\", \"m\".\"Grade\", \"m\".\"ReferenceCondition\", \"m\".\"StableId\", \"m\".\"Standard\", \"m\".\"Temper\", \"m0\".\"Id\", \"m0\".\"Authority\", \"m0\".\"Condition\", \"m0\".\"Kind\", \"m0\".\"MaterialId\", \"m0\".\"Notes\", \"m0\".\"ReferenceTemperatureKelvin\", \"m0\".\"SourceId\", \"m0\".\"SourceUri\", \"m0\".\"UnitSymbol\", \"m0\".\"ValueSi\"\r\nFROM \"Materials\" AS \"m\"\r\nLEFT JOIN \"MaterialProperties\" AS \"m0\" ON \"m\".\"Id\" = \"m0\".\"MaterialId\"\r\nORDER BY \"m\".\"StableId\", \"m\".\"Id\"", "SELECT \"m\".\"Id\", \"m\".\"CatalogId\", \"m\".\"ConstitutiveClass\", \"m\".\"Designation\", \"m\".\"DisplayName\", \"m\".\"Family\", \"m\".\"FirmamentPath\", \"m\".\"Grade\", \"m\".\"ReferenceCondition\", \"m\".\"StableId\", \"m\".\"Standard\", \"m\".\"Temper\", \"m0\".\"Id\", \"m0\".\"Authority\", \"m0\".\"Condition\", \"m0\".\"Kind\", \"m0\".\"MaterialId\", \"m0\".\"Notes\", \"m0\".\"ReferenceTemperatureKelvin\", \"m0\".\"SourceId\", \"m0\".\"SourceUri\", \"m0\".\"UnitSymbol\", \"m0\".\"ValueSi\"\r\nFROM \"Materials\" AS \"m\"\r\nLEFT JOIN \"MaterialProperties\" AS \"m0\" ON \"m\".\"Id\" = \"m0\".\"MaterialId\"\r\nORDER BY \"m\".\"StableId\", \"m\".\"Id\"", new IRelationalParameter[] { })));
- var emptyValueBuffer = ValueBuffer.Empty;
- var emptySnapshot = Snapshot.Empty;
- var model = materializerLiftableConstantContext.Dependencies.Model;
- var materialEntityEntityType = model.FindEntityType("Aetheris.Kernel.StandardLibrary.Materials.Database.MaterialEntity");
- var constitutiveClassProperty = ((IPropertyBase)(((ITypeBase)materialEntityEntityType).FindProperty("ConstitutiveClass")));
- var materialEntityEntityType0 = ((RuntimeEntityType)(materialEntityEntityType));
- var materialEntityPrimaryKeyProperties = materialEntityEntityType.FindPrimaryKey().Properties;
- var parentIdentifierLambda = object[] (QueryContext queryContext, DbDataReader dataReader) => new object[]
-{
- ((object)(((int? )(dataReader.GetInt32(0)))))
-};
- var findNavigation = materialEntityEntityType.FindNavigation("Properties");
- var propertiesNavigation = ((INavigationBase)(findNavigation));
- var propertiesNavigationCollectionAccessor = ((IPropertyBase)findNavigation).GetCollectionAccessor();
- var selfIdentifierLambda = object[] (QueryContext queryContext, DbDataReader dataReader) => new object[]
-{
- ((object)((dataReader.IsDBNull(12) ? default(int? ) : ((int? )(dataReader.GetInt32(12))))))
-};
- var parentIdentifierValueComparers = new Func<object, object, bool>[]
-{
- bool (object left, object right) => (left == null ? right == null : right != null && ((int)(left)) == ((int)(right)))
-};
- var materialPropertyEntityEntityType = model.FindEntityType("Aetheris.Kernel.StandardLibrary.Materials.Database.MaterialPropertyEntity");
- var authorityProperty = ((IPropertyBase)(((ITypeBase)materialPropertyEntityEntityType).FindProperty("Authority")));
- var kindProperty = ((IPropertyBase)(((ITypeBase)materialPropertyEntityEntityType).FindProperty("Kind")));
- var materialPropertyEntityEntityType0 = ((RuntimeEntityType)(materialPropertyEntityEntityType));
- var materialInverseNavigation = ((INavigationBase)(materialPropertyEntityEntityType.FindNavigation("Material")));
- return IEnumerable<MaterialEntity> (QueryContext queryContext) => SingleQueryingEnumerable.Create(((RelationalQueryContext)(queryContext)), IRelationalCommandTemplate (Dictionary<string, object> parameters) => relationalCommandTemplate, (ReaderColumn[])(null), MaterialEntity (QueryContext queryContext, DbDataReader dataReader, ResultContext resultContext, SingleQueryResultCoordinator resultCoordinator) =>
-{
- if (resultContext.Values == null)
- {
- IEntityType entityType1 = default(IEntityType);
- var materializationContext1 = new MaterializationContext(in emptyValueBuffer, queryContext.Context);
- var instance1 = default(MaterialEntity);
- if (((object)(dataReader.GetInt32(0))) != null)
- {
- var shadowSnapshot1 = emptySnapshot;
- entityType1 = materialEntityEntityType;
- if (entityType1 == materialEntityEntityType)
- {
- var instance = UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Ctor();
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Id_Set(instance) = dataReader.GetInt32(0);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_CatalogId_Set(instance) = dataReader.GetString(1);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_ConstitutiveClass_Set(instance) = ((ValueConverter<MaterialConstitutiveClass, string>)(((IReadOnlyProperty)(constitutiveClassProperty)).GetTypeMapping().Converter)).ConvertFromProviderTyped(dataReader.GetString(2));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Designation_Set(instance) = dataReader.GetString(3);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_DisplayName_Set(instance) = dataReader.GetString(4);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Family_Set(instance) = dataReader.GetString(5);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_FirmamentPath_Set(instance) = dataReader.GetString(6);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Grade_Set(instance) = (dataReader.IsDBNull(7) ? default(string) : dataReader.GetString(7));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_ReferenceCondition_Set(instance) = dataReader.GetString(8);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_StableId_Set(instance) = dataReader.GetString(9);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Standard_Set(instance) = (dataReader.IsDBNull(10) ? default(string) : dataReader.GetString(10));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Temper_Set(instance) = (dataReader.IsDBNull(11) ? default(string) : dataReader.GetString(11));
- if (instance is IInjectableService)
- {
- ((IInjectableService)(instance)).Injected(materializationContext1.Context, instance, QueryTrackingBehavior.NoTracking, materialEntityEntityType0);
- }
-
- instance1 = instance;
- }
- else
- {
- instance1 = default(MaterialEntity);
- }
- }
- else
- {
- var keyValues1 = new object[]
- {
- ((object)(dataReader.GetInt32(0)))
- };
- ShapedQueryCompilingExpressionVisitor.CreateNullKeyValueInNoTrackingQuery(materialEntityEntityType, materialEntityPrimaryKeyProperties, keyValues1);
- }
-
- var entity = instance1;
- resultContext.Values = new object[]
- {
- entity
- };
- RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.InitializeIncludeCollection<MaterialEntity, MaterialEntity>(0, queryContext, dataReader, resultCoordinator, ((MaterialEntity)(resultContext.Values[0])), parentIdentifierLambda, parentIdentifierLambda, propertiesNavigation, propertiesNavigationCollectionAccessor, false, true);
- }
-
- RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.PopulateIncludeCollection(0, queryContext, dataReader, resultCoordinator, parentIdentifierLambda, parentIdentifierLambda, selfIdentifierLambda, parentIdentifierValueComparers, parentIdentifierValueComparers, parentIdentifierValueComparers, MaterialPropertyEntity (QueryContext queryContext, DbDataReader dataReader, ResultContext resultContext, SingleQueryResultCoordinator resultCoordinator) =>
- {
- IEntityType entityType2 = default(IEntityType);
- var materializationContext2 = new MaterializationContext(in emptyValueBuffer, queryContext.Context);
- var instance2 = default(MaterialPropertyEntity);
- if ((dataReader.IsDBNull(12) ? default(object) : ((object)(dataReader.GetInt32(12)))) != null)
- {
- var shadowSnapshot2 = emptySnapshot;
- entityType2 = materialPropertyEntityEntityType;
- if (entityType2 == materialPropertyEntityEntityType)
- {
- var instance = UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Ctor();
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Id_Set(instance) = (dataReader.IsDBNull(12) ? default(int) : dataReader.GetInt32(12));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Authority_Set(instance) = (dataReader.IsDBNull(13) ? default(MaterialPropertyAuthority) : ((ValueConverter<MaterialPropertyAuthority, string>)(((IReadOnlyProperty)(authorityProperty)).GetTypeMapping().Converter)).ConvertFromProviderTyped(dataReader.GetString(13)));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Condition_Set(instance) = (dataReader.IsDBNull(14) ? default(string) : dataReader.GetString(14));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Kind_Set(instance) = (dataReader.IsDBNull(15) ? default(MaterialPropertyKind) : ((ValueConverter<MaterialPropertyKind, string>)(((IReadOnlyProperty)(kindProperty)).GetTypeMapping().Converter)).ConvertFromProviderTyped(dataReader.GetString(15)));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_MaterialId_Set(instance) = (dataReader.IsDBNull(16) ? default(int) : dataReader.GetInt32(16));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Notes_Set(instance) = (dataReader.IsDBNull(17) ? default(string) : dataReader.GetString(17));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_ReferenceTemperatureKelvin_Set(instance) = (dataReader.IsDBNull(18) ? default(double? ) : ((double? )(dataReader.GetDouble(18))));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_SourceId_Set(instance) = (dataReader.IsDBNull(19) ? default(string) : dataReader.GetString(19));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_SourceUri_Set(instance) = (dataReader.IsDBNull(20) ? default(string) : dataReader.GetString(20));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_UnitSymbol_Set(instance) = (dataReader.IsDBNull(21) ? default(string) : dataReader.GetString(21));
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_ValueSi_Set(instance) = (dataReader.IsDBNull(22) ? default(double) : dataReader.GetDouble(22));
- if (instance is IInjectableService)
- {
- ((IInjectableService)(instance)).Injected(materializationContext2.Context, instance, QueryTrackingBehavior.NoTracking, materialPropertyEntityEntityType0);
- }
-
- instance2 = instance;
- }
- else
- {
- instance2 = default(MaterialPropertyEntity);
- }
- }
-
- var entity = instance2;
- return entity;
- }, materialInverseNavigation, (MaterialEntity unnamed1, MaterialPropertyEntity unnamed2) =>
- {
- propertiesNavigationCollectionAccessor.Add(unnamed1, unnamed2, true);
- UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Material_Set(unnamed2) = unnamed1;
- }, false);
- return (resultCoordinator.ResultReady ? ((MaterialEntity)(resultContext.Values[0])) : default(MaterialEntity));
-}, typeof(MaterialCatalogDbContext), false, false, true);
- }
-
- private static object Query2_Executor;
-
- #endregion Query2
- #region Unsafe accessors
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Id>k__BackingField")]
-private static extern ref int UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_Id_Set(MaterialCatalogMetadataEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<CatalogId>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_CatalogId_Set(MaterialCatalogMetadataEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<SchemaVersion>k__BackingField")]
-private static extern ref int UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_SchemaVersion_Set(MaterialCatalogMetadataEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<SeedVersion>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_SeedVersion_Set(MaterialCatalogMetadataEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
-private static extern MaterialCatalogMetadataEntity UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialCatalogMetadataEntity_Ctor();
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Id>k__BackingField")]
-private static extern ref int UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Id_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<CatalogId>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_CatalogId_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<ConstitutiveClass>k__BackingField")]
-private static extern ref MaterialConstitutiveClass UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_ConstitutiveClass_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Designation>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Designation_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<DisplayName>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_DisplayName_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Family>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Family_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<FirmamentPath>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_FirmamentPath_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Grade>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Grade_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<ReferenceCondition>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_ReferenceCondition_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<StableId>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_StableId_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Standard>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Standard_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Temper>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Temper_Set(MaterialEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Id>k__BackingField")]
-private static extern ref int UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Id_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Authority>k__BackingField")]
-private static extern ref MaterialPropertyAuthority UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Authority_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Condition>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Condition_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Kind>k__BackingField")]
-private static extern ref MaterialPropertyKind UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Kind_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<MaterialId>k__BackingField")]
-private static extern ref int UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_MaterialId_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Notes>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Notes_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<ReferenceTemperatureKelvin>k__BackingField")]
-private static extern ref double? UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_ReferenceTemperatureKelvin_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<SourceId>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_SourceId_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<SourceUri>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_SourceUri_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<UnitSymbol>k__BackingField")]
-private static extern ref string UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_UnitSymbol_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<ValueSi>k__BackingField")]
-private static extern ref double UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_ValueSi_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Material>k__BackingField")]
-private static extern ref MaterialEntity UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Material_Set(MaterialPropertyEntity instance);
- [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
-private static extern MaterialEntity UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialEntity_Ctor();
- [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
-private static extern MaterialPropertyEntity UnsafeAccessor_Aetheris_Kernel_StandardLibrary_Materials_Database_MaterialPropertyEntity_Ctor();
- #endregion Unsafe accessors
- }
-}
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
- file sealed class InterceptsLocationAttribute : Attribute
- {
- public InterceptsLocationAttribute(string filePath, int line, int column) { }
- }
-}
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/MaterialEntities.cs b/Aetheris.Kernel.StandardLibrary/Materials/Database/MaterialEntities.cs
index 8cfccfe4..2b34ece9 100644
--- a/Aetheris.Kernel.StandardLibrary/Materials/Database/MaterialEntities.cs
+++ b/Aetheris.Kernel.StandardLibrary/Materials/Database/MaterialEntities.cs
@@ -1,5 +1,3 @@
-using Microsoft.EntityFrameworkCore;
-
namespace Aetheris.Kernel.StandardLibrary.Materials.Database;
public class MaterialEntity
@@ -42,31 +40,3 @@ public class MaterialCatalogMetadataEntity
public required string CatalogId { get; set; }
public required string SeedVersion { get; set; }
}
-
-public sealed class MaterialCatalogDbContext(DbContextOptions<MaterialCatalogDbContext> options) : DbContext(options)
-{
- public const int SchemaVersion = 1;
- public DbSet<MaterialEntity> Materials => Set<MaterialEntity>();
- public DbSet<MaterialPropertyEntity> MaterialProperties => Set<MaterialPropertyEntity>();
- public DbSet<MaterialCatalogMetadataEntity> CatalogMetadata => Set<MaterialCatalogMetadataEntity>();
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- var material = modelBuilder.Entity<MaterialEntity>();
- material.ToTable("Materials");
- material.HasIndex(x => new { x.CatalogId, x.StableId }).IsUnique();
- material.HasIndex(x => x.FirmamentPath).IsUnique();
- material.Property(x => x.ConstitutiveClass).HasConversion<string>();
-
- var property = modelBuilder.Entity<MaterialPropertyEntity>();
- property.ToTable("MaterialProperties");
- property.HasIndex(x => new { x.MaterialId, x.Kind }).IsUnique();
- property.Property(x => x.Kind).HasConversion<string>();
- property.Property(x => x.Authority).HasConversion<string>();
- property.HasOne(x => x.Material).WithMany(x => x.Properties).HasForeignKey(x => x.MaterialId).OnDelete(DeleteBehavior.Cascade);
-
- var metadata = modelBuilder.Entity<MaterialCatalogMetadataEntity>();
- metadata.ToTable("CatalogMetadata");
- metadata.HasIndex(x => x.CatalogId).IsUnique();
- }
-}
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs b/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs
index 59d0e6bb..9131f8a6 100644
--- a/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs
+++ b/Aetheris.Kernel.StandardLibrary/Materials/MaterialCatalog.cs
@@ -1,6 +1,4 @@
using Aetheris.Kernel.StandardLibrary.Materials.Database;
-using Aetheris.Kernel.StandardLibrary.Materials.Database.CompiledModel;
-using Microsoft.EntityFrameworkCore;
namespace Aetheris.Kernel.StandardLibrary.Materials;
@@ -9,69 +7,44 @@ public interface IMaterialResolver
MaterialResolutionResult Resolve(string reference);
}
+/// <summary>A validated, immutable snapshot of engineering material values and provenance.</summary>
public sealed class MaterialCatalog : IDisposable
{
public const int ExpectedSeedMaterialCount = 4;
- private readonly MaterialCatalogDbContext database;
+ public const int CurrentSchemaVersion = 1;
+ private readonly ResolvedMaterial[] materials;
- public MaterialCatalog(string databasePath)
+ public MaterialCatalog(IEnumerable<MaterialEntity> entities, int schemaVersion = CurrentSchemaVersion)
{
- var fullPath = Path.GetFullPath(databasePath);
- var options = new DbContextOptionsBuilder<MaterialCatalogDbContext>()
- .UseSqlite($"Data Source={fullPath};Mode=ReadOnly;Pooling=False")
- .UseModel(MaterialCatalogDbContextModel.Instance)
- .Options;
- database = new(options);
+ if (schemaVersion != CurrentSchemaVersion) throw new FormatException($"Unsupported material catalog schema {schemaVersion}.");
+ var rows = entities.ToArray();
+ var errors = MaterialDataValidator.Validate(rows);
+ if (errors.Count > 0) throw new FormatException(string.Join(Environment.NewLine, errors));
+ materials = rows.OrderBy(x => x.StableId, StringComparer.Ordinal).Select(Map).ToArray();
}
- public IQueryable<MaterialCatalogItem> Materials => database.Materials.AsNoTracking().Select(x => new MaterialCatalogItem
+ public int SchemaVersion => CurrentSchemaVersion;
+ public static MaterialCatalog OpenDefault() => new(MaterialSeedData.Create());
+ public IQueryable<MaterialCatalogItem> Materials => materials.Select(x => new MaterialCatalogItem
{
- CatalogId = x.CatalogId,
- StableId = x.StableId,
- FirmamentPath = x.FirmamentPath,
- Family = x.Family,
- Designation = x.Designation,
- Grade = x.Grade,
- Temper = x.Temper,
- Standard = x.Standard,
- DisplayName = x.DisplayName,
- ConstitutiveClass = x.ConstitutiveClass,
+ CatalogId = x.Identity.CatalogId, StableId = x.Identity.StableId,
+ FirmamentPath = x.Identity.FirmamentPath, Family = x.Identity.Family,
+ Designation = x.Identity.Designation, Grade = x.Identity.Grade,
+ Temper = x.Identity.Temper, Standard = x.Identity.Standard,
+ DisplayName = x.Identity.DisplayName, ConstitutiveClass = x.ConstitutiveClass,
ReferenceCondition = x.ReferenceCondition,
- });
- public int SchemaVersion => database.CatalogMetadata.AsNoTracking().Single(x => x.CatalogId == "standard").SchemaVersion;
+ }).AsQueryable();
- public static MaterialCatalog OpenDefault() => new(MaterialCatalogDatabase.DefaultDatabasePath);
+ public ResolvedMaterial? GetById(string catalogId, string stableId) => materials.SingleOrDefault(x => x.Identity.CatalogId == catalogId && x.Identity.StableId == stableId);
+ public IReadOnlyList<ResolvedMaterial> FindByDesignation(string designation) => materials.Where(x => x.Identity.Designation == designation || x.Identity.Grade == designation).ToArray();
+ internal IReadOnlyList<ResolvedMaterial> FindByReference(string reference) => materials.Where(x => x.Identity.FirmamentPath == reference || x.Identity.StableId == reference || (x.Identity.CatalogId + ":" + x.Identity.StableId) == reference).ToArray();
- public ResolvedMaterial? GetById(string catalogId, string stableId)
- {
- var entity = LoadAll().SingleOrDefault(x => x.CatalogId == catalogId && x.StableId == stableId);
- return entity is null ? null : Map(entity);
- }
-
- public IReadOnlyList<ResolvedMaterial> FindByDesignation(string designation) => LoadAll()
- .Where(x => x.Designation == designation || x.Grade == designation)
- .OrderBy(x => x.StableId).Select(Map).ToArray();
-
- internal IReadOnlyList<ResolvedMaterial> FindByReference(string reference) => LoadAll()
- .Where(x => x.FirmamentPath == reference || x.StableId == reference || (x.CatalogId + ":" + x.StableId) == reference)
- .OrderBy(x => x.StableId).Select(Map).ToArray();
-
- public void Dispose() => database.Dispose();
-
- // The standard catalog is deliberately small and immutable. Loading its
- // bounded row set through one parameter-free EF query lets NativeAOT use
- // EF's generated query interceptor; identity filtering remains ordinary
- // deterministic in-memory comparison over database-derived entities.
- private MaterialEntity[] LoadAll() => database.Materials.AsNoTracking()
- .Include(x => x.Properties)
- .OrderBy(x => x.StableId)
- .ToArray();
+ // Retained for callers that previously scoped the database-backed catalog.
+ public void Dispose() { }
private static ResolvedMaterial Map(MaterialEntity entity)
{
- var validationErrors = MaterialDataValidator.Validate([entity]);
- if (validationErrors.Count > 0) throw new FormatException(string.Join(Environment.NewLine, validationErrors));
- var values = entity.Properties.ToDictionary(x => x.Kind, x => new MaterialPropertyValue(x.Kind, x.ValueSi, x.UnitSymbol, new(x.SourceId, x.SourceUri, x.Authority, x.Condition, x.ReferenceTemperatureKelvin, x.Notes)));
+ var values = entity.Properties.OrderBy(x => x.Kind).ToDictionary(x => x.Kind, x => new MaterialPropertyValue(x.Kind, x.ValueSi, x.UnitSymbol, new(x.SourceId, x.SourceUri, x.Authority, x.Condition, x.ReferenceTemperatureKelvin, x.Notes)));
var identity = new MaterialIdentity(entity.CatalogId, entity.StableId, entity.FirmamentPath, entity.Family, entity.Designation, entity.Grade, entity.Temper, entity.Standard, entity.DisplayName);
StructuralMaterialProperties? structural = null;
if (values.TryGetValue(MaterialPropertyKind.Density, out var density)
@@ -85,12 +58,6 @@ public sealed class MaterialCatalog : IDisposable
new(values.GetValueOrDefault(MaterialPropertyKind.ThermalConductivity), values.GetValueOrDefault(MaterialPropertyKind.SpecificHeat), values.GetValueOrDefault(MaterialPropertyKind.CoefficientOfThermalExpansion)), values);
}
- // Browser WebAssembly cannot initialize the EF/SQLite compiled model. Use
- // the very same immutable rows that seed the desktop catalog, with the
- // same identity filter, validation, and ResolvedMaterial mapping.
- internal static IReadOnlyList<ResolvedMaterial> FindBundledByReference(string reference) => MaterialSeedData.Create()
- .Where(x => x.FirmamentPath == reference || x.StableId == reference || (x.CatalogId + ":" + x.StableId) == reference)
- .OrderBy(x => x.StableId).Select(Map).ToArray();
}
public sealed class MaterialResolver(Func<MaterialCatalog> catalogFactory) : IMaterialResolver
@@ -103,9 +70,8 @@ public sealed class MaterialResolver(Func<MaterialCatalog> catalogFactory) : IMa
try
{
var normalized = reference.Trim();
- IReadOnlyList<ResolvedMaterial> matches;
- if (OperatingSystem.IsBrowser()) matches = MaterialCatalog.FindBundledByReference(normalized);
- else { using var catalog = catalogFactory(); matches = catalog.FindByReference(normalized); }
+ using var catalog = catalogFactory();
+ var matches = catalog.FindByReference(normalized);
return matches.Count switch
{
0 => MaterialResolutionResult.Failure(MaterialResolutionError.UnknownMaterial, $"Unknown material reference '{reference}'. Use a stable catalog ID or Firmament material path."),
@@ -119,27 +85,3 @@ public sealed class MaterialResolver(Func<MaterialCatalog> catalogFactory) : IMa
}
}
}
-
-public static class MaterialCatalogDatabase
-{
- public static string DefaultDatabasePath => Path.Combine(AppContext.BaseDirectory, "Materials", "aetheris-materials-x1.sqlite");
-
- public static void Recreate(string databasePath)
- {
- var fullPath = Path.GetFullPath(databasePath);
- Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
- if (File.Exists(fullPath)) File.Delete(fullPath);
- var options = new DbContextOptionsBuilder<MaterialCatalogDbContext>()
- .UseSqlite($"Data Source={fullPath};Pooling=False")
- .UseModel(MaterialCatalogDbContextModel.Instance)
- .Options;
- using var database = new MaterialCatalogDbContext(options);
- database.Database.EnsureCreated();
- var seed = MaterialSeedData.Create();
- var errors = MaterialDataValidator.Validate(seed);
- if (errors.Count > 0) throw new InvalidDataException(string.Join(Environment.NewLine, errors));
- database.Materials.AddRange(seed);
- database.CatalogMetadata.Add(new MaterialCatalogMetadataEntity { Id = 1, CatalogId = "standard", SchemaVersion = MaterialCatalogDbContext.SchemaVersion, SeedVersion = "MAT-DB-X1" });
- database.SaveChanges();
- }
-}
diff --git a/Aetheris.Kernel.StandardLibrary/build/Aetheris.Kernel.StandardLibrary.targets b/Aetheris.Kernel.StandardLibrary/build/Aetheris.Kernel.StandardLibrary.targets
deleted file mode 100644
index 82f681fd..00000000
--- a/Aetheris.Kernel.StandardLibrary/build/Aetheris.Kernel.StandardLibrary.targets
+++ /dev/null
@@ -1,21 +0,0 @@
-<Project>
- <PropertyGroup>
- <_AetherisMaterialCatalog>$(MSBuildThisFileDirectory)..\contentFiles\any\any\Materials\aetheris-materials-x1.sqlite</_AetherisMaterialCatalog>
- </PropertyGroup>
-
- <Target Name="CopyAetherisMaterialCatalogToOutput"
- AfterTargets="Build"
- Condition="Exists('$(_AetherisMaterialCatalog)')">
- <Copy SourceFiles="$(_AetherisMaterialCatalog)"
- DestinationFolder="$(TargetDir)Materials"
- SkipUnchangedFiles="true" />
- </Target>
-
- <Target Name="CopyAetherisMaterialCatalogToPublish"
- AfterTargets="Publish"
- Condition="Exists('$(_AetherisMaterialCatalog)') and '$(PublishDir)' != ''">
- <Copy SourceFiles="$(_AetherisMaterialCatalog)"
- DestinationFolder="$(PublishDir)Materials"
- SkipUnchangedFiles="true" />
- </Target>
-</Project>
diff --git a/Aetheris.Materials.Sqlite/Aetheris.Materials.Sqlite.csproj b/Aetheris.Materials.Sqlite/Aetheris.Materials.Sqlite.csproj
new file mode 100644
index 00000000..b0a0d745
--- /dev/null
+++ b/Aetheris.Materials.Sqlite/Aetheris.Materials.Sqlite.csproj
@@ -0,0 +1,14 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors</InterceptorsNamespaces>
+ <Description>Optional SQLite catalog interoperability for Aetheris. Includes native SQLite.</Description>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="../Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
+ <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
+ <Content Include="aetheris-materials-x1.sqlite" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" Link="Materials/aetheris-materials-x1.sqlite" Pack="true" PackagePath="contentFiles/any/any/Materials/aetheris-materials-x1.sqlite" PackageCopyToOutput="true" />
+ <None Include="build/Aetheris.Materials.Sqlite.targets" Pack="true" PackagePath="buildTransitive/Aetheris.Materials.Sqlite.targets" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextAssemblyAttributes.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextAssemblyAttributes.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextAssemblyAttributes.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextAssemblyAttributes.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextModel.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextModel.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextModel.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextModel.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextModelBuilder.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextModelBuilder.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogDbContextModelBuilder.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogDbContextModelBuilder.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogMetadataEntityEntityType.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogMetadataEntityEntityType.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogMetadataEntityEntityType.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogMetadataEntityEntityType.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogMetadataEntityUnsafeAccessors.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogMetadataEntityUnsafeAccessors.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialCatalogMetadataEntityUnsafeAccessors.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialCatalogMetadataEntityUnsafeAccessors.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialEntityEntityType.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialEntityEntityType.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialEntityEntityType.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialEntityEntityType.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialEntityUnsafeAccessors.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialEntityUnsafeAccessors.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialEntityUnsafeAccessors.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialEntityUnsafeAccessors.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialPropertyEntityEntityType.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialPropertyEntityEntityType.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialPropertyEntityEntityType.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialPropertyEntityEntityType.cs
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialPropertyEntityUnsafeAccessors.cs b/Aetheris.Materials.Sqlite/CompiledModel/MaterialPropertyEntityUnsafeAccessors.cs
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/CompiledModel/MaterialPropertyEntityUnsafeAccessors.cs
rename to Aetheris.Materials.Sqlite/CompiledModel/MaterialPropertyEntityUnsafeAccessors.cs
diff --git a/Aetheris.Materials.Sqlite/MaterialCatalogDatabase.cs b/Aetheris.Materials.Sqlite/MaterialCatalogDatabase.cs
new file mode 100644
index 00000000..8a49b630
--- /dev/null
+++ b/Aetheris.Materials.Sqlite/MaterialCatalogDatabase.cs
@@ -0,0 +1,43 @@
+using Aetheris.Kernel.StandardLibrary.Materials.Database;
+using Aetheris.Kernel.StandardLibrary.Materials.Database.CompiledModel;
+using Microsoft.EntityFrameworkCore;
+
+namespace Aetheris.Kernel.StandardLibrary.Materials;
+
+/// <summary>Optional SQLite interoperability. The default catalog needs no database.</summary>
+public static class SqliteMaterialCatalog
+{
+ public static MaterialCatalog Open(string databasePath)
+ {
+ var options = new DbContextOptionsBuilder<MaterialCatalogDbContext>()
+ .UseSqlite($"Data Source={Path.GetFullPath(databasePath)};Mode=ReadOnly;Pooling=False")
+ .UseModel(MaterialCatalogDbContextModel.Instance).Options;
+ using var database = new MaterialCatalogDbContext(options);
+ var version = database.CatalogMetadata.AsNoTracking().Single(x => x.CatalogId == "standard").SchemaVersion;
+ return new MaterialCatalog(database.Materials.AsNoTracking().Include(x => x.Properties).ToArray(), version);
+ }
+}
+
+public static class MaterialCatalogDatabase
+{
+ public static string DefaultDatabasePath => Path.Combine(AppContext.BaseDirectory, "Materials", "aetheris-materials-x1.sqlite");
+
+ public static void Recreate(string databasePath)
+ {
+ var fullPath = Path.GetFullPath(databasePath);
+ Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
+ if (File.Exists(fullPath)) File.Delete(fullPath);
+ var options = new DbContextOptionsBuilder<MaterialCatalogDbContext>()
+ .UseSqlite($"Data Source={fullPath};Pooling=False")
+ .UseModel(MaterialCatalogDbContextModel.Instance)
+ .Options;
+ using var database = new MaterialCatalogDbContext(options);
+ database.Database.EnsureCreated();
+ var seed = MaterialSeedData.Create();
+ var errors = MaterialDataValidator.Validate(seed);
+ if (errors.Count > 0) throw new InvalidDataException(string.Join(Environment.NewLine, errors));
+ database.Materials.AddRange(seed);
+ database.CatalogMetadata.Add(new MaterialCatalogMetadataEntity { Id = 1, CatalogId = "standard", SchemaVersion = MaterialCatalogDbContext.SchemaVersion, SeedVersion = "MAT-DB-X1" });
+ database.SaveChanges();
+ }
+}
diff --git a/Aetheris.Materials.Sqlite/MaterialCatalogDbContext.cs b/Aetheris.Materials.Sqlite/MaterialCatalogDbContext.cs
new file mode 100644
index 00000000..aeb41c7e
--- /dev/null
+++ b/Aetheris.Materials.Sqlite/MaterialCatalogDbContext.cs
@@ -0,0 +1,31 @@
+using Microsoft.EntityFrameworkCore;
+
+namespace Aetheris.Kernel.StandardLibrary.Materials.Database;
+
+public sealed class MaterialCatalogDbContext(DbContextOptions<MaterialCatalogDbContext> options) : DbContext(options)
+{
+ public const int SchemaVersion = 1;
+ public DbSet<MaterialEntity> Materials => Set<MaterialEntity>();
+ public DbSet<MaterialPropertyEntity> MaterialProperties => Set<MaterialPropertyEntity>();
+ public DbSet<MaterialCatalogMetadataEntity> CatalogMetadata => Set<MaterialCatalogMetadataEntity>();
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ var material = modelBuilder.Entity<MaterialEntity>();
+ material.ToTable("Materials");
+ material.HasIndex(x => new { x.CatalogId, x.StableId }).IsUnique();
+ material.HasIndex(x => x.FirmamentPath).IsUnique();
+ material.Property(x => x.ConstitutiveClass).HasConversion<string>();
+
+ var property = modelBuilder.Entity<MaterialPropertyEntity>();
+ property.ToTable("MaterialProperties");
+ property.HasIndex(x => new { x.MaterialId, x.Kind }).IsUnique();
+ property.Property(x => x.Kind).HasConversion<string>();
+ property.Property(x => x.Authority).HasConversion<string>();
+ property.HasOne(x => x.Material).WithMany(x => x.Properties).HasForeignKey(x => x.MaterialId).OnDelete(DeleteBehavior.Cascade);
+
+ var metadata = modelBuilder.Entity<MaterialCatalogMetadataEntity>();
+ metadata.ToTable("CatalogMetadata");
+ metadata.HasIndex(x => x.CatalogId).IsUnique();
+ }
+}
diff --git a/Aetheris.Kernel.StandardLibrary/Materials/Database/aetheris-materials-x1.sqlite b/Aetheris.Materials.Sqlite/aetheris-materials-x1.sqlite
similarity index 100%
rename from Aetheris.Kernel.StandardLibrary/Materials/Database/aetheris-materials-x1.sqlite
rename to Aetheris.Materials.Sqlite/aetheris-materials-x1.sqlite
diff --git a/Aetheris.Materials.Sqlite/build/Aetheris.Materials.Sqlite.targets b/Aetheris.Materials.Sqlite/build/Aetheris.Materials.Sqlite.targets
new file mode 100644
index 00000000..52ef5334
--- /dev/null
+++ b/Aetheris.Materials.Sqlite/build/Aetheris.Materials.Sqlite.targets
@@ -0,0 +1,11 @@
+<Project>
+ <PropertyGroup>
+ <_AetherisSqliteCatalog>$(MSBuildThisFileDirectory)..\contentFiles\any\any\Materials\aetheris-materials-x1.sqlite</_AetherisSqliteCatalog>
+ </PropertyGroup>
+ <Target Name="CopyAetherisSqliteCatalogToOutput" AfterTargets="Build" Condition="Exists('$(_AetherisSqliteCatalog)')">
+ <Copy SourceFiles="$(_AetherisSqliteCatalog)" DestinationFolder="$(TargetDir)Materials" SkipUnchangedFiles="true" />
+ </Target>
+ <Target Name="CopyAetherisSqliteCatalogToPublish" AfterTargets="Publish" Condition="Exists('$(_AetherisSqliteCatalog)') and '$(PublishDir)' != ''">
+ <Copy SourceFiles="$(_AetherisSqliteCatalog)" DestinationFolder="$(PublishDir)Materials" SkipUnchangedFiles="true" />
+ </Target>
+</Project>
diff --git a/Aetheris.ThreeDm.CLI/Aetheris.ThreeDm.CLI.csproj b/Aetheris.ThreeDm.CLI/Aetheris.ThreeDm.CLI.csproj
new file mode 100644
index 00000000..78bc28c5
--- /dev/null
+++ b/Aetheris.ThreeDm.CLI/Aetheris.ThreeDm.CLI.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <PackAsTool>true</PackAsTool>
+ <ToolCommandName>aetheris-3dm</ToolCommandName>
+ <PackageId>Aetheris.ThreeDm.CLI</PackageId>
+ <Description>Optional Aetheris 3DM inspection and recovery tool. Includes the native Rhino3dm interoperability library.</Description>
+ </PropertyGroup>
+ <ItemGroup><ProjectReference Include="../Aetheris.ThreeDm/Aetheris.ThreeDm.csproj" /></ItemGroup>
+</Project>
diff --git a/Aetheris.ThreeDm.CLI/Program.cs b/Aetheris.ThreeDm.CLI/Program.cs
new file mode 100644
index 00000000..50bb05b8
--- /dev/null
+++ b/Aetheris.ThreeDm.CLI/Program.cs
@@ -0,0 +1,33 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Aetheris.CLI;
+
+public static class Program
+{
+ public static int Main(string[] args)
+ {
+ if (args.Length == 0 || args[0] is "--help" or "-h")
+ {
+ Console.WriteLine("Usage: aetheris-3dm <inspect|recover> <file.3dm> [options]. Use '<command> --help' for options.");
+ return args.Length == 0 ? 1 : 0;
+ }
+ var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+ options.Converters.Add(new JsonStringEnumConverter());
+ try
+ {
+ return args[0] switch
+ {
+ "inspect" or "inspect-3dm" => ThreeDmCli.Run(args[1..], Console.Out, Console.Error, options),
+ "recover" or "recover-3dm" => ThreeDmCli.Recover(args[1..], Console.Out, Console.Error, options),
+ _ => Unknown(args[0]),
+ };
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine($"3dm-operation-failed: {e.Message}");
+ return 1;
+ }
+ }
+ private static int Unknown(string command) { Console.Error.WriteLine($"Unknown 3DM command '{command}'."); return 1; }
+}
diff --git a/Aetheris.CLI/ThreeDmCli.cs b/Aetheris.ThreeDm.CLI/ThreeDmCli.cs
similarity index 97%
rename from Aetheris.CLI/ThreeDmCli.cs
rename to Aetheris.ThreeDm.CLI/ThreeDmCli.cs
index e1c2f5f2..acd82e1d 100644
--- a/Aetheris.CLI/ThreeDmCli.cs
+++ b/Aetheris.ThreeDm.CLI/ThreeDmCli.cs
@@ -9,12 +9,12 @@ internal static class ThreeDmCli
{
if (args.Length == 1 && args[0] is "--help" or "-h")
{
- stdout.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");
+ stdout.WriteLine("Usage: aetheris-3dm recover <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");
return 0;
}
if (args.Length < 1)
{
- stderr.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");
+ stderr.WriteLine("Usage: aetheris-3dm recover <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");
return 1;
}
var json = false;
@@ -118,12 +118,12 @@ internal static class ThreeDmCli
{
if (args.Length == 1 && args[0] is "--help" or "-h")
{
- stdout.WriteLine("Usage: aetheris inspect-3dm <file.3dm> [--json]");
+ stdout.WriteLine("Usage: aetheris-3dm inspect <file.3dm> [--json]");
return 0;
}
if (args.Length is < 1 or > 2 || (args.Length == 2 && args[1] != "--json"))
{
- stderr.WriteLine("Usage: aetheris inspect-3dm <file.3dm> [--json]");
+ stderr.WriteLine("Usage: aetheris-3dm inspect <file.3dm> [--json]");
return 1;
}
var inventory = ThreeDmInspector.Inspect(args[0]);
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 71222b85..7bba91ef 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -1,4 +1,6 @@
<Solution>
+ <Project Path="Aetheris.Materials.Sqlite/Aetheris.Materials.Sqlite.csproj" />
+ <Project Path="Aetheris.ThreeDm.CLI/Aetheris.ThreeDm.CLI.csproj" />
<Project Path="Aetheris.Cloth3D/Aetheris.Cloth3D.csproj" />
<Project Path="test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj" />
<Project Path="Aetheris.Cadmata.Desktop/Aetheris.Cadmata.Desktop.csproj" />
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f7283338..e9d2b980 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -8,7 +8,18 @@ Thank you for improving Aetheris. Keep changes focused, explain the engineering
## Build and test
-Install the .NET SDK selected by [`global.json`](global.json). Firmament uses an exact managed WGSL compiler package built from a reviewed Copeland commit. A fresh checkout must prepare that ignored local feed before restoring the solution:
+Install the .NET SDK selected by [`global.json`](global.json).
+
+Source builds that include Drawing Notes also require Node 24 and npm. MSBuild
+restores the pinned PDF.js dependency from `Aetheris.Drawing/Web/package-lock.json`
+with install scripts and optional native packages disabled. Only selected browser
+runtime assets and licenses are embedded; downloaded distributions stay ignored.
+Published Aetheris tools do not require Node or npm. See
+[`Aetheris.Drawing/Web/README.md`](Aetheris.Drawing/Web/README.md).
+
+Firmament uses an exact managed WGSL compiler package built from a reviewed
+Copeland commit. A fresh checkout must prepare that ignored local feed before
+restoring the solution:
```powershell
git clone --no-checkout https://github.com/yuechen-li-dev/Copeland.git artifacts/local/managed-wgsl/source
diff --git a/docs/development/reports/2026-10/CORE-CLI-NATIVE-DEPENDENCY-REMOVAL.md b/docs/development/reports/2026-10/CORE-CLI-NATIVE-DEPENDENCY-REMOVAL.md
new file mode 100644
index 00000000..d3c56ee4
--- /dev/null
+++ b/docs/development/reports/2026-10/CORE-CLI-NATIVE-DEPENDENCY-REMOVAL.md
@@ -0,0 +1,157 @@
+# Core CLI native dependency removal
+
+2026-10-23. Base `b80e1838` plus the local changes. Source changes and local
+qualification; no package publication.
+
+## Boundary and implementation
+
+The default compiler/CLI bundles no **third-party OS-native libraries**. .NET's
+runtime and apphost remain platform dependencies; browser rendering uses the
+user's browser. This is not a claim that the entire desktop application or every
+optional interoperability package contains no native code.
+
+- Removed PDFtoImage, SkiaSharp and PDFium from `Aetheris.Drawing`. PDF metadata
+ inspection uses managed PdfPig 0.1.16. PDF.js 6.4.299 renders pages, thumbnails
+ and source-linked PNG crops in the existing Drawing Notes UI. Its pinned
+ minified browser assets and font/CMap/decoder licenses are embedded; there
+ are no CDN requests, Node canvas dependencies or bundled browser executable.
+ Portable browser WebAssembly decoders are included, not OS shared libraries.
+ Only the pinned npm manifests and restore instructions are tracked. The full
+ download and former vendor folder are ignored; source builds restore assets
+ with `npm ci --ignore-scripts --omit=optional`. Explicit resource inputs exclude
+ maps, viewers, legacy builds, package metadata, types and Node tooling.
+- Vector drawing generation remains the existing managed PDF/SVG/PPTX path.
+ Headless source-PDF rasterization is explicitly optional:
+ `--renderer <path-to-pdftoppm>`. No installation, discovery or silent backend
+ fallback occurs. An omitted backend reports `drawing-renderer-required`.
+- The default material catalog uses the **existing** managed seed rows, shared
+ with browser compilation. Validation and mapping remain in StandardLibrary.
+ A regression compares every resolved identity, SI property and provenance
+ field against the original checked-in SQLite database.
+- `Aetheris.Materials.Sqlite` owns EF/SQLite, its compiled model, reproducible
+ database generator and historical database. Custom callers migrate from
+ `new MaterialCatalog(path)` to `SqliteMaterialCatalog.Open(path)`, retaining
+ the `IMaterialResolver` injection seam. The default compiler does not reference
+ this optional adapter. Its query adapter is qualified on .NET; NativeAOT
+ SQLite query execution is not claimed.
+- `Aetheris.ThreeDm.CLI` supplies `aetheris-3dm inspect` and `recover`, retaining
+ the existing inspection/recovery implementation and Rhino3dm dependency.
+ Old core CLI command names give an explicit installation/invocation message.
+ No reflection-based plugin loader or parallel command implementation was added.
+- FrictionLab retains its managed executable entry point (`dotnet run` works),
+ but no longer generates an unnecessary apphost that was copied into the CLI.
+
+## Coordinates and diagnostics
+
+Notes remain referenced to the source SHA-256 and top-left physical PDF points
+on the **rotated visible CropBox**, including UserUnit. The managed library's
+page-size shortcut missed an inherited CropBox; inspection therefore resolves
+page-tree box metadata through its existing tokenizer/object resolver, with
+bounded cycle detection and explicit malformed-metadata failures. It does not
+introduce another PDF parser.
+
+The browser verifies the PDF hash, page count and viewport dimensions before
+enabling annotations. A mismatch with an old notebook is an explicit error;
+coordinates are not silently converted. Source inspector and renderer versions
+are distinct metadata. Legacy notebook renderer provenance survives loading.
+Crop sidecars retain page, original bounds, source hash, actual renderer version,
+DPI and output filename; raster bounds round outward to whole pixels.
+
+The external renderer uses argument lists, an execution timeout, process cleanup,
+temporary output and PNG dimension verification. Browser rendering uses PDF.js
+viewports and canvas encoding. Drawing Notes exceptions now retain their codes
+and messages in structured CLI JSON, and code-bearing text output.
+
+## Package qualification
+
+The CLI build rejects resolved third-party native assets. The release script and
+CI additionally run `scripts/Test-CoreCliPayload.ps1` over the actual package,
+dependency receipts and PE/native payload files. The only runtime exemption is
+the .NET runtime/apphost. Optional packages are deliberately outside that guard.
+
+Evidence defaults to ignored `artifacts/local/native-dependency-removal/`:
+
+- Core NuGet tool: **19,752,875 bytes (18.84 MiB)**; actual package, portable
+ publish directory and ZIP all passed the guard. The Windows self-contained
+ publish also passed, with only its .NET runtime/apphost native files exempted.
+- A deliberate injection of a real native SQLite DLL into the portable payload
+ was rejected as an unowned native PE. The clean payload passed again.
+ A synthetic unexpected native dependency was independently rejected from the
+ resolved-graph check.
+- Core and optional 3DM tools were packed, installed using local-only NuGet feeds,
+ and invoked through their installed commands. Core PDF inspection succeeded;
+ 3DM inspection preserved the local source's 27 BReps, 185 faces, 346 edges,
+ 219 vertices and metre-to-millimetre unit conversion.
+- Real browser qualification checked all four rotations, an inherited offset
+ CropBox and UserUnit 2 against **rendered red-pixel bounds**, then exercised
+ annotation creation, save/reload and PNG/metadata downloads on both the
+ coordinate witness and the engineering sheet.
+- External pdftoppm 26.07.0 rendering and crops were checked against the same
+ actual colored source pixels in all four orientations, not just output sizes.
+- Published CLI compiled the countersunk L-bracket and two-component mounted
+ bracket assembly to STEP, and generated the inspection plate's PDF/SVG/PPTX
+ drawing. These paths do not invoke a PDF rasterizer.
+ Framework-dependent and self-contained inspection drawings have identical
+ PDF SHA-256 `5fd16e2871d428dd8a82401986317051d4f5b3998a11aed479a0af99fd9db4dd`.
+ The existing complete code-native assembly rehearsal passed, including STEP
+ round trips, stable definitions, moved occurrence placement and solid-Revolve
+ geometry parity.
+
+The browser regression is `scripts/test-drawing-notes-browser.mjs`; deterministic
+source witnesses and regeneration instructions are in `fixtures/DrawingNotes/`.
+Public usage and compatibility changes are documented under `docs/public/`.
+
+Follow-up packaging hygiene: PDF.js is now a pinned npm build dependency rather
+than checked-in vendor files. `.gitignore` excludes the downloaded distribution
+and archives; the project embeds an explicit runtime subset using minified
+modules. The revised tool package is **19,603,470 bytes**, with browser and
+native-payload checks recorded under `artifacts/local/pdfjs-packaging/`. Optional
+native Node canvas packages are omitted during restore.
+The follow-up Release build, 1,088-test fast lane and complete 5,963-test suite
+passed again with zero failures/skips. Browser rendering/crops and package
+inspection passed; Git sees just the two manifests and README in the asset folder.
+
+## Final regression gate
+
+| Check | Result |
+|---|---|
+| Release solution build | Passed; final incremental build had zero errors/warnings |
+| Fast Core lane | 1,088 passed |
+| Full serial solution lane | **5,963 passed, zero failures/skips, 20 populated suites** |
+| Material catalog parity and catalog behavior | 7 passed, including every original SQLite value and provenance field |
+| Drawing Notes managed/external renderer tests | 16 passed, external renderer explicitly configured |
+| Focused Drawing Notes/optional-tool CLI diagnostics | 5 passed |
+| Real browser server/render/save/crop checks | Passed |
+| Tool package, portable publish/ZIP and Windows self-contained publish | Native-asset guards passed |
+| Published CLI STEP, assembly, drawing and local-tool install paths | Passed |
+| Repository layout and whitespace checks | Passed |
+
+FrictionLab has no discoverable tests and is not counted as coverage. After the
+full run, the PDF.js fallback-module MIME correction was rebuilt and rechecked
+with the 16 Drawing tests, five CLI tests and real browser qualification; no
+engineering code changed. Standalone optional 3DM error handling was checked
+against a missing file as well as successful inventory. Linux/other RID execution
+was not run locally; CI now checks the actual portable tool package on Linux.
+
+An initial run exposed a Drawing Notes CLI code-propagation failure (repaired), and an
+unmodified assembly display test hit its five-second tessellation wall-clock
+budget. The complete subsequent run passed, including that test. No engineering
+algorithm or timeout threshold was changed for this pass.
+
+Packaging is serial with MSBuild node reuse disabled. Fifteen reusable workers
+left by an early packaging probe were identified by their completed parent
+process and reaped; unrelated processes were not stopped.
+Automatic approval review rejected deletion of redundant local downloads and
+the initial package probe, supplying only “blocked by policy.” Those temporary
+files remain; `artifacts/local/native-dependency-removal/cleanup-probes.ps1` is
+provided for manual review (`-WhatIf` previews its bounded targets). It was not run.
+
+## Verdict
+
+**Success.** The default compiler/CLI admits the same engineering workflows while
+its real published payload is free of third-party OS-native libraries. Drawing
+Notes remains usable offline through the browser; explicitly external rasterizing
+and native interoperability have visible, optional ownership. No engineering
+emitter or geometry algorithm changed. This qualifies the core tool boundary,
+not a general removal of native code from WebView2/.NET or optional Rhino/SQLite
+integrations.
diff --git a/docs/public/drawing-notes.md b/docs/public/drawing-notes.md
index 0cc7a967..1020eda4 100644
--- a/docs/public/drawing-notes.md
+++ b/docs/public/drawing-notes.md
@@ -55,15 +55,20 @@ Do not force uncertainty into a known type. Use `Unknown`, `Low`, or `Unresolved
## Highlight and crop
-Render a crisp page or export pixels from the source PDF only:
+The browser UI renders PDF pages, thumbnails and crops with locally bundled PDF.js. It works offline and does not require PDFium, Skia, Poppler or a CDN. Select a note or drag a rectangle, then click **Export crop** to download its PNG and `.crop.json` source metadata (allow multiple downloads if your browser asks).
+
+For headless automation, explicitly select an external Poppler `pdftoppm` executable. Aetheris does not install or bundle it. Omitting the renderer produces `drawing-renderer-required`; inspection, notes and vector drawing generation need no native backend:
```powershell
-aetheris drawing render drawing.pdf --page 1 --out page-1.png --dpi 240
+$renderer = "C:/tools/poppler/bin/pdftoppm.exe" # or /usr/bin/pdftoppm
+aetheris drawing render drawing.pdf --page 1 --out page-1.png --dpi 240 --renderer $renderer
aetheris drawing crop drawing.pdf --page 1 `
--bounds "465,60,180,200" --name DetailD `
- --out notes/crops/p01-detail-d.png --dpi 300
+ --out notes/crops/p01-detail-d.png --dpi 300 --renderer $renderer
```
+Crop coordinates are relative to the top-left of the **rotated, visible CropBox**, in physical PDF points (1/72 inch, including UserUnit). Raster boundaries round outward to whole pixels at the selected DPI; the sidecar keeps the requested page-space bounds. The browser checks the source hash and page dimensions before enabling annotation. Older notebooks retain their renderer provenance; incompatible coordinates require explicit reconciliation.
+
Every crop receives a `.crop.json` sidecar containing its page, source bounds, document hash, renderer, and DPI. The PNG is a rendering of the real source area, not an OCR redraw.
For interactive work, launch the local browser UI:
diff --git a/docs/public/firmament/materials.md b/docs/public/firmament/materials.md
index 43b845b8..20ec0df4 100644
--- a/docs/public/firmament/materials.md
+++ b/docs/public/firmament/materials.md
@@ -15,6 +15,12 @@ Preview 3 ships four catalog entries:
| `Standard.Materials.Steel.ASTM_A36` | ASTM A36 structural steel |
| `Standard.Materials.StainlessSteel.304_Annealed` | 304 stainless, annealed |
-The Standard Library catalog is backed by a deployed SQLite asset and resolved by .NET. Firmament does not expose SQL. FEA consumes catalog density and the properties required by its constitutive model; an unknown material is a named error, not a fallback.
+The Standard Library uses the same versioned, managed catalog on desktop and in the browser. No database engine or catalog file is required for the four built-in materials. Identity, SI values and property provenance remain attached to each resolved material. Firmament does not expose SQL. FEA consumes catalog density and the properties required by its constitutive model; an unknown material is a named error, not a fallback.
-Build/solve [`catalog-material-coupon.firmament`](../../../fixtures/Canonical/Materials/material-catalog-coupon.firmament) with `aetheris fea ... --out-dir artifacts/material --json`.
+Build/solve [`catalog-material-coupon.firmament`](../../../fixtures/Canonical/Materials/material-catalog-coupon.firmament) with `aetheris fea ... --out-dir artifacts/local/material --json`.
+
+## Optional SQLite interoperability
+
+Applications that maintain an external SQLite catalog can reference `Aetheris.Materials.Sqlite` and use `SqliteMaterialCatalog.Open(path)` in place of the former `new MaterialCatalog(path)`. It returns a validated in-memory `MaterialCatalog`; the database is closed before geometry compilation. `MaterialResolver(() => SqliteMaterialCatalog.Open(path))` retains the resolver injection seam. This optional package includes native SQLite and is not a dependency of the compiler or CLI.
+
+For managed integrations, `new MaterialCatalog(entities)` accepts material rows with typed properties and provenance, validates the complete snapshot, and resolves it without database access. `MaterialCatalogDatabase.Recreate(path)` remains in the optional SQLite package for applications that generate the standard seed database.
diff --git a/docs/public/reference/3dm-recovery.md b/docs/public/reference/3dm-recovery.md
index 9a4c3781..9b28042b 100644
--- a/docs/public/reference/3dm-recovery.md
+++ b/docs/public/reference/3dm-recovery.md
@@ -1,10 +1,22 @@
# 3DM geometry recovery evidence
-`aetheris inspect-3dm model.3dm --json` reads Rhino/OpenNURBS file metadata and BRep inventory. `aetheris recover-3dm model.3dm --json` measures bounded analytic and non-rational recovery candidates. Use `--body N --edge N` or `--body N --face N` with `recover-3dm` to inspect one source entity. `--recovery-tolerance-mm N` sets the generic spline budget (default 0.1 mm). The file's unit metadata determines conversion to Aetheris millimetres.
+3DM support is an optional tool because Rhino/OpenNURBS interoperability requires the native Rhino3dm library. Install it separately:
+
+```powershell
+dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease
+aetheris-3dm inspect model.3dm --json
+aetheris-3dm recover model.3dm --json
+```
+
+The default `aetheris` compiler does not include Rhino3dm. Its old `inspect-3dm` / `recover-3dm` commands report how to install and invoke the companion tool.
+
+From a source checkout, use `dotnet run --project Aetheris.ThreeDm.CLI -- inspect model.3dm --json` (or `recover`). Pack the optional tool with `dotnet pack Aetheris.ThreeDm.CLI -c Release -o artifacts/local/packages`; it is intentionally separate from `Aetheris.CLI`.
+
+`aetheris-3dm inspect model.3dm --json` reads Rhino/OpenNURBS file metadata and BRep inventory. `aetheris-3dm recover model.3dm --json` measures bounded analytic and non-rational recovery candidates. Use `--body N --edge N` or `--body N --face N` with `recover-3dm` to inspect one source entity. `--recovery-tolerance-mm N` sets the generic spline budget (default 0.1 mm). The file's unit metadata determines conversion to Aetheris millimetres.
The recovery report is a **review aid**. It lists source object UUIDs, body/face/edge indices, degree and control-net sizes, candidate dimensions, RMS/p95/max deviations, angular deviations, rejected alternatives, and topology status. It also groups repeated radii as hypotheses. For unrecognized rational supports, `genericRecovery` reports the bounded non-rational candidate, its method, control-net complexity, and deviation against both the shared reducer and independent Rhino evaluation. The analysis mode does not build a BRep or STEP.
-`aetheris recover-3dm model.3dm --bind-step --out-dir artifacts/local/3dm-bind --json` runs the separate topology-binding path. It preserves Rhino edge reuse, vertices, loops, and trim direction, retains source UV pcurves when qualified, and asks the shared recovered-pcurve binder for the rest. It exports only bodies that pass shell, pcurve, trusted STEP preflight, reimport, and sampled bounding-box checks. STEP files and the JSON report should stay under ignored `artifacts/local/` for private source models. Add `--body N` to bind just one source BRep.
+`aetheris-3dm recover model.3dm --bind-step --out-dir artifacts/local/3dm-bind --json` runs the separate topology-binding path. It preserves Rhino edge reuse, vertices, loops, and trim direction, retains source UV pcurves when qualified, and asks the shared recovered-pcurve binder for the rest. It exports only bodies that pass shell, pcurve, trusted STEP preflight, reimport, and sampled bounding-box checks. STEP files and the JSON report should stay under ignored `artifacts/local/` for private source models. Add `--body N` to bind just one source BRep.
Add `--combined-step` for a whole-file AP242 assembly when every source BRep qualifies. This emits `recovered-assembly.step` alongside deterministic per-object files; a source BRep with disconnected closed components contributes one STEP solid per component. Singular Rhino trims remain vertex semantics in the bound BRep. On mixed singular loops, the reference STEP omits pcurve associations that cannot yet roundtrip reliably, while preserving the 3D edges, faces, and source binding evidence. Explicit source vertex tolerances are capped locally at 1 mm and reported separately from the default 0.1 mm spline recovery budget. A near-coincident planar inner loop can be reimported under the explicit `AllowBoundedNearCoincidentInnerLoop` import policy; the default strict STEP importer continues to reject crossings.
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index 3be4dd55..a5244de1 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -2,14 +2,16 @@
Primary public commands:
+Commands use `aetheris` unless a separate executable is shown. The optional `aetheris-3dm` tool includes native Rhino3dm; [installation and source usage](3dm-recovery.md).
+
| Command | Purpose |
|---|---|
| `validate <file> [--json]` | Check admission; generic mechanical validation includes in-memory geometry preflight |
| `frontend-shadow <file> [--json] [--ast] [--validate] [--benchmark]` | Developer-only original-source structural evidence and bounded production comparison |
| `build <file> [--output path] [--json]` | Materialize and export exact STEP AP242 |
| `inspect <firmament-or-step> [--json]` | Inspect source semantics or route STEP to analysis |
-| `inspect-3dm <file.3dm> [--json]` | Inventory Rhino/OpenNURBS metadata, units, BRep topology, and unsupported objects |
-| `recover-3dm <file.3dm> [--body N [--edge N\|--face N]] [--json]` | Measure provisional analytic/non-rational recovery candidates; see [3DM recovery evidence](3dm-recovery.md) |
+| `aetheris-3dm inspect <file.3dm> [--json]` | Inventory Rhino/OpenNURBS metadata, units, BRep topology, and unsupported objects |
+| `aetheris-3dm recover <file.3dm> [--body N [--edge N\|--face N]] [--json]` | Measure provisional analytic/non-rational recovery candidates; see [3DM recovery evidence](3dm-recovery.md) |
| `analyze <step> [--json]` | Reinspect topology, surfaces, bounds, manifold state, and PMI |
| `analyze section <step> ((--xy\|--xz\|--yz) --offset value\|--origin x,y,z --normal x,y,z) [--out section.svg] [--json]` | Extract trim-aware analytic section loops in a principal or arbitrary plane and optionally render deterministic SVG evidence |
| `analyze compound <step> [--json]` | Inspect every disconnected rigid root without silently selecting or merging one |
diff --git a/docs/public/web-sdk/capability-matrix.md b/docs/public/web-sdk/capability-matrix.md
index 8c31c539..db691cbe 100644
--- a/docs/public/web-sdk/capability-matrix.md
+++ b/docs/public/web-sdk/capability-matrix.md
@@ -16,7 +16,8 @@
| Multiple export formats | Yes | Yes | One ZIP download; no partial files on failure; transient drawing/STL scratch files are removed |
| Sheet metal | Yes | No | Not qualified in the browser |
| FEA | Yes | No | Deferred |
-| SQLite materials | Yes | No | Native vararg calls are not browser-safe |
+| Built-in materials | Yes | Yes | Shared managed catalog; same identity, properties and provenance |
+| External SQLite catalogs | Optional adapter | No | `Aetheris.Materials.Sqlite`; excluded from compiler and browser dependencies |
| 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 | Yes | Dedicated module Worker; used by Helios for builds and exports |
diff --git a/docs/public/web-sdk/troubleshooting.md b/docs/public/web-sdk/troubleshooting.md
index 7bf2e080..09773bd9 100644
--- a/docs/public/web-sdk/troubleshooting.md
+++ b/docs/public/web-sdk/troubleshooting.md
@@ -6,4 +6,4 @@ Serve over HTTP(S), not `file://`. Preserve `.wasm` files and serve them as `app
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. Omit it or pass `false`. SQLite materials, external file import, sheet metal, and FEA are likewise outside the admitted browser capability set.
+Use `worker: true` to run builds in the dedicated module Worker; omit it or pass `false` for the direct transport. External SQLite catalogs, external file import, sheet metal, and FEA remain outside the admitted browser capability set. Built-in material resolution uses the shared managed catalog.
diff --git a/docs/release/Aetheris.CLI.README.md b/docs/release/Aetheris.CLI.README.md
index a1d81f53..37223cd9 100644
--- a/docs/release/Aetheris.CLI.README.md
+++ b/docs/release/Aetheris.CLI.README.md
@@ -14,9 +14,9 @@ under the GNU Affero General Public License v3.0 (`AGPL-3.0`); third-party
assets retain their respective licenses and provenance. Alternative licensing
is available on request.
-`aetheris inspect-3dm <file.3dm> [--json]` inventories Rhino/OpenNURBS geometry,
+`aetheris-3dm inspect <file.3dm> [--json]` inventories Rhino/OpenNURBS geometry,
units, topology, and current import blockers. It does not convert 3DM to STEP.
-`aetheris recover-3dm <file.3dm> [--json]` measures provisional analytic and
+`aetheris-3dm recover <file.3dm> [--json]` measures provisional analytic and
non-rational recovery candidates. See `3DM-IMPORT-X0.md` and `3DM-RECOVERY-X1.md`
for the local qualification boundaries.
@@ -26,3 +26,7 @@ discovery and the complete desktop experience.
See the [Aetheris manual](https://yuechen-li-dev.github.io/aetheris/) for the
supported Firmament surface and Preview 3 limitations.
+
+The core CLI bundles no third-party OS-native libraries. The .NET runtime/apphost is still required (or included in self-contained distributions). 3DM inspection and recovery are supplied by the separate `Aetheris.ThreeDm.CLI` tool (`dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease`), which includes native Rhino3dm. The built-in material catalog is managed; custom SQLite catalogs use the optional `Aetheris.Materials.Sqlite` library.
+
+Drawing Notes previews and crops render locally in the browser using bundled PDF.js assets; no CDN or native PDF renderer is required. Headless PNG render/crop commands require `--renderer <path-to-pdftoppm>`, selecting an external Poppler installation explicitly. PDF drawing generation itself remains managed vector output and needs no rasterizer.
diff --git a/fixtures/DrawingNotes/README.md b/fixtures/DrawingNotes/README.md
new file mode 100644
index 00000000..674c0296
--- /dev/null
+++ b/fixtures/DrawingNotes/README.md
@@ -0,0 +1,19 @@
+# Drawing Notes regression sources
+
+- `synthetic-engineering-drawing.pdf`: repository-owned engineering sheet;
+ regenerate with `python fixtures/DrawingNotes/generate_synthetic.py`.
+- `page-coordinates.pdf`: small deterministic PDF 1.7 witness with an inherited,
+ offset CropBox, page rotations 0/90/180/270 and UserUnit 2. Regenerate with
+ `python fixtures/DrawingNotes/generate_page_coordinates.py`. A red rectangle
+ has known physical page-space bounds after each rotation; the browser test
+ checks its actual rendered pixels, not just page metadata.
+
+Run `node scripts/test-drawing-notes-browser.mjs` after building the Release CLI
+to exercise the real server, bundled PDF.js, annotation save/reload and source-linked
+PNG crops. Playwright and a browser are development prerequisites; neither ships
+in the compiler. Output defaults to ignored `artifacts/local/drawing-browser/`.
+Set `AETHERIS_PLAYWRIGHT_MODULE` / `AETHERIS_BROWSER_PATH` for local installations.
+
+Managed inspection and notebook tests run without native libraries. To qualify
+the explicitly external headless renderer as well, set `AETHERIS_TEST_PDFTOPPM`
+to a Poppler pdftoppm executable and run `dotnet test Aetheris.Drawing.Tests`.
diff --git a/fixtures/DrawingNotes/generate_page_coordinates.py b/fixtures/DrawingNotes/generate_page_coordinates.py
new file mode 100644
index 00000000..5fff3b96
--- /dev/null
+++ b/fixtures/DrawingNotes/generate_page_coordinates.py
@@ -0,0 +1,26 @@
+"""Small, repository-owned PDF witness: inherited CropBox, four rotations, UserUnit=2.
+
+The red rectangle is at local (20, 20)..(60, 40) before rotation/scaling.
+Generated bytes are deterministic and contain no third-party drawing content.
+"""
+from pathlib import Path
+
+objects = [
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R 6 0 R] /Count 4 /MediaBox [0 0 400 300] /CropBox [10 20 210 120] >>",
+]
+for rotation in (0, 90, 180, 270):
+ objects.append(f"<< /Type /Page /Parent 2 0 R /Rotate {rotation} /UserUnit 2 /Resources << >> /Contents 7 0 R >>".encode())
+stream = b"1 0 0 rg 30 40 40 20 re f\n"
+objects.append(b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"endstream")
+pdf = bytearray(b"%PDF-1.7\n")
+offsets = [0]
+for i, obj in enumerate(objects, 1):
+ offsets.append(len(pdf))
+ pdf.extend(f"{i} 0 obj\n".encode() + obj + b"\nendobj\n")
+xref = len(pdf)
+pdf.extend(f"xref\n0 {len(offsets)}\n0000000000 65535 f \n".encode())
+for offset in offsets[1:]:
+ pdf.extend(f"{offset:010d} 00000 n \n".encode())
+pdf.extend(f"trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
+Path(__file__).with_name("page-coordinates.pdf").write_bytes(pdf)
diff --git a/fixtures/DrawingNotes/page-coordinates.pdf b/fixtures/DrawingNotes/page-coordinates.pdf
new file mode 100644
index 00000000..1a9c9aad
--- /dev/null
+++ b/fixtures/DrawingNotes/page-coordinates.pdf
@@ -0,0 +1,40 @@
+%PDF-1.7
+1 0 obj
+<< /Type /Catalog /Pages 2 0 R >>
+endobj
+2 0 obj
+<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R 6 0 R] /Count 4 /MediaBox [0 0 400 300] /CropBox [10 20 210 120] >>
+endobj
+3 0 obj
+<< /Type /Page /Parent 2 0 R /Rotate 0 /UserUnit 2 /Resources << >> /Contents 7 0 R >>
+endobj
+4 0 obj
+<< /Type /Page /Parent 2 0 R /Rotate 90 /UserUnit 2 /Resources << >> /Contents 7 0 R >>
+endobj
+5 0 obj
+<< /Type /Page /Parent 2 0 R /Rotate 180 /UserUnit 2 /Resources << >> /Contents 7 0 R >>
+endobj
+6 0 obj
+<< /Type /Page /Parent 2 0 R /Rotate 270 /UserUnit 2 /Resources << >> /Contents 7 0 R >>
+endobj
+7 0 obj
+<< /Length 26 >>
+stream
+1 0 0 rg 30 40 40 20 re f
+endstream
+endobj
+xref
+0 8
+0000000000 65535 f
+0000000009 00000 n
+0000000058 00000 n
+0000000182 00000 n
+0000000284 00000 n
+0000000387 00000 n
+0000000491 00000 n
+0000000595 00000 n
+trailer
+<< /Size 8 /Root 1 0 R >>
+startxref
+670
+%%EOF
diff --git a/scripts/Test-CoreCliPayload.ps1 b/scripts/Test-CoreCliPayload.ps1
new file mode 100644
index 00000000..e842eaf8
--- /dev/null
+++ b/scripts/Test-CoreCliPayload.ps1
@@ -0,0 +1,84 @@
+[CmdletBinding()]
+param(
+ [string]$AssetsPath = "Aetheris.CLI/obj/project.assets.json",
+ [string]$PublishDirectory,
+ [string]$PackagePath
+)
+
+$ErrorActionPreference = 'Stop'
+Add-Type -AssemblyName System.IO.Compression
+Add-Type -AssemblyName System.Reflection.Metadata
+
+function Is-RuntimeOwner([string]$Name) {
+ return $Name -match '^(runtimepack\.)?Microsoft\.NETCore\.App\.Runtime\.'
+}
+
+function Get-NativePaths($Library) {
+ if ($Library.native) { $Library.native.Keys }
+ if ($Library.runtimeTargets) { $Library.runtimeTargets.GetEnumerator() | Where-Object { $_.Value.assetType -eq 'native' } | ForEach-Object Key }
+}
+
+function Test-ResolvedGraph([string]$JsonPath) {
+ $assets = Get-Content -LiteralPath $JsonPath -Raw | ConvertFrom-Json -AsHashtable
+ if (!$assets.targets -or !$assets.targets.Count) { throw "No dependency targets found in $JsonPath" }
+ foreach ($target in $assets.targets.Values) {
+ foreach ($library in $target.GetEnumerator()) {
+ if (Is-RuntimeOwner $library.Key) { continue }
+ $native = @(Get-NativePaths $library.Value)
+ if (@($native | Where-Object { $_ -and $_ -notlike '*/_._' }).Count) {
+ throw "Default CLI resolves third-party native assets from $($library.Key): $($native -join ', ')"
+ }
+ }
+ }
+}
+
+function Test-Payload($Files, $Open) {
+ $deps = @($Files | Where-Object { $_ -match '(^|/)aetheris\.deps\.json$' })
+ if ($deps.Count -ne 1) { throw 'Payload must contain exactly one aetheris.deps.json.' }
+ $allowedRuntimeFiles = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
+ $stream = & $Open $deps[0]
+ $reader = [IO.StreamReader]::new($stream)
+ try { $graph = $reader.ReadToEnd() | ConvertFrom-Json -AsHashtable } finally { $reader.Dispose() }
+ if (!$graph.targets -or !$graph.targets.Count) { throw 'Payload dependency receipt has no targets.' }
+ foreach ($target in $graph.targets.Values) {
+ foreach ($library in $target.GetEnumerator()) {
+ $native = @(Get-NativePaths $library.Value)
+ foreach ($file in ($native | Where-Object { $_ -and $_ -notlike '*/_._' })) {
+ if (!(Is-RuntimeOwner $library.Key)) { throw "Payload contains third-party native dependency $($library.Key): $file" }
+ [void]$allowedRuntimeFiles.Add([IO.Path]::GetFileName($file))
+ }
+ }
+ }
+ foreach ($file in $Files) {
+ $name = [IO.Path]::GetFileName($file)
+ if ($allowedRuntimeFiles.Contains($name)) { continue }
+ if ($file -match '\.(so(\.\d+)*|dylib|node)$') { throw "Unowned native asset in CLI payload: $file" }
+ if ($file -notmatch '\.(dll|exe)$') { continue }
+ # Our own framework-dependent apphost is executable bootstrap code, like .NET itself.
+ if ($name -in @('aetheris.exe', 'aetheris')) { continue }
+ $input = & $Open $file
+ $memory = [IO.MemoryStream]::new()
+ try {
+ $input.CopyTo($memory); $memory.Position = 0
+ $pe = [Reflection.PortableExecutable.PEReader]::new($memory)
+ try { if (!$pe.HasMetadata) { throw "Unowned native PE in CLI payload: $file" } } finally { $pe.Dispose() }
+ }
+ finally { $input.Dispose(); $memory.Dispose() }
+ }
+}
+
+Test-ResolvedGraph $AssetsPath
+if ($PublishDirectory) {
+ $root = [IO.Path]::GetFullPath($PublishDirectory)
+ $files = @(Get-ChildItem -LiteralPath $root -Recurse -File | ForEach-Object { [IO.Path]::GetRelativePath($root, $_.FullName).Replace('\', '/') })
+ Test-Payload $files { param($name) [IO.File]::OpenRead((Join-Path $root $name)) }
+}
+if ($PackagePath) {
+ $archive = [IO.Compression.ZipFile]::OpenRead([IO.Path]::GetFullPath($PackagePath))
+ try {
+ $files = @($archive.Entries | Where-Object { !$_.FullName.EndsWith('/') } | ForEach-Object FullName)
+ Test-Payload $files { param($name) $archive.GetEntry($name).Open() }
+ }
+ finally { $archive.Dispose() }
+}
+Write-Output 'Core CLI dependency graph and supplied payloads contain no third-party OS-native libraries (.NET runtime/apphost excluded).'
diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1
index 165839e8..0a1812a0 100644
--- a/scripts/package-release.ps1
+++ b/scripts/package-release.ps1
@@ -119,7 +119,8 @@ finally { Pop-Location }
# from a clean configuration so identical inputs produce identical archives.
dotnet clean (Join-Path $repoRoot 'Aetheris.slnx') -c Release
-dotnet publish (Join-Path $repoRoot 'Aetheris.CLI/Aetheris.CLI.csproj') -c Release -r win-x64 --self-contained true -t:Rebuild -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $stage 'Aetheris-win-x64')
+dotnet publish (Join-Path $repoRoot 'Aetheris.CLI/Aetheris.CLI.csproj') -c Release -r win-x64 --self-contained true -m:1 -nr:false -p:UseSharedCompilation=false -t:Rebuild -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $stage 'Aetheris-win-x64')
+& (Join-Path $PSScriptRoot 'Test-CoreCliPayload.ps1') -AssetsPath (Join-Path $repoRoot 'Aetheris.CLI/obj/project.assets.json') -PublishDirectory (Join-Path $stage 'Aetheris-win-x64')
dotnet publish (Join-Path $repoRoot 'Aetheris.Forge.Host/Aetheris.Forge.Host.csproj') -c Release -r win-x64 --self-contained true -t:Rebuild -p:PublishAot=true -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $stage 'Aetheris-win-x64/forge-host')
Normalize-PeTimestamps (Join-Path $stage 'Aetheris-win-x64/forge-host/Aetheris.Forge.Host.exe')
dotnet publish (Join-Path $repoRoot 'Aetheris.Server/Aetheris.Server.csproj') -c Release -r win-x64 --self-contained true -t:Rebuild -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $stage 'Aetheris-win-x64/cadmata')
@@ -174,8 +175,9 @@ foreach ($relativeExample in $publicExamples) {
}
# Build the framework-dependent tool payload explicitly. Reusing the preceding
# RID-specific publish output can package stale non-RID bytes with a new filename.
-dotnet pack (Join-Path $repoRoot 'Aetheris.CLI/Aetheris.CLI.csproj') -c Release -t:Rebuild -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $output 'packages')
+dotnet pack (Join-Path $repoRoot 'Aetheris.CLI/Aetheris.CLI.csproj') -c Release -m:1 -nr:false -p:UseSharedCompilation=false -t:Rebuild -p:Version=$Version -p:DebugType=None -p:DebugSymbols=false -o (Join-Path $output 'packages')
Get-ChildItem -LiteralPath (Join-Path $output 'packages') -Filter '*.nupkg' -File | ForEach-Object { Normalize-ZipArchive $_.FullName -NuGetPackage }
+Get-ChildItem -LiteralPath (Join-Path $output 'packages') -Filter 'Aetheris.CLI.*.nupkg' -File | ForEach-Object { & (Join-Path $PSScriptRoot 'Test-CoreCliPayload.ps1') -AssetsPath (Join-Path $repoRoot 'Aetheris.CLI/obj/project.assets.json') -PackagePath $_.FullName }
Get-ChildItem -LiteralPath $stage -Recurse -Filter '*.pdb' -File | Remove-Item -Force
$extensionRoot = Join-Path $repoRoot 'tools/vscode-firmament'
diff --git a/scripts/test-drawing-notes-browser.mjs b/scripts/test-drawing-notes-browser.mjs
new file mode 100644
index 00000000..57dd30b5
--- /dev/null
+++ b/scripts/test-drawing-notes-browser.mjs
@@ -0,0 +1,105 @@
+// Real browser + CLI/server regression. No test server or substitute PDF renderer.
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const output = path.resolve(root, process.env.AETHERIS_DRAWING_EVIDENCE ?? 'artifacts/local/drawing-browser');
+const cli = path.join(root, 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll');
+const { chromium } = await import(process.env.AETHERIS_PLAYWRIGHT_MODULE ?? 'playwright');
+const browser = await chromium.launch(process.env.AETHERIS_BROWSER_PATH ? { executablePath: process.env.AETHERIS_BROWSER_PATH } : {});
+const port = Number(process.env.AETHERIS_DRAWING_PORT ?? 4188);
+const url = `http://127.0.0.1:${port}`;
+await fs.mkdir(output, { recursive: true });
+
+async function command(args) {
+ const child = spawn('dotnet', [cli, ...args], { cwd: root, windowsHide: true });
+ let error = ''; child.stderr.on('data', b => error += b);
+ await new Promise((resolve, reject) => { child.on('error', reject); child.on('exit', code => code === 0 ? resolve() : reject(new Error(error))); });
+}
+async function ready(server) {
+ for (let n = 0; n < 100; n++) {
+ if (server.exitCode !== null) throw new Error(`Drawing server exited ${server.exitCode}`);
+ try { if ((await fetch(`${url}/api/project`)).ok) return; } catch {}
+ await new Promise(r => setTimeout(r, 100));
+ }
+ throw new Error('Drawing server did not start');
+}
+
+const results = [];
+try {
+ for (const fixture of ['page-coordinates.pdf', 'synthetic-engineering-drawing.pdf']) {
+ const notes = path.join(output, path.basename(fixture, '.pdf'));
+ const source = path.join(root, 'fixtures/DrawingNotes', fixture);
+ await command(['drawing', 'notes', 'create', source, '--out', notes]);
+ const projectPath = path.join(notes, 'drawing-notes.json');
+ const server = spawn('dotnet', [cli, 'drawing', 'notes', 'serve', projectPath, '--source', source, '--port', String(port)], { cwd: root, windowsHide: true });
+ const serverLog = []; server.stderr.on('data', b => serverLog.push(b.toString()));
+ const page = await browser.newPage({ viewport: { width: 1400, height: 950 }, acceptDownloads: true });
+ const errors = []; page.on('pageerror', e => errors.push(e.message));
+ try {
+ await ready(server);
+ const fallback = await fetch(`${url}/pdfjs/wasm/jbig2_nowasm_fallback.js`);
+ assert.ok(fallback.ok && fallback.headers.get('content-type')?.includes('javascript'), 'PDF.js fallback modules need JavaScript MIME types');
+ await page.goto(url);
+ await page.waitForFunction(() => document.querySelector('#status').textContent === 'Saved');
+ const project = JSON.parse(await fs.readFile(projectPath, 'utf8'));
+ for (const metadata of project.document.pages) {
+ await page.locator(`[data-page="${metadata.number}"]`).click();
+ await page.waitForFunction(([w, h]) => {
+ const c = document.querySelector('#pageImage');
+ return document.querySelector('#status').textContent === 'Saved' && c.width === Math.ceil(w * 2.5) && c.height === Math.ceil(h * 2.5);
+ }, [metadata.widthPoints, metadata.heightPoints]);
+ if (fixture === 'page-coordinates.pdf') {
+ const pixels = await page.locator('#pageImage').evaluate(canvas => {
+ const { data } = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
+ let minX = canvas.width, minY = canvas.height, maxX = -1, maxY = -1;
+ for (let y = 0; y < canvas.height; y++) for (let x = 0; x < canvas.width; x++) {
+ const i = (y * canvas.width + x) * 4;
+ if (data[i] > 220 && data[i + 1] < 30 && data[i + 2] < 30) { minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); }
+ }
+ return [minX / 2.5, minY / 2.5, (maxX + 1) / 2.5, (maxY + 1) / 2.5];
+ });
+ const expected = [[40, 120, 120, 160], [40, 40, 80, 120], [280, 40, 360, 80], [120, 280, 160, 360]][metadata.number - 1];
+ pixels.forEach((v, i) => assert.ok(Math.abs(v - expected[i]) < 1, `${metadata.number}: pixel bound ${pixels} != ${expected}`));
+ results.push({ page: metadata.number, metadata, redBounds: pixels });
+ }
+ }
+ await page.locator('[data-page="1"]').click();
+ await page.waitForFunction(() => document.querySelector('#status').textContent === 'Saved');
+ const m = project.document.pages[0], overlay = await page.locator('#overlay').boundingBox();
+ const start = { x: overlay.x + 40 / m.widthPoints * overlay.width, y: overlay.y + 50 / m.heightPoints * overlay.height };
+ const end = { x: overlay.x + 120 / m.widthPoints * overlay.width, y: overlay.y + 90 / m.heightPoints * overlay.height };
+ await page.mouse.move(start.x, start.y); await page.mouse.down(); await page.mouse.move(end.x, end.y, { steps: 4 }); await page.mouse.up(); await page.keyboard.press('v');
+ await page.waitForFunction(() => document.querySelector('#status').textContent === 'Saved');
+ const saved = JSON.parse(await fs.readFile(projectPath, 'utf8'));
+ const region = saved.regions.at(-1);
+ assert.ok(Math.abs(region.bounds.x - 40) < 1 && Math.abs(region.bounds.y - 50) < 1);
+ assert.ok(Math.abs(region.bounds.width - 80) < 1 && Math.abs(region.bounds.height - 40) < 1);
+ const downloads = [];
+ page.on('download', d => downloads.push(d));
+ await page.locator('#crop').click();
+ await page.waitForFunction(() => document.querySelector('#status').textContent.startsWith('Crop exported'));
+ for (let n = 0; downloads.length < 2 && n < 100; n++) await new Promise(r => setTimeout(r, 50));
+ assert.equal(downloads.length, 2);
+ for (const d of downloads) await d.saveAs(path.join(notes, d.suggestedFilename()));
+ const crop = JSON.parse(await fs.readFile(path.join(notes, downloads.find(d => d.suggestedFilename().endsWith('.json')).suggestedFilename()), 'utf8'));
+ assert.equal(crop.documentSha256, project.document.sha256); assert.equal(crop.page, 1); assert.equal(crop.dpi, 300);
+ assert.deepEqual(crop.bounds, region.bounds); assert.equal(crop.rendererVersion, 'PDF.js-6.4.299');
+ await page.reload(); await page.waitForFunction(() => document.querySelector('#status').textContent === 'Saved');
+ assert.equal(await page.locator('#overlay .box').count(), saved.regions.length + saved.annotations.length);
+ await page.screenshot({ path: path.join(notes, 'browser.png') });
+ assert.deepEqual(errors, []);
+ results.push({ fixture, savedRegion: region, crop });
+ } finally {
+ await page.close();
+ server.kill('SIGTERM');
+ await new Promise(resolve => server.exitCode !== null ? resolve() : server.once('exit', resolve));
+ await fs.writeFile(path.join(notes, 'server.log'), serverLog.join(''));
+ }
+ }
+ await fs.writeFile(path.join(output, 'results.json'), JSON.stringify(results, null, 2));
+ console.log('Drawing Notes browser qualification passed: real PDF rendering, rotations, inherited CropBox/UserUnit, pixel bounds, annotation save/reload and source-linked PNG crops.');
+} finally { await browser.close(); }