### registry.json example Source: https://github.com/bdovaz/unitynuget Example of the registry.json schema showing package entries with properties like listed, version, analyzer, and ignore. ```json { "Acornima": { "listed": true, "version": "0.9.0" }, "Akka.Analyzers": { "listed": true, "version": "0.3.3", "analyzer": true }, "Microsoft.CSharp": { "ignore": true } } ``` -------------------------------- ### All method - get all listed packages Source: https://github.com/bdovaz/unitynuget Returns the NpmPackageListAllResponse containing only listed packages (NpmPackageRegistry.ListedPackageInfos). This is the payload for the GET /-/all npm endpoint. The dictionary keys are the npm package IDs ({scope}.{id}). ```csharp /// /// Get all packages registered. /// /// A list of packages registered public NpmPackageListAllResponse All() { return _npmPackageRegistry.ListedPackageInfos; } ``` -------------------------------- ### GET /-/all response body shape Source: https://github.com/bdovaz/unitynuget Example JSON response for `GET /-/all`. Each value is an `NpmPackageInfo`; the converter flattens `Packages` into an object keyed by package id. ```json { "_updated": 99999, "org.nuget.serilog": { "name": "org.nuget.serilog", "description": "...", "maintainers": [], "versions": { "2.10.0": "latest" }, "keywords": [], "author": "..." } } ``` -------------------------------- ### Usage example for RegistryProgressEventArgs Source: https://github.com/bdovaz/unitynuget Subscribes to OnProgress to display a progress percentage. Handles Total being zero to avoid division by zero. ```csharp cache.OnProgress = (_, e) => { double percent = e.Total != 0 ? (double)e.Current * 100 / e.Total : 0; Console.WriteLine($"\rBuilding packages: {percent:F1}% ({e.Current}/{e.Total})"); }; ``` -------------------------------- ### Run the tool (one-shot conversion) Source: https://github.com/bdovaz/unitynuget Installs the tool globally, changes to a working directory containing appsettings.json and registry.json, runs unityNuGet, and checks the exit code. Exit code 0 indicates success, -1 indicates any build error. ```bash dotnet tool install -g UnityNuGet.Tool cd /path/to/working/dir # contains appsettings.json + registry.json unityNuGet echo $? # 0 on success, -1 on any build error ``` -------------------------------- ### Usage example for RegistryLogEventArgs Source: https://github.com/bdovaz/unitynuget Subscribes to OnWarning and OnError to write messages to the console. Requires a built RegistryCache instance. ```csharp RegistryCache cache = BuildCache(registry, options, logger, signer); cache.OnWarning = (_, e) => Console.Error.WriteLine($"Warning: {e.Message}"); cache.OnError = (_, e) => Console.Error.WriteLine($"Error: {e.Message}"); await cache.Build(); ``` -------------------------------- ### All() Source: https://github.com/bdovaz/unitynuget Retrieves all packages registered in the npm registry cache. Returns a list of listed packages, which is the payload for the GET /-/all npm endpoint. ```APIDOC ## All() ### Description Get all packages registered. ### Method All ### Endpoint All() ### Parameters *(none)* ### Response Returns `NpmPackageListAllResponse` containing only listed packages (`NpmPackageRegistry.ListedPackageInfos`). The dictionary keys are the npm package IDs (`{scope}.{id}`). ``` -------------------------------- ### registry.json entry with full options Source: https://github.com/bdovaz/unitynuget Example registry.json entry showing all available options for a package, including listed, version, defineConstraints, analyzer, includePrerelease, and includeUnlisted. Also shows an ignored entry for Microsoft.CSharp. ```json { "My.Package": { "listed": true, "version": "2.0.0", "defineConstraints": [ "!UNITY_2021_2_OR_NEWER" ], "analyzer": false, "includePrerelease": false, "includeUnlisted": false }, "Microsoft.CSharp": { "ignore": true } } ``` -------------------------------- ### Registry Registration in a Host Source: https://github.com/bdovaz/unitynuget Shows how to register the Registry as a singleton and hosted service in a .NET host. The Registry is started automatically and loads the registry file before the cache updater runs. ```APIDOC ### Description Registers the Registry as a singleton and hosted service in a .NET host. The Registry is started automatically and loads the registry file before the cache updater runs. ### Code ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using UnityNuGet; HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); builder.Services.AddSingleton(); builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); builder.Services.Configure(builder.Configuration.GetSection("Registry")); IHost host = builder.Build(); await host.RunAsync(); ``` ``` -------------------------------- ### Count Source: https://github.com/bdovaz/unitynuget Gets the number of package entries loaded from the registry file. Accessing this property before StartAsync completes will throw a NullReferenceException. ```APIDOC ## Count ### Description Gets the number of package entries loaded from the registry file. Accessing this property before StartAsync completes will throw a NullReferenceException. ### Property `public int Count` ### Returns - **int** - Number of package entries loaded from the registry file. ### Remarks Reads the backing dictionary with the null-forgiving operator (`_data!`), so accessing it before `StartAsync` has completed results in a `NullReferenceException`. ``` -------------------------------- ### GET /-/all Source: https://github.com/bdovaz/unitynuget Returns a list of all packages in the registry. The response is an NpmPackageListAllResponse serialized by UnityNuGetJsonSerializerContext, with the Packages collection flattened into an object keyed by package id. ```APIDOC ## GET /-/all ### Description Returns a list of all packages in the registry. The response is an NpmPackageListAllResponse serialized by UnityNuGetJsonSerializerContext, with the Packages collection flattened into an object keyed by package id. ### Method GET ### Endpoint /-/all ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **_updated** (number) - Timestamp of the last update. - **{packageId}** (NpmPackageInfo) - Object keyed by package id, each value is an NpmPackageInfo. ### Request Example None ### Response Example ```json { "_updated": 99999, "org.nuget.serilog": { "name": "org.nuget.serilog", "description": "...", "maintainers": [], "versions": { "2.10.0": "latest" }, "keywords": [], "author": "..." } } ``` ### Error Response - **200** with an `NpmError` body (see error codes below). Note: `Results.Json(error, ...)` also returns status 200 — the npm-compatible `NpmError` body signals failure, not the HTTP status code. ``` -------------------------------- ### GET /-/all Source: https://github.com/bdovaz/unitynuget Returns the npm 'all packages' listing. This endpoint provides a list of all available packages in the registry. ```APIDOC ## GET /-/all ### Description Returns the npm 'all packages' listing. This endpoint provides a list of all available packages in the registry. ### Method GET ### Endpoint /-/all ### Response #### Success Response (200 OK) - **Body** (JSON) - The list of all packages. ### Request Example ``` GET /-/all HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 200 OK Content-Type: application/json { "_updated": 1234567890, "package1": {}, "package2": {} } ``` ``` -------------------------------- ### NuGetRedirectLogger usage example Source: https://github.com/bdovaz/unitynuget Shows how to create a NuGetRedirectLogger with a console logger and pass it to NuGet APIs that accept an ILogger, such as PackageMetadataResource.GetMetadataAsync. ```csharp using Microsoft.Extensions.Logging; using UnityNuGet; ILoggerFactory loggerFactory = LoggerFactory.Create(b => b.AddConsole()); ILogger logger = loggerFactory.CreateLogger("NuGet"); NuGetRedirectLogger redirect = new(logger); // Pass redirect wherever NuGet APIs accept an ILogger: // e.g. PackageMetadataResource.GetMetadataAsync(..., redirect, cancellationToken) ``` -------------------------------- ### NuGetConsoleLogger usage example Source: https://github.com/bdovaz/unitynuget Shows how to use NuGetConsoleLogger with PackageMetadataResource.GetMetadataAsync to retrieve package metadata from nuget.org. ```csharp using NuGet.Protocol.Core.Types; using UnityNuGet; var repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json"); var resource = await repository.GetResourceAsync(); IEnumerable metas = await resource.GetMetadataAsync( "serilog", includePrerelease: false, includeUnlisted: false, new SourceCacheContext(), new NuGetConsoleLogger(), CancellationToken.None); ``` -------------------------------- ### GetPackage method - get a specific package Source: https://github.com/bdovaz/unitynuget Returns the NpmPackage (full version listing) or null if the package is not in the registry cache. Throws ArgumentNullException if packageId is null. This powers the GET /{id} endpoint; the HTTP layer converts the null result into NpmError.NotFound. ```csharp /// /// Get a specific package for the specified package id. /// /// /// A npm package or null if not found public NpmPackage? GetPackage(string packageId) { ArgumentNullException.ThrowIfNull(packageId); _npmPackageRegistry.Packages.TryGetValue(packageId, out NpmPackage? package); return package; } ``` -------------------------------- ### MapMethods for GET|HEAD /{id}/-/{file} Source: https://github.com/bdovaz/unitynuget Registers the GET and HEAD methods for the package file download endpoint. Validates the file name pattern and existence, returns the file for GET, and sets headers with content length for HEAD. Returns not_found or not_initialized errors as JSON. ```csharp builder.MapMethods("{id}/-/{file}", new[] { HttpMethod.Head.Method, HttpMethod.Get.Method }, handler: (string id, string file, HttpContext httpContext, RegistryCacheSingleton registryCacheSingleton, RegistryCacheReport registryCacheReport) => { if (!TryGetInstance(registryCacheSingleton, registryCacheReport, out RegistryCache? instance, out NpmError? error)) { return Results.Json(error, UnityNuGetJsonSerializerContext.Default); } NpmPackage? package = instance?.GetPackage(id); if (package == null) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } if (!file.StartsWith(id + "-") || !file.EndsWith(".tgz")) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } string? filePath = instance?.GetPackageFilePath(file); if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } // This method can be called with HEAD request, so in that case we just calculate the content length if (httpContext.Request.Method.Equals(HttpMethod.Head.Method)) { httpContext.Response.ContentType = "application/octet-stream"; httpContext.Response.ContentLength = new FileInfo(filePath).Length; return Results.Ok(); } else { return Results.File(filePath, "application/octet-stream", file); } }); ``` -------------------------------- ### GET / Source: https://github.com/bdovaz/unitynuget Redirects to the npm all packages listing at /-/all. Returns a 302 Found with an empty body and a Location header pointing to /-/all. ```APIDOC ## GET / ### Description Redirects to the npm all packages listing at /-/all. ### Method GET ### Endpoint / ### Response #### Success Response (302 Found) - **Location** (string) - The redirect target: `/-/all` - **Body** - empty ### Request Example ``` GET / HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 302 Found Location: /-/all ``` ``` -------------------------------- ### GET /{id} response body shape Source: https://github.com/bdovaz/unitynuget Example JSON response for `GET /{id}`. Shows the abbreviated npm format with `_id`, `_rev`, `dist-tags`, `versions`, `time`, and `users` fields. ```json { "_id": "org.nuget.serilog", "_rev": "1-0", "name": "org.nuget.serilog", "dist-tags": { "latest": "2.10.0" }, "versions": { "2.10.0": { "name": "org.nuget.serilog", "version": "2.10.0", "dist": { "tarball": "https://.../org.nuget.serilog/-/org.nuget.serilog-2.10.0.tgz", "shasum": "..." }, "dependencies": {}, "_id": "org.nuget.serilog@2.10.0", "unity": "2019.1", "displayName": "Serilog (NuGet)" } }, "time": { "2.10.0": "2021-..." }, "users": {} } ``` -------------------------------- ### Docker Compose Environment Mapping Source: https://github.com/bdovaz/unitynuget Shows the full option surface of the UnityNuGet registry as environment variables in a docker-compose.yml file. Use this to configure the registry when running via Docker Compose. The example includes all configuration keys, such as Registry:RootHttpUrl, Registry:UnityScope, and Signing:UpmServiceAccountKeyId. ```yaml environment: - Registry:RootHttpUrl=http://localhost:5000/ - Registry:Filter= - Registry:UnityScope=org.custom - Registry:MinimumUnityVersion=2020.1 - Registry:PackageNameNuGetPostFix= (Custom NuGet) - Registry:PackageKeywords:0=customKeyword - Registry:RegistryFilePath=/data/registry.json - Registry:RootPersistentFolder=/data/unity_packages - Registry:UpdateInterval=00:01:00 - Registry:AllowServingWithMissingDependencies=false - Logging:LogLevel:Default=Information - Signing:UpmServiceAccountKeyId= - Signing:UpmServiceAccountKeySecret= - Signing:UnityOrganizationId= - Signing:PackageIdRegexPattern= ``` -------------------------------- ### Enumerate curated packages from Registry Source: https://github.com/bdovaz/unitynuget Resolves the Registry from DI after the host has started, then enumerates curated packages. Uses Count, foreach over KeyValuePair, and TryGetValue to check for a specific package like 'serilog'. Demonstrates accessing Listed and Version properties. ```csharp using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using UnityNuGet; // Resolve from DI once the host has started: Registry registry = host.Services.GetRequiredService(); Console.WriteLine($"Curated packages: {registry.Count}"); foreach (KeyValuePair pair in registry) { Console.WriteLine($"{pair.Key}: listed={pair.Value.Listed}, minVersion={pair.Value.Version}"); } if (registry.TryGetValue("serilog", out RegistryEntry? serilogEntry)) { Console.WriteLine($"Serilog minimum version: {serilogEntry.Version}"); } else { Console.WriteLine("Serilog is not curated in this registry file."); } ``` -------------------------------- ### GET / redirect to /-/all Source: https://github.com/bdovaz/unitynuget Maps the root path to a 302 redirect to the npm all-packages listing. The response has an empty body and a Location header of /-/all. ```csharp builder.MapGet("/", () => Results.Redirect("/-/all")); ``` -------------------------------- ### GET /{id} Source: https://github.com/bdovaz/unitynuget Returns a single package document for the specified package ID. The response contains metadata about the package. ```APIDOC ## GET /{id} ### Description Returns a single package document for the specified package ID. The response contains metadata about the package. ### Method GET ### Endpoint /{id} ### Parameters #### Path Parameters - **id** (string) - Required - The package ID. ### Response #### Success Response (200 OK) - **Body** (JSON) - The package document. ### Request Example ``` GET /some-package HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 200 OK Content-Type: application/json { "name": "some-package", "versions": {} } ``` ``` -------------------------------- ### Map GET /status endpoint Source: https://github.com/bdovaz/unitynuget Registers the GET /status route that renders an HTML page from a Scriban template. No request parameters; sets templateContext.LoopLimit = 0 to disable render loop limits. Returns 200 with text/html; charset=utf-8 via WriteAsync. ```csharp builder.MapGet("/status", async context => { ... }); ``` -------------------------------- ### Environment variables for package signing Source: https://github.com/bdovaz/unitynuget/blob/master/readme.md Set these environment variables to enable automatic package signing with the upm pack command. They are defined in the Prerequisites section of the Unity documentation. ```text Signing:UpmServiceAccountKeyId Signing:UpmServiceAccountKeySecret Signing:UnityOrganizationId ``` -------------------------------- ### RegistryCacheReport class definition Source: https://github.com/bdovaz/unitynuget Collects and exposes status messages and progress for the registry cache. Running is true between Start() and Complete(). Progress is index * 100 / total (0 when total is 0). TimeRemainingForNextUpdate is TimeSpan.Zero when errors exist and null before first completion. The /status endpoint renders these collections; TryGetInstance uses ErrorMessages.Any() to decide between build-failure and still-initializing responses. ```csharp public class RegistryCacheReport(RegistryCacheSingleton registryCacheSingleton, IOptions registryOptionsAccessor) { public IEnumerable InformationMeessages => _informationMessages; public IEnumerable WarningMessages => _warningMessages; public IEnumerable ErrorMessages => _errorMessages; public bool Running { get; private set; } public double Progress { get; } public TimeSpan? TimeRemainingForNextUpdate { get; } public void AddInformation(string message) => _informationMessages.Add(message); public void AddWarning(string message) => _warningMessages.Add(message); public void AddError(string message) => _errorMessages.Add(message); public void Start(); public void Complete(); } ``` -------------------------------- ### Example JSON shape for NpmPackageListAllResponse Source: https://github.com/bdovaz/unitynuget Shows the flat JSON object produced by the NpmPackageListAllResponseConverter: property names are package IDs and values are NpmPackageInfo objects, as in the npm /-/all endpoint. ```json { "org.nuget.serilog": { "name": "org.nuget.serilog", "description": "...", "versions": { "2.10.0": "latest" } } } ``` -------------------------------- ### GET /-/all endpoint handler Source: https://github.com/bdovaz/unitynuget Maps the npm-compatible `/-/all` route. Returns a 200 with an `NpmPackageListAllResponse` serialized by `UnityNuGetJsonSerializerContext`; on failure returns a 200 with an `NpmError` body. No query string handling. ```csharp builder.MapGet("-/all", (RegistryCacheSingleton registryCacheSingleton, RegistryCacheReport registryCacheReport) => { if (!TryGetInstance(registryCacheSingleton, registryCacheReport, out RegistryCache? instance, out NpmError? error)) { return Results.Json(error, UnityNuGetJsonSerializerContext.Default); } NpmPackageListAllResponse? result = instance?.All(); return Results.Json(result, UnityNuGetJsonSerializerContext.Default); }); ``` -------------------------------- ### GET /{id} Source: https://github.com/bdovaz/unitynuget Returns the full npm package document for the given package id. The id is matched exactly against the registry's package dictionary. If the package is not found, an NpmError.NotFound body is returned. ```APIDOC ## GET /{id} ### Description Returns the full npm package document for the given package id. The id is matched exactly against the registry's package dictionary. If the package is not found, an NpmError.NotFound body is returned. ### Method GET ### Endpoint /{id} ### Parameters #### Path Parameters - **id** (string) - Required - npm package id as registered (e.g. `org.nuget.serilog`); matching is via the dictionary `Packages` (order-independent, exact string) #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **_id** (string) - Package id. - **_rev** (string) - Revision string. - **name** (string) - Package name. - **dist-tags** (object) - Distribution tags, e.g. `{ "latest": "2.10.0" }`. - **versions** (object) - Object keyed by version, each value is a version document. - **time** (object) - Object keyed by version, each value is a timestamp. - **users** (object) - Object of users. ### Request Example None ### Response Example ```json { "_id": "org.nuget.serilog", "_rev": "1-0", "name": "org.nuget.serilog", "dist-tags": { "latest": "2.10.0" }, "versions": { "2.10.0": { "name": "org.nuget.serilog", "version": "2.10.0", "dist": { "tarball": "https://.../org.nuget.serilog/-/org.nuget.serilog-2.10.0.tgz", "shasum": "..." }, "dependencies": {}, "_id": "org.nuget.serilog@2.10.0", "unity": "2019.1", "displayName": "Serilog (NuGet)" } }, "time": { "2.10.0": "2021-..." }, "users": {} } ``` ### Error Response - **200** with body `{"error":"not_found","reason":"document not found"}` (`NpmError.NotFound`) if package not found. - **200** with body with `error: "not_initialized"` if registry not initialized or failed. ``` -------------------------------- ### GET|HEAD /{id}/-/{file} Source: https://github.com/bdovaz/unitynuget Downloads a package tarball file for a given package id and version. Supports both GET and HEAD requests; HEAD returns only headers with content length. ```APIDOC ## [GET|HEAD] /{id}/-/{file} ### Description Downloads a package tarball file for a given package id and version. Supports both GET and HEAD requests; HEAD returns only headers with content length. ### Method GET, HEAD ### Endpoint /{id}/-/{file} ### Parameters #### Path Parameters - **id** (string) - Required - Package id - **file** (string) - Required - File name in format `{id}-{version}.tgz` ### Response #### Success Response (200) - For GET: file download with `Content-Type: application/octet-stream` and `Content-Disposition` filename = `file` - For HEAD: headers only with `Content-Type: application/octet-stream` and `Content-Length` from file size, empty body #### Not Found Response (200) - Body: `{"error":"not_found","reason":"document not found"}` #### Not Initialized / Failed Response (200) - Body with `error: "not_initialized"` ``` -------------------------------- ### GET /{id} endpoint handler Source: https://github.com/bdovaz/unitynuget Maps the `{id}` route. Returns a 200 with the full `NpmPackage` document if found; otherwise returns a 200 with `NpmError.NotFound` or an `NpmError` from `TryGetInstance` (e.g., `not_initialized`). ```csharp builder.MapGet("{id}", (string id, RegistryCacheSingleton registryCacheSingleton, RegistryCacheReport registryCacheReport) => { if (!TryGetInstance(registryCacheSingleton, registryCacheReport, out RegistryCache? instance, out NpmError? error)) { return Results.Json(error, UnityNuGetJsonSerializerContext.Default); } NpmPackage? package = instance?.GetPackage(id); if (package == null) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } return Results.Json(package, UnityNuGetJsonSerializerContext.Default); }); ``` -------------------------------- ### Wire events and build once (console usage equivalent to the Tool) Source: https://github.com/bdovaz/unitynuget Constructs a RegistryCache with required parameters and event handlers for progress, warnings, and errors. Build() never throws; errors surface via OnError. After building, GetPackage retrieves a package by ID. ```csharp using UnityNuGet; RegistryCache cache = new( registry, rootPersistentFolder: "/data/unity_packages", rootHttpUri: new Uri("https://unitynuget-registry.openupm.com/"), unityScope: "org.nuget", minimumUnityVersion: "2019.1", packageNameNuGetPostFix: " (NuGet)", packageKeywords: ["nuget"], targetFrameworks: registryOptions.TargetFrameworks, roslynAnalyzerVersions: registryOptions.RoslynAnalyzerVersions, logger: logger, unityPackageSigner: signer) { OnProgress = (_, e) => Console.WriteLine($"[{e.Current}/{e.Total}] packages"), OnWarning = (_, e) => Console.Error.WriteLine($"WARN: {e.Message}"), OnError = (_, e) => Console.Error.WriteLine($"ERROR: {e.Message}") }; await cache.Build(); // never throws; errors surface via OnError NpmPackage? serilog = cache.GetPackage("org.nuget.serilog"); Console.WriteLine(serilog?.Versions.Keys); ``` -------------------------------- ### GET /{id}/-/{file} Source: https://github.com/bdovaz/unitynuget Downloads the tarball for a specific package file. Supports both GET and HEAD requests; HEAD returns the file size without the body. ```APIDOC ## GET /{id}/-/{file} ### Description Downloads the tarball for a specific package file. Supports both GET and HEAD requests; HEAD returns the file size without the body. ### Method GET, HEAD ### Endpoint /{id}/-/{file} ### Parameters #### Path Parameters - **id** (string) - Required - The package ID. - **file** (string) - Required - The filename of the tarball. ### Response #### Success Response (200 OK) - **Body** (binary) - The tarball content (application/octet-stream). ### Request Example ``` GET /some-package/-/some-package-1.0.0.tgz HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 200 OK Content-Type: application/octet-stream ``` ``` -------------------------------- ### StartAsync Source: https://github.com/bdovaz/unitynuget Performs the load of the registry file. Resolves the file path, opens the file, deserializes the JSON, and copies the data into a dictionary with case-insensitive comparer. Logs an information message with the registry file path. ```APIDOC ## StartAsync ### Description Performs the load of the registry file. Resolves the file path, opens the file, deserializes the JSON, and copies the data into a dictionary with case-insensitive comparer. Logs an information message with the registry file path. ### Method `public async Task StartAsync(CancellationToken cancellationToken)` ### Parameters - **cancellationToken** (CancellationToken) - Required - Propagates notification that the operation should be canceled. ### Behavior 1. Resolves the registry file path: if `RegistryOptions.RegistryFilePath` is rooted (`Path.IsPathRooted`), it is used as-is; otherwise it is combined with `Directory.GetCurrentDirectory()`. 2. Opens the file with `File.OpenRead` — a missing file throws `FileNotFoundException`. 3. Deserializes the JSON into `IDictionary` using the source-generated `UnityNuGetJsonSerializerContext.Default.IDictionaryStringRegistryEntry` context. 4. Copies the data into `Dictionary` with `StringComparer.OrdinalIgnoreCase`. Logs an information message: `Using Unity registry file \`{UnityRegistryFile}\`. ``` -------------------------------- ### StartAsync method Source: https://github.com/bdovaz/unitynuget Loads the registry file asynchronously. Resolves the file path (rooted or combined with current directory), opens with File.OpenRead (throws FileNotFoundException if missing), deserializes JSON using the source-generated context, and copies into a case-insensitive dictionary. Logs 'Using Unity registry file `{UnityRegistryFile}`'. ```csharp public async Task StartAsync(CancellationToken cancellationToken) ``` -------------------------------- ### Serve package files (server usage) Source: https://github.com/bdovaz/unitynuget Endpoint handler equivalent: retrieves a package by ID and its file path, returning NotFound JSON if either is missing, otherwise returns the file as an octet stream. ```csharp // Endpoint handler equivalent: NpmPackage? package = cache.GetPackage(id); if (package == null) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } string? filePath = cache.GetPackageFilePath(file); if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { return Results.Json(NpmError.NotFound, UnityNuGetJsonSerializerContext.Default); } return Results.File(filePath, "application/octet-stream", file); ``` -------------------------------- ### Sign async method Source: https://github.com/bdovaz/unitynuget Spawns the upm executable with 'pack' arguments and sets UPM_SERVICE_ACCOUNT_KEY_ID and UPM_SERVICE_ACCOUNT_KEY_SECRET in the process environment. Stdout lines are logged at Information level, stderr at Error level. ```csharp public async Task Sign(string packageDirectoryPath, string destinationDirectoryPath, CancellationToken cancellationToken = default) { ProcessStartInfo processStartInfo = new() { FileName = _signingOptions.UpmExecutableFilePath, Arguments = string.Join(' ', new string[] { "pack", packageDirectoryPath, "--organization-id", _signingOptions.UnityOrganizationId!.Value.ToString(), "--destination", destinationDirectoryPath }), RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; processStartInfo.Environment.Add(UpmServiceAccountKeyIdEnvironmentVariableName, _signingOptions.UpmServiceAccountKeyId); processStartInfo.Environment.Add(UpmServiceAccountKeySecretEnvironmentVariableName, _signingOptions.UpmServiceAccountKeySecret); Process process = new() { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.OutputDataReceived += (sender, args) => { if (!string.IsNullOrEmpty(args.Data)) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("{Message}", args.Data); } } }; process.ErrorDataReceived += (sender, args) => { if (!string.IsNullOrEmpty(args.Data)) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError("{Message}", args.Data); } } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); await process.WaitForExitAsync(cancellationToken); } ``` -------------------------------- ### Run the server with docker-compose style YAML Source: https://github.com/bdovaz/unitynuget Configure and run the UnityNuGet server using a docker-compose style YAML service definition. Sets environment variables for registry options, signing executable path, and mounts volumes for registry.json and unity_packages. ```yaml services: unitynuget: build: ../.. environment: - Registry:RootHttpUrl=http://localhost:5000/ - Registry:UnityScope=org.nuget - Registry:UpdateInterval=00:01:00 - Registry:AllowServingWithMissingDependencies=false - Signing:UpmExecutableFilePath=/root/.upm/bin/upm ports: - 5000:8080 volumes: - ./registry.json:/data/registry.json - ./unity_packages:/data/unity_packages ``` -------------------------------- ### GET /status Source: https://github.com/bdovaz/unitynuget Returns an HTML build-status page. This endpoint provides a human-readable status page for the service. ```APIDOC ## GET /status ### Description Returns an HTML build-status page. This endpoint provides a human-readable status page for the service. ### Method GET ### Endpoint /status ### Response #### Success Response (200 OK) - **Body** (HTML) - The build-status page. ### Request Example ``` GET /status HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 200 OK Content-Type: text/html ... ``` ``` -------------------------------- ### Register Registry as hosted service in a host Source: https://github.com/bdovaz/unitynuget Registers the Registry as a singleton and hosted service using Microsoft.Extensions.DependencyInjection and Hosting. Configure RegistryOptions from the 'Registry' configuration section. StartAsync is invoked automatically at startup, loading the registry file before RegistryCacheUpdater builds the cache. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using UnityNuGet; HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); builder.Services.AddSingleton(); builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); builder.Services.Configure(builder.Configuration.GetSection("Registry")); IHost host = builder.Build(); await host.RunAsync(); ``` -------------------------------- ### RegistryCacheInitializer hosted service Source: https://github.com/bdovaz/unitynuget IHostedService that initializes the registry cache on startup. Resolves the server URI and Unity package folder based on environment and configuration, then populates the singleton. ```csharp public class RegistryCacheInitializer(IConfiguration configuration, IHostEnvironment hostEnvironment, ILoggerFactory loggerFactory, IOptions registryOptionsAccessor, RegistryCacheSingleton registryCacheSingleton) : IHostedService { public Task StartAsync(CancellationToken cancellationToken); public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } ``` -------------------------------- ### Registry Constructor Source: https://github.com/bdovaz/unitynuget Initializes a new instance of the Registry class. The constructor itself performs no I/O; all work happens in StartAsync. ```APIDOC ## Registry Constructor ### Description Initializes a new instance of the Registry class. The constructor itself performs no I/O; all work happens in StartAsync. ### Method Constructor ### Signature ```csharp public Registry( ILoggerFactory loggerFactory, IOptions registryOptionsAccessor) ``` ### Parameters - **loggerFactory** (ILoggerFactory) - Required - Logging factory; a logger named `"NuGet"` is created from it and logs the resolved registry file path - **registryOptionsAccessor** (IOptions) - Required - Options accessor; the `RegistryFilePath` option selects the registry file to load ``` -------------------------------- ### GetPackageFilePath(string packageFileName) Source: https://github.com/bdovaz/unitynuget Gets the absolute file path for a package file to download. Includes a path-traversal guard to prevent directory traversal attacks. ```APIDOC ## GetPackageFilePath(string packageFileName) ### Description Gets the path for the specified package file to download. ### Method GetPackageFilePath ### Endpoint GetPackageFilePath(string packageFileName) ### Parameters #### Path Parameters - **packageFileName** (string) - Required - File name as received in the download URL, e.g. `org.nuget.serilog-2.1.0.tgz` ### Response Returns the absolute path of the package file under `_rootPersistentFolder`. Throws `ArgumentNullException` if `packageFileName` is null. ``` -------------------------------- ### Full constructor for RegistryCache Source: https://github.com/bdovaz/unitynuget Initializes a RegistryCache with all configuration parameters. Side effects include creating the persistent folder, setting NUGET_PACKAGES in CI, loading NuGet settings, parsing target frameworks, and computing signing capability. ```csharp public RegistryCache( Registry registry, string rootPersistentFolder, Uri rootHttpUri, string unityScope, string minimumUnityVersion, string packageNameNuGetPostFix, string[] packageKeywords, RegistryTargetFramework[] targetFrameworks, RoslynAnalyzerVersion[] roslynAnalyzerVersions, ILogger logger, UnityPackageSigner unityPackageSigner) ``` -------------------------------- ### GET /health Source: https://github.com/bdovaz/unitynuget Liveness probe endpoint used by Docker HEALTHCHECK. Returns ASP.NET Core health check status (healthy or unhealthy). ```APIDOC ## GET /health ### Description Liveness probe endpoint used by Docker HEALTHCHECK. Returns ASP.NET Core health check status (healthy or unhealthy). ### Method GET ### Endpoint /health ### Response #### Success Response (200 OK) - **Status** (string) - "Healthy" when the service is healthy. #### Error Response (503 Service Unavailable) - **Status** (string) - "Unhealthy" when the service is unhealthy. ### Request Example ``` GET /health HTTP/1.1 Host: example.com ``` ### Response Example ``` HTTP/1.1 200 OK Content-Type: text/plain Healthy ``` ``` -------------------------------- ### Registry constructor Source: https://github.com/bdovaz/unitynuget Constructor signature for Registry. It performs no I/O; all loading happens in StartAsync. The loggerFactory creates a logger named "NuGet" and the registryOptionsAccessor provides the RegistryFilePath option. ```csharp public Registry( ILoggerFactory loggerFactory, IOptions registryOptionsAccessor) ``` -------------------------------- ### Add scoped registry via manifest.json Source: https://github.com/bdovaz/unitynuget/blob/master/readme.md Manually edit Packages/manifest.json to add the Unity NuGet scoped registry and a dependency. The scopes field must include 'org.nuget'. ```json { "scopedRegistries": [ // Other registries... { "name": "Unity NuGet", "url": "https://unitynuget-registry.openupm.com", "scopes": [ "org.nuget" ] } ], "dependencies": { // Other dependencies... "org.nuget.scriban": "2.1.0" } } ``` -------------------------------- ### RegistryCache Full Constructor Source: https://github.com/bdovaz/unitynuget Creates a new RegistryCache instance with explicit configuration for all settings. This constructor initializes the cache with the provided registry, storage paths, Unity scope, and other parameters. ```APIDOC ## RegistryCache Full Constructor ### Description Creates a new RegistryCache instance with explicit configuration for all settings. This constructor initializes the cache with the provided registry, storage paths, Unity scope, and other parameters. ### Method Constructor ### Signature ```csharp public RegistryCache( Registry registry, string rootPersistentFolder, Uri rootHttpUri, string unityScope, string minimumUnityVersion, string packageNameNuGetPostFix, string[] packageKeywords, RegistryTargetFramework[] targetFrameworks, RoslynAnalyzerVersion[] roslynAnalyzerVersions, ILogger logger, UnityPackageSigner unityPackageSigner) ``` ### Parameters - **registry** (Registry) - Required - The curated registry used for package listing and dependency resolution - **rootPersistentFolder** (string) - Required - Disk folder where `.tgz`, `.sha1`, `.json` cache files and `version.txt` are stored; created if missing; `ArgumentNullException` if null - **rootHttpUri** (Uri) - Required - Base HTTP URL used to build absolute `tarball` URLs (`new Uri(_rootHttpUri, $"{npmPackage.Id}/-/{fileName}")`); `ArgumentNullException` if null - **unityScope** (string) - Required - UPM scope prefix, e.g. `org.nuget`; npm package IDs become `{unityScope}.{nugetIdLowercased}` - **minimumUnityVersion** (string) - Required - Unity version written into the `unity` field of the UPM `package.json`, e.g. `2019.1` - **packageNameNuGetPostFix** (string) - Required - Suffix appended to the `displayName`, e.g. ` (NuGet)` - **packageKeywords** (string[]) - Required - Keywords added to every package - **targetFrameworks** (RegistryTargetFramework[]) - Required - Target frameworks (e.g. `netstandard2.0` / `netstandard2.1`) with their Unity define constraints - **roslynAnalyzerVersions** (RoslynAnalyzerVersion[]) - Required - Supported Roslyn analyzer versions and their define constraints - **logger** (ILogger) - Required - Logger prefixing `NuGet`-based operations - **unityPackageSigner** (UnityPackageSigner) - Required - Signs generated packages when signing is enabled ### Side Effects - `Directory.CreateDirectory(_rootPersistentFolder)` when missing. - When `IsRunningAsContinuousIntegration`, sets environment variable `NUGET_PACKAGES` to `/.nuget`. - Loads NuGet settings via `Settings.LoadDefaultSettings(root: Directory.GetCurrentDirectory())`, builds a `SourceRepositoryProvider` with `Repository.Provider.GetCoreV3()` and stores `_sourceRepositories`. This honors a custom `NuGet.Config` beside the working directory (e.g. to reach private Azure DevOps feeds). - Parses each `RegistryTargetFramework.Name` into `registryTargetFramework.Framework = NuGetFramework.Parse(...)`. - Creates the internal `NpmPackageRegistry` and a `SourceCacheContext`. - Sets `GlobalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(_settings)`. - Computes `_canSignPackages = _unityPackageSigner.CanSign()`. ``` -------------------------------- ### RegistryCacheInitializer class declaration Source: https://github.com/bdovaz/unitynuget Primary constructor for the hosted service that resolves registry options and initializes the cache. Uses IHostEnvironment to select folder base and always sets uri to _registryOptions.RootHttpUrl!. ```csharp public class RegistryCacheInitializer(IHostEnvironment hostEnvironment, ILoggerFactory loggerFactory, IOptions registryOptionsAccessor, RegistryCacheSingleton registryCacheSingleton) : IHostedService { public Task StartAsync(CancellationToken cancellationToken); public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } ``` -------------------------------- ### Platform tree built by CreateAllPlatforms Source: https://github.com/bdovaz/unitynuget Text representation of the platform hierarchy generated by CreateAllPlatforms. Shows the root AnyOs.AnyCpu with editor flag and its descendants, including Windows, Linux, Android, WebGL, iOS, and OSX configurations. ```text AnyOs.AnyCpu (editor) ├── Windows.AnyCpu (editor) │ ├── Windows.X64 (editor) │ └── Windows.X86 ├── Linux.X64 (editor) ├── Android.AnyCpu │ ├── Android.ARMv7 │ ├── Android.ARM64 │ ├── Android.X86 │ └── Android.X64 ├── WebGL.AnyCpu ├── iOS.AnyCpu └── OSX.AnyCpu (editor) ├── OSX.X64 (editor) └── OSX.ARM64 (editor) ``` -------------------------------- ### Programmatic host in custom code (C#) Source: https://github.com/bdovaz/unitynuget Set up the UnityNuGet server programmatically in custom C# code using the WebApplication builder. Registers required services, configures options from configuration sections, and maps health checks and UnityNuGet endpoints. ```csharp using Microsoft.AspNetCore.Builder; using UnityNuGet; using UnityNuGet.Server; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection("Registry")); builder.Services.AddSingleton, ValidateRegistryOptions>(); builder.Services.AddOptionsWithValidateOnStart(); builder.Services.Configure(builder.Configuration.GetSection("Signing")); builder.Services.AddSingleton(); WebApplication app = builder.Build(); app.MapHealthChecks("/health"); app.MapUnityNuGetEndpoints(); app.Run(); ``` -------------------------------- ### Consume a package document with NpmPackage Source: https://github.com/bdovaz/unitynuget Shows how to fetch a package document from the UnityNuGet registry using HttpClient and deserialize it with the provided JSON context. Prints the latest version, tarball, shasum, and dependencies. Requires the UnityNuGet.Npm namespace and System.Net.Http.Json. ```csharp using System.Net.Http.Json; using UnityNuGet.Npm; using HttpClient http = new(); NpmPackage package = await http.GetFromJsonAsync( "https://unitynuget-registry.openupm.com/org.nuget.serilog", UnityNuGetJsonSerializerContext.Default.NpmPackage) ?? throw new InvalidOperationException(); string latest = package.DistTags["latest"]; NpmPackageVersion version = package.Versions[latest]; Console.WriteLine($"Latest {version.Name} is {version.Version} (Unity {version.Unity})"); Console.WriteLine($"Tarball: {version.Distribution.Tarball}"); Console.WriteLine($"Shasum: {version.Distribution.Shasum}"); foreach ((string dep, string range) in version.Dependencies) { Console.WriteLine($" depends on {dep}@{range}"); } ``` -------------------------------- ### Bind options in a host Source: https://github.com/bdovaz/unitynuget Configures RegistryOptions and SigningOptions from the 'Registry' and 'Signing' configuration sections, and registers validation for RegistryOptions with AddOptionsWithValidateOnStart. ```csharp using Microsoft.Extensions.DependencyInjection; using UnityNuGet; builder.Services.Configure(builder.Configuration.GetSection("Registry")); builder.Services.Configure(builder.Configuration.GetSection("Signing")); builder.Services.AddSingleton, ValidateRegistryOptions>(); builder.Services.AddOptionsWithValidateOnStart(); ``` -------------------------------- ### Add scoped registry via Package Manager UI Source: https://github.com/bdovaz/unitynuget/blob/master/readme.md Values to enter in Unity's Package Manager UI to add the scoped registry. Use the exact Name, Url, and Scope(s) shown. ```yaml Name: Unity NuGet Url: https://unitynuget-registry.openupm.com Scope(s): org.nuget ```