Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/build-packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ jobs:
- name: Install .NET SDK
uses: actions/setup-dotnet@v5
with:
dotnet-version: 11.x
dotnet-version: |
8.0.x
10.0.x
11.x

- name: Install Linux build prerequisites
shell: bash
Expand Down Expand Up @@ -98,6 +101,10 @@ jobs:
shell: bash
run: dotnet test --solution typstsharp.slnx

- name: Run tests against the .NET Standard 2.1 assembly
shell: bash
run: dotnet test --project src/typstsharp.tests/typstsharp.tests.csproj --framework net10.0 -p:TestNetStandardLibrary=true

pack-runtime:
name: Pack typstsharp.runtime.${{ matrix.rid }}
runs-on: ${{ matrix.os }}
Expand Down
14 changes: 12 additions & 2 deletions .github/workflows/pack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ jobs:
if: matrix.test_type == ''
uses: actions/setup-dotnet@v5
with:
dotnet-version: 11.x
dotnet-version: |
8.0.x
10.0.x
11.x

- name: Run tests (native host)
if: matrix.test_type == ''
Expand All @@ -111,6 +114,10 @@ jobs:
run: |
docker run --rm -v ${{ github.workspace }}:/workspace -w /workspace mcr.microsoft.com/dotnet/sdk:11.0-alpine sh -c "
set -eu
apk add --no-cache curl bash
curl -fsSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh
bash /tmp/dotnet-install.sh --channel 8.0 --runtime dotnet --install-dir /usr/share/dotnet
bash /tmp/dotnet-install.sh --channel 10.0 --runtime dotnet --install-dir /usr/share/dotnet
dotnet nuget add source /workspace/artifacts --name local-artifacts
dotnet nuget locals all --clear
dotnet restore src/typstsharp.tests/typstsharp.tests.csproj -p:UsePackagedLibrary=true -p:PackageVersion=${{ needs.version.outputs.package_version }}
Expand All @@ -124,7 +131,10 @@ jobs:
docker run --rm -v ${{ github.workspace }}:/workspace -w /workspace fedora:40 sh -c "
set -eu
dnf install -y curl tar icu
curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel 11.0 --install-dir /usr/share/dotnet
curl -fsSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh
bash /tmp/dotnet-install.sh --channel 11.0 --install-dir /usr/share/dotnet
bash /tmp/dotnet-install.sh --channel 8.0 --runtime dotnet --install-dir /usr/share/dotnet
bash /tmp/dotnet-install.sh --channel 10.0 --runtime dotnet --install-dir /usr/share/dotnet
ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
dotnet nuget add source /workspace/artifacts --name local-artifacts
dotnet nuget locals all --clear
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# typstsharp

A .NET 11.0 wrapper around the Typst 0.15 rendering stack. The managed layer in `src/typstsharp` calls into the Rust `typst_core` crate via P/Invoke and exposes convenient helpers for C# consumers plus a simple CLI.
A .NET wrapper around the Typst 0.15 rendering stack that targets .NET Standard 2.1, .NET 8, .NET 10, and .NET 11. The managed layer in `src/typstsharp` calls into the Rust `typst_core` crate via P/Invoke and exposes convenient helpers for C# consumers plus a simple CLI.

For the latest changes, see our [Release Notes](RELEASENOTES.md).

Expand Down Expand Up @@ -305,7 +305,7 @@ You only need to install the main `typstsharp` package. Portable builds (`dotnet

## Prerequisites

- [.NET SDK 11.0](https://dotnet.microsoft.com/) – required to build the managed projects.
- [.NET SDK 11.0](https://dotnet.microsoft.com/) – required to build the managed projects. Install the .NET 8 and .NET 10 runtimes as well to run the tests on all target frameworks.
- [Rust toolchain](https://www.rust-lang.org/tools/install) (with `cargo`) – **only required if you are building the project from source.** The NuGet packages include pre-compiled native binaries.

## Building
Expand Down Expand Up @@ -334,9 +334,11 @@ dotnet pack src/typstsharp.runtime/typstsharp.runtime.csproj -c Release -p:Runti

```pwsh
# after a successful build
dotnet run --project src/typstsharp.cli/typstsharp.cli.csproj
dotnet run --project src/typstsharp.cli/typstsharp.cli.csproj --framework net11.0
```

Use `--framework net8.0` or `--framework net10.0` to run the CLI on either of those installed runtimes.

Because the Rust binary is registered as a runtime asset, `typst_core.dll`, `libtypst_core.so`, or `libtypst_core.dylib` will appear beside the CLI executable automatically.

## Notes
Expand Down
3 changes: 2 additions & 1 deletion RELEASENOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
- Fixed `ua-1` (PDF/UA-1, the accessibility standard) being rejected by `pdfStandards`. The accepted names are now taken from `typst_pdf::PdfStandard` itself, so every standard Typst supports is accepted, including ones added by later Typst releases. The documented `v-` prefix on plain PDF versions still works, and applies only to them: `v-a-2b` is not a spelling of `a-2b`.

### Changed
- **Breaking:** Upgraded target frameworks to `net10.0` and `net11.0`, removing deprecated `net8` and `net9` targets.
- The library and CLI target `net8.0`, `net10.0`, and `net11.0`.
- `TypstCompiler.FromSource(...)` and the static one-shot helpers no longer copy the source onto the managed heap before handing it to the compiler. It is encoded straight into the native buffer, so a source over roughly 42,500 characters no longer puts an array on the large object heap for the duration of one call: a 200 KB source measured 200,024 bytes of managed heap before and none after. Native memory allocated while building a compiler is also released now when construction fails part way through, rather than leaking.
- **Breaking (binary):** `SvgResult.GetEnumerator()` and `PngResult.GetEnumerator()` now return `PageEnumerator<T>` rather than `IEnumerator<T>`, so that `foreach` over a result no longer boxes the enumerator. Source-compatible: `foreach`, LINQ, `Count` and the indexer all keep compiling. Because a return type is part of the method signature and the compiler emits a direct call for pattern-based `foreach`, an assembly compiled against an earlier version throws `MissingMethodException` on that `foreach` until it is recompiled.
- **Breaking:** an invalid combination of PDF standards now fails the compilation instead of silently producing an ordinary PDF. The validation error from `PdfStandards::new` was discarded and export fell back to the default, so a pipeline could believe it was writing PDF/A while it was not. Combinations such as two PDF/A levels, or a PDF/A level that contradicts the requested PDF version, now throw with the message and hints from Typst. Callers passing a contradictory combination today receive a document and will receive an exception after this change.
Expand All @@ -20,6 +20,7 @@
- The native library is now built with size optimisation (`opt-level = "z"`), thin LTO (`lto = "thin"`), a single codegen unit, symbol stripping (`strip = "symbols"`), and single-target crate compilation (`--crate-type cdylib`), so that LTO runs across the dependency graph and unreferenced symbols and DWARF debug sections are stripped.

### Added
- Added a `netstandard2.1` target for the NuGet library. A compatible native Typst runtime is still required.
- Added `TypstCompilerPool` for high-concurrency and ASP.NET Core workloads. It lazily pools up to `Environment.ProcessorCount` (or a configured `maxConcurrency`) `TypstCompiler` instances, bounds concurrent native compilations, applies per-request `sys.inputs` or updated source strings atomically, and returns the compiler to the pool before the caller streams the resulting zero-copy `TypstDocument`.
- Added concurrent-access detection on `TypstCompiler`: using a single `TypstCompiler` instance from two threads simultaneously now throws `InvalidOperationException` with guidance to use `TypstCompilerPool`, rather than racing on the underlying native `SystemWorld`.
- Added `compiler.SetSource(string source)` (and `pool.CompileSourceToDocument` / `CompileSourceToDocumentAsync`) to update an in-memory compiler's main document source in place, preserving its `FileId` and using Typst's incremental `Source::replace` diffing across compilations.
Expand Down
2 changes: 1 addition & 1 deletion src/typstsharp.cli/typstsharp.cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<TargetFrameworks>net8.0;net10.0;net11.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
6 changes: 4 additions & 2 deletions src/typstsharp.tests/typstsharp.tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<TargetFrameworks>net8.0;net10.0;net11.0</TargetFrameworks>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
Expand All @@ -15,7 +15,9 @@
</ItemGroup>

<ItemGroup Condition="'$(UsePackagedLibrary)' != 'true'">
<ProjectReference Include="..\typstsharp\typstsharp.csproj" />
<ProjectReference Include="..\typstsharp\typstsharp.csproj">
<SetTargetFramework Condition="'$(TestNetStandardLibrary)' == 'true'">TargetFramework=netstandard2.1</SetTargetFramework>
</ProjectReference>
</ItemGroup>

<ItemGroup Condition="'$(UsePackagedLibrary)' == 'true'">
Expand Down
31 changes: 31 additions & 0 deletions src/typstsharp/Guard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Diagnostics.CodeAnalysis;

namespace typstsharp;

internal static class Guard
{
internal static void NotNull([NotNull] object? value, string paramName)
{
if (value is null)
throw new ArgumentNullException(paramName);
}

internal static void NotNullOrEmpty([NotNull] string? value, string paramName)
{
NotNull(value, paramName);
if (value.Length == 0)
throw new ArgumentException("The value cannot be an empty string.", paramName);
}

internal static void NotNegative(int value, string paramName)
{
if (value < 0)
throw new ArgumentOutOfRangeException(paramName, value, "The value must be non-negative.");
}

internal static void NotDisposed(bool disposed, object instance)
{
if (disposed)
throw new ObjectDisposedException(instance.GetType().FullName);
}
}
5 changes: 5 additions & 0 deletions src/typstsharp/IsExternalInit.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#if NETSTANDARD2_1
namespace System.Runtime.CompilerServices;

internal static class IsExternalInit;
#endif
4 changes: 2 additions & 2 deletions src/typstsharp/NativeBuffers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public NativeBufferMemoryManager(TypstDocument owner, byte* pointer, int length)

public override Span<byte> GetSpan()
{
ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner);
Guard.NotDisposed(_owner.IsDisposed, _owner);
return new Span<byte>(_pointer, _length);
}

Expand All @@ -38,7 +38,7 @@ public override Span<byte> GetSpan()
/// </summary>
public override MemoryHandle Pin(int elementIndex = 0)
{
ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner);
Guard.NotDisposed(_owner.IsDisposed, _owner);

if ((uint)elementIndex > (uint)_length)
{
Expand Down
26 changes: 13 additions & 13 deletions src/typstsharp/TypstCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ public static int MaxCacheAge
get => checked((int)CsBindgen.NativeMethods.get_max_cache_age());
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
Guard.NotNegative(value, nameof(value));
CsBindgen.NativeMethods.set_max_cache_age((nuint)value);
}
}
Expand Down Expand Up @@ -364,7 +364,7 @@ public static int MaxCacheAge
/// <exception cref="InvalidOperationException">Thrown if the native eviction failed.</exception>
public static void EvictCache(int maxAge)
{
ArgumentOutOfRangeException.ThrowIfNegative(maxAge);
Guard.NotNegative(maxAge, nameof(maxAge));
if (!CsBindgen.NativeMethods.evict_cache_with_max_age((nuint)maxAge))
{
throw new InvalidOperationException("Typst failed to evict its compilation cache.");
Expand Down Expand Up @@ -597,7 +597,7 @@ public PdfResult CompilePdf(IEnumerable<string>? pdfStandards = null)
/// <returns>The warnings reported by the Typst compiler.</returns>
public IReadOnlyList<string> CompilePdf(string outputFile, IEnumerable<string>? pdfStandards = null)
{
ArgumentException.ThrowIfNullOrEmpty(outputFile);
Guard.NotNullOrEmpty(outputFile, nameof(outputFile));

using var document = CompileToDocument("pdf", pdfStandards: pdfStandards);
document.WriteOutputToFile(outputFile);
Expand All @@ -614,7 +614,7 @@ public IReadOnlyList<string> CompilePdf(string outputFile, IEnumerable<string>?
/// <returns>The warnings reported by the Typst compiler.</returns>
public async Task<IReadOnlyList<string>> CompilePdfAsync(string outputFile, IEnumerable<string>? pdfStandards = null, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(outputFile);
Guard.NotNullOrEmpty(outputFile, nameof(outputFile));

using var document = CompileToDocument("pdf", pdfStandards: pdfStandards);
await document.WriteOutputToFileAsync(outputFile, cancellationToken: cancellationToken).ConfigureAwait(false);
Expand All @@ -630,7 +630,7 @@ public async Task<IReadOnlyList<string>> CompilePdfAsync(string outputFile, IEnu
/// <returns>The warnings reported by the Typst compiler.</returns>
public IReadOnlyList<string> CompilePdf(Stream destination, IEnumerable<string>? pdfStandards = null)
{
ArgumentNullException.ThrowIfNull(destination);
Guard.NotNull(destination, nameof(destination));

using var document = CompileToDocument("pdf", pdfStandards: pdfStandards);
document.CopyOutputTo(destination);
Expand All @@ -647,7 +647,7 @@ public IReadOnlyList<string> CompilePdf(Stream destination, IEnumerable<string>?
/// <returns>The warnings reported by the Typst compiler.</returns>
public async Task<IReadOnlyList<string>> CompilePdfAsync(Stream destination, IEnumerable<string>? pdfStandards = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(destination);
Guard.NotNull(destination, nameof(destination));

using var document = CompileToDocument("pdf", pdfStandards: pdfStandards);
await document.CopyOutputToAsync(destination, cancellationToken: cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -733,7 +733,7 @@ public record TypstWarning(string Message);
/// <param name="mergedGap">The distance between neighbouring pages in a merged SVG, in points.</param>
public void Compile(string outputFile, string format, float ppi = 144.0f, IEnumerable<string>? pdfStandards = null, float mergedGap = 0f)
{
ArgumentException.ThrowIfNullOrEmpty(outputFile);
Guard.NotNullOrEmpty(outputFile, nameof(outputFile));

using var document = CompileToDocument(format, ppi, pdfStandards, mergedGap);
if (document.OutputCount == 1)
Expand Down Expand Up @@ -764,7 +764,7 @@ public void Compile(string outputFile, string format, float ppi = 144.0f, IEnume
/// <exception cref="InvalidOperationException">Thrown if the compiler is already in use on another thread or if updating the source fails.</exception>
public unsafe void SetSource(string source)
{
ArgumentNullException.ThrowIfNull(source);
Guard.NotNull(source, nameof(source));
EnterExclusiveUse();
try
{
Expand Down Expand Up @@ -807,7 +807,7 @@ public unsafe void SetSource(string source)
/// <exception cref="Exception">Thrown if the inputs fail to be set in the native compiler.</exception>
public void SetSysInputs(IDictionary<string, string> inputs)
{
ArgumentNullException.ThrowIfNull(inputs);
Guard.NotNull(inputs, nameof(inputs));
var sysInputsJson = JsonSerializer.Serialize<IDictionary<string, string>>(inputs, sourceGenOptions);
SetSysInputsJson(sysInputsJson);
}
Expand All @@ -823,8 +823,8 @@ public void SetSysInputs(IDictionary<string, string> inputs)
/// <param name="jsonTypeInfo">The source-generated <see cref="JsonTypeInfo{T}"/> metadata.</param>
public void SetSysInputs<T>(T inputs, JsonTypeInfo<T> jsonTypeInfo)
{
ArgumentNullException.ThrowIfNull(inputs);
ArgumentNullException.ThrowIfNull(jsonTypeInfo);
Guard.NotNull(inputs, nameof(inputs));
Guard.NotNull(jsonTypeInfo, nameof(jsonTypeInfo));
var sysInputsJson = JsonSerializer.Serialize(inputs, jsonTypeInfo);
SetSysInputsJson(sysInputsJson);
}
Expand All @@ -839,7 +839,7 @@ public void SetSysInputs<T>(T inputs, JsonTypeInfo<T> jsonTypeInfo)
/// <exception cref="InvalidOperationException">Thrown if <paramref name="json"/> is not a valid JSON object or the compiler is in use on another thread.</exception>
public unsafe void SetSysInputsJson(string json)
{
ArgumentNullException.ThrowIfNull(json);
Guard.NotNull(json, nameof(json));
EnterExclusiveUse();
try
{
Expand Down Expand Up @@ -916,7 +916,7 @@ protected virtual unsafe void Dispose(bool disposing)

private void EnterExclusiveUse()
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
Guard.NotDisposed(Volatile.Read(ref _disposed) != 0, this);

if (Interlocked.CompareExchange(ref _inUse, 1, 0) != 0)
{
Expand Down
Loading