10 Commits

Author SHA1 Message Date
swcs 2b16e2067c 1.3.0 2026-05-11 15:08:40 +02:00
swcs 4ece202cbb remove unnecessary dep 2026-04-30 14:55:29 +02:00
swcs 6bcabcdea8 make config path customizable 2026-03-25 15:42:31 +01:00
swcs 214938b966 do not run proxy service when not in dev env 2026-03-25 12:58:20 +01:00
swcs ae1efdc527 correct prop naming 2026-03-25 12:54:53 +01:00
swcs 7c581583d2 Update ViteProxy.csproj 2024-08-20 14:29:11 +02:00
swcs a8f07fc203 1.2 release 2024-08-20 14:20:27 +02:00
swcs 0f1df639f8 dbg type = embedded 2024-08-18 23:50:09 +02:00
swcs 2ce477f9b8 remove default useStaticFiles call 2024-05-24 13:23:21 +02:00
swcs fcfec6b2f9 new working directory allows absolute paths; allow multiple proxies with named configs 2024-02-29 13:09:47 +01:00
7 changed files with 150 additions and 107 deletions
+48 -48
View File
@@ -8,27 +8,27 @@ namespace ViteProxy;
public class ProcessProxy public class ProcessProxy
{ {
string workingDirectory; readonly string _workingDirectory;
string script; readonly string _script;
Action<ProcessStartInfo> onProcessConfigure = null; Action<ProcessStartInfo> _onProcessConfigure = null;
Action<string, bool> captureLog = null; Action<string, bool> _captureLog = null;
bool isWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
Dictionary<string, string> envVars = new(); readonly Dictionary<string, string> _envVars = new();
HashSet<string> arguments = new(); readonly HashSet<string> _arguments = new();
bool forwardLog = false; readonly bool _forwardLog = false;
Process process = null; Process _process = null;
EventedStreamReader stdOut; EventedStreamReader _stdOut;
EventedStreamReader stdErr; EventedStreamReader _stdErr;
public ProcessProxy(string workingDirectory, string script, bool forwardLog = false) public ProcessProxy(string workingDirectory, string script, bool forwardLog = false)
{ {
this.workingDirectory = workingDirectory; this._workingDirectory = workingDirectory;
this.script = script; this._script = script;
this.forwardLog = forwardLog; this._forwardLog = forwardLog;
} }
@@ -37,7 +37,7 @@ public class ProcessProxy
/// </summary> /// </summary>
public ProcessProxy EnvVar(string key, string value) public ProcessProxy EnvVar(string key, string value)
{ {
envVars.Add(key, value); _envVars.Add(key, value);
return this; return this;
} }
@@ -47,7 +47,7 @@ public class ProcessProxy
/// </summary> /// </summary>
public ProcessProxy Argument(string argument) public ProcessProxy Argument(string argument)
{ {
arguments.Add(argument); _arguments.Add(argument);
return this; return this;
} }
@@ -57,7 +57,7 @@ public class ProcessProxy
/// </summary> /// </summary>
public ProcessProxy Configure(Action<ProcessStartInfo> onProcessConfigure) public ProcessProxy Configure(Action<ProcessStartInfo> onProcessConfigure)
{ {
this.onProcessConfigure = onProcessConfigure; this._onProcessConfigure = onProcessConfigure;
return this; return this;
} }
@@ -67,7 +67,7 @@ public class ProcessProxy
/// </summary> /// </summary>
public ProcessProxy Capture(Action<string, bool> action) public ProcessProxy Capture(Action<string, bool> action)
{ {
this.captureLog = action; this._captureLog = action;
return this; return this;
} }
@@ -80,16 +80,16 @@ public class ProcessProxy
{ {
StartProcess(); StartProcess();
using var stdErrReader = new EventedStreamStringReader(stdErr); using var stdErrReader = new EventedStreamStringReader(_stdErr);
try try
{ {
// TODO implement timeout // TODO implement timeout
// https://stackoverflow.com/questions/18760252/timeout-an-async-method-implemented-with-taskcompletionsource // https://stackoverflow.com/questions/18760252/timeout-an-async-method-implemented-with-taskcompletionsource
await stdOut.WaitForFinish(); await _stdOut.WaitForFinish();
} }
catch (EndOfStreamException ex) catch (EndOfStreamException ex)
{ {
throw new InvalidOperationException($"The script '{script}' exited without indicating that the server was listening for requests.\nThe error output was: " + $"{stdErrReader.ReadAsString()}", ex); throw new InvalidOperationException($"The script '{_script}' exited without indicating that the server was listening for requests.\nThe error output was: " + $"{stdErrReader.ReadAsString()}", ex);
} }
} }
@@ -102,22 +102,22 @@ public class ProcessProxy
{ {
StartProcess(); StartProcess();
using var stdErrReader = new EventedStreamStringReader(stdErr); using var stdErrReader = new EventedStreamStringReader(_stdErr);
try try
{ {
await stdOut.WaitForMatch(new Regex(startupCondition, RegexOptions.IgnoreCase, startupTimeout == default ? TimeSpan.FromMinutes(5) : startupTimeout)); await _stdOut.WaitForMatch(new Regex(startupCondition, RegexOptions.IgnoreCase, startupTimeout == default ? TimeSpan.FromMinutes(5) : startupTimeout));
} }
catch (EndOfStreamException ex) catch (EndOfStreamException ex)
{ {
throw new InvalidOperationException($"The script '{script}' exited without indicating that the server was listening for requests.\nThe error output was: " + $"{stdErrReader.ReadAsString()}", ex); throw new InvalidOperationException($"The script '{_script}' exited without indicating that the server was listening for requests.\nThe error output was: " + $"{stdErrReader.ReadAsString()}", ex);
} }
} }
public void Exit() public void Exit()
{ {
try { process?.Kill(); } catch { } try { _process?.Kill(); } catch { }
try { process?.WaitForExit(); } catch { } try { _process?.WaitForExit(); } catch { }
AppDomain.CurrentDomain.DomainUnload -= UnloadHandler; AppDomain.CurrentDomain.DomainUnload -= UnloadHandler;
AppDomain.CurrentDomain.ProcessExit -= UnloadHandler; AppDomain.CurrentDomain.ProcessExit -= UnloadHandler;
@@ -130,18 +130,18 @@ public class ProcessProxy
/// </summary> /// </summary>
Process StartProcess() Process StartProcess()
{ {
string executable = script; string executable = _script;
StringBuilder command = new(); StringBuilder command = new();
command.Append(script); command.Append(_script);
command.Append(' '); command.Append(' ');
foreach (string arg in arguments) foreach (string arg in _arguments)
{ {
command.Append(arg); command.Append(arg);
} }
string argumentList = command.ToString(); string argumentList = command.ToString();
if (isWindows) if (IsWindows)
{ {
argumentList = $"/c {argumentList}"; argumentList = $"/c {argumentList}";
executable = "cmd"; executable = "cmd";
@@ -154,20 +154,20 @@ public class ProcessProxy
RedirectStandardInput = true, RedirectStandardInput = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardError = true,
WorkingDirectory = workingDirectory WorkingDirectory = _workingDirectory
}; };
foreach (var envVar in envVars) foreach (var envVar in _envVars)
{ {
startInfo.Environment[envVar.Key] = envVar.Value; startInfo.Environment[envVar.Key] = envVar.Value;
} }
onProcessConfigure?.Invoke(startInfo); _onProcessConfigure?.Invoke(startInfo);
try try
{ {
process = Process.Start(startInfo); _process = Process.Start(startInfo);
process.EnableRaisingEvents = true; _process.EnableRaisingEvents = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -185,7 +185,7 @@ public class ProcessProxy
AppDomain.CurrentDomain.ProcessExit += UnloadHandler; AppDomain.CurrentDomain.ProcessExit += UnloadHandler;
AppDomain.CurrentDomain.UnhandledException += UnloadHandler; AppDomain.CurrentDomain.UnhandledException += UnloadHandler;
return process; return _process;
} }
@@ -197,13 +197,13 @@ public class ProcessProxy
void AttachLogger(bool isStream = false) void AttachLogger(bool isStream = false)
{ {
stdOut = new EventedStreamReader(process.StandardOutput); _stdOut = new EventedStreamReader(_process.StandardOutput);
stdErr = new EventedStreamReader(process.StandardError); _stdErr = new EventedStreamReader(_process.StandardError);
stdOut.OnReceivedLine += line => WriteToLog(line); _stdOut.OnReceivedLine += line => WriteToLog(line);
stdOut.OnReceivedChunk += chunk => WriteToLog(chunk); _stdOut.OnReceivedChunk += chunk => WriteToLog(chunk);
stdErr.OnReceivedLine += line => WriteToLog(line, true); _stdErr.OnReceivedLine += line => WriteToLog(line, true);
stdErr.OnReceivedChunk += chunk => WriteToLog(chunk, true); _stdErr.OnReceivedChunk += chunk => WriteToLog(chunk, true);
} }
@@ -216,11 +216,11 @@ public class ProcessProxy
line = line.StartsWith("<s>") ? line.Substring(3) : line; line = line.StartsWith("<s>") ? line.Substring(3) : line;
if (captureLog != null) if (_captureLog != null)
{ {
captureLog(line, isError); _captureLog(line, isError);
} }
if (forwardLog) if (_forwardLog)
{ {
(isError ? Console.Error : Console.Out).WriteLine(line); (isError ? Console.Error : Console.Out).WriteLine(line);
} }
@@ -236,11 +236,11 @@ public class ProcessProxy
return; return;
} }
if (captureLog != null) if (_captureLog != null)
{ {
captureLog(new String(chunk.Array, chunk.Offset, chunk.Count), isError); _captureLog(new String(chunk.Array, chunk.Offset, chunk.Count), isError);
} }
if (forwardLog) if (_forwardLog)
{ {
(isError ? Console.Error : Console.Out).Write(chunk.Array, chunk.Offset, chunk.Count); (isError ? Console.Error : Console.Out).Write(chunk.Array, chunk.Offset, chunk.Count);
} }
+10 -8
View File
@@ -1,17 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFrameworks>net6.0;net7.0;net8.0;net9.0;net10.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ViteProxy</RootNamespace> <RootNamespace>ViteProxy</RootNamespace>
<AssemblyName>ViteProxy</AssemblyName> <AssemblyName>ViteProxy</AssemblyName>
<Version>0.0.0</Version> <Version>1.3.0</Version>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Include="../viteproxy-logo.png" Pack="true" PackagePath="\" />
<None Include="../README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup> <PropertyGroup>
<Product>ViteProxy</Product> <Product>ViteProxy</Product>
<Title>ViteProxy</Title> <Title>ViteProxy</Title>
<Copyright>Copyright © Tobias Klika 2022</Copyright> <Copyright>Copyright © Tobias Klika 2026</Copyright>
<Tags>Vite, npm, middleware, server, development</Tags> <Tags>Vite, npm, middleware, server, development</Tags>
<Authors>Tobias Klika</Authors> <Authors>Tobias Klika</Authors>
<Description>ViteProxy is a proxy for vite projects within ASP.NET Core.</Description> <Description>ViteProxy is a proxy for vite projects within ASP.NET Core.</Description>
@@ -20,7 +25,8 @@
<PublishRepositoryUrl>true</PublishRepositoryUrl> <PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageId>ViteProxy</PackageId> <PackageId>ViteProxy</PackageId>
<PackageProjectUrl>https://github.com/ceee/ViteProxy</PackageProjectUrl> <PackageProjectUrl>https://github.com/ceee/ViteProxy</PackageProjectUrl>
<PackageIconUrl>https://raw.githubusercontent.com/ceee/ViteProxy/main/viteproxy-logo.png</PackageIconUrl> <PackageIcon>viteproxy-logo.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<EmbedUntrackedSources>true</EmbedUntrackedSources> <EmbedUntrackedSources>true</EmbedUntrackedSources>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild> <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
@@ -31,9 +37,5 @@
<ItemGroup> <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All"/>
</ItemGroup>
</Project> </Project>
+26 -17
View File
@@ -2,46 +2,55 @@
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace ViteProxy; namespace ViteProxy;
public static class ViteProxyApplicationBuilderExtensions public static class ViteProxyApplicationBuilderExtensions
{ {
public static IApplicationBuilder UseViteStaticFiles(this IApplicationBuilder app) /// <summary>
/// Provides static files from the vite working directory or a custom directory or from the named vite settings
/// </summary>
/// <param name="app">The app builder</param>
/// <param name="path">Provide a file path for static file delivery</param>
/// <param name="configName">When vite proxy is added via named options these can be used here for correct retrieval of the vite working directory</param>
/// <returns>The app builde</returns>
public static IApplicationBuilder UseViteStaticFiles(this IApplicationBuilder app, string path = null, string configName = null)
{ {
IWebHostEnvironment env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>(); IWebHostEnvironment env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
IOptions<ViteProxyOptions> options = app.ApplicationServices.GetRequiredService<IOptions<ViteProxyOptions>>();
string workingDirectory = (options.Value.WorkingDirectory ?? String.Empty).Trim('/');
if (workingDirectory == null) // do not provide static files when not in development
if (!env.IsDevelopment())
{ {
return app; return app;
} }
app.UseStaticFiles(); if (path == null && configName == null)
app.UseStaticFiles(new StaticFileOptions
{ {
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, workingDirectory)) IOptions<ViteProxyOptions> options = app.ApplicationServices.GetRequiredService<IOptions<ViteProxyOptions>>();
}); path = options.Value.WorkingDirectory;
}
return app; if (configName != null)
} {
using IServiceScope scope = app.ApplicationServices.CreateScope();
IOptionsSnapshot<ViteProxyOptions> optionsSnapschat = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<ViteProxyOptions>>();
public static IApplicationBuilder UseViteStaticFiles(this IApplicationBuilder app, string path) ViteProxyOptions options = optionsSnapschat.Get(configName);
{ path = options.WorkingDirectory;
IWebHostEnvironment env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>(); }
if (path == null) if (path == null)
{ {
return app; return app;
} }
app.UseStaticFiles(); // TODO build full path
ViteWorkingDirectory workingDirectory = new(env, path);
app.UseStaticFiles(new StaticFileOptions app.UseStaticFiles(new StaticFileOptions
{ {
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, path)) FileProvider = new PhysicalFileProvider(workingDirectory.Path)
}); });
return app; return app;
+1 -1
View File
@@ -15,7 +15,7 @@ public class ViteProxyOptions
/// <summary> /// <summary>
/// Directory where the frontend files are located /// Directory where the frontend files are located
/// </summary> /// </summary>
public string WorkingDirectory { get; set; } public string WorkingDirectory { get; set; } = "App";
/// <summary> /// <summary>
/// Whether to enable the proxy or not /// Whether to enable the proxy or not
+25 -25
View File
@@ -7,39 +7,38 @@ namespace ViteProxy;
public class ViteProxyService : IHostedService public class ViteProxyService : IHostedService
{ {
ViteProxyOptions options; readonly ViteProxyOptions _options;
ILogger<ViteProxyService> logger; readonly ViteWorkingDirectory _workingDirectory;
string workingDirectory; readonly ILogger<ViteProxyService> _logger;
bool isRunning = false; readonly IWebHostEnvironment _env;
bool _isRunning = false;
public ViteProxyService(IWebHostEnvironment env, ILogger<ViteProxyService> logger, IOptions<ViteProxyOptions> options) public ViteProxyService(IWebHostEnvironment env, ILogger<ViteProxyService> logger, IOptions<ViteProxyOptions> options) : this(env, logger, options.Value ?? new()) { }
public ViteProxyService(IWebHostEnvironment env, ILogger<ViteProxyService> logger, ViteProxyOptions options)
{ {
this.options = options.Value ?? new(); _options = options ?? new();
this.workingDirectory = Path.Combine(env.ContentRootPath, (this.options.WorkingDirectory ?? String.Empty).Trim('/')); _workingDirectory = new ViteWorkingDirectory(env, _options.WorkingDirectory);
this.logger = logger; _env = env;
_logger = logger;
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
if (!this.options.Enabled) if (!_options.Enabled || !_env.IsDevelopment())
{ {
return; return;
} }
// locate npm version and throw if it is not installed // locate npm version and throw if it is not installed
Version npmVersion = await FindNpmVersion(); Version npmVersion = await FindNpmVersion() ?? throw new Exception("Please install node+npm to use the vite dev service (https://www.npmjs.com/)");
if (npmVersion == null)
{
throw new Exception("Please install node+npm to use the vite dev service (https://www.npmjs.com/)");
}
// start vite server // start vite server
ProcessProxy viteProcess = await StartDevServer(options.Port); ProcessProxy viteProcess = await StartDevServer(_options.Port);
logger.LogInformation("vite listening on: http://localhost:{port}", options.Port); _logger.LogInformation("vite listening on: http://localhost:{port} (path: {workingDirectory})", _options.Port, _workingDirectory.Path);
} }
public Task StopAsync(CancellationToken cancellationToken) public Task StopAsync(CancellationToken cancellationToken)
@@ -55,7 +54,7 @@ public class ViteProxyService : IHostedService
{ {
Version version = null; Version version = null;
ProcessProxy process = new ProcessProxy(workingDirectory, "npm").Argument("-v").Capture((value, err) => ProcessProxy process = new ProcessProxy(_workingDirectory.Path, "npm").Argument("-v").Capture((value, err) =>
{ {
if (version == null && !value.Contains("not recognized") && Version.TryParse(value, out Version _version)) if (version == null && !value.Contains("not recognized") && Version.TryParse(value, out Version _version))
{ {
@@ -79,14 +78,15 @@ public class ViteProxyService : IHostedService
PidUtils.KillPort((ushort)port, true); PidUtils.KillPort((ushort)port, true);
// create and run the vite script // create and run the vite script
ProcessProxy process = new ProcessProxy(workingDirectory, "npm", options.ForwardLog) ProcessProxy process = new ProcessProxy(_workingDirectory.Path, "npm", _options.ForwardLog)
.Argument("run " + options.ScriptName) .Argument("run " + _options.ScriptName)
.EnvVar("PORT", port.ToString()) .EnvVar("PORT", port.ToString())
//.EnvVar("URL_PREFIX", "/@viteproxy/")
.Capture(CaptureLog); .Capture(CaptureLog);
await process.RunAsync(options.StartupCondition, TimeSpan.FromSeconds(options.TimeoutInSeconds)); await process.RunAsync(_options.StartupCondition, TimeSpan.FromSeconds(_options.TimeoutInSeconds));
isRunning = true; _isRunning = true;
return process; return process;
} }
@@ -94,18 +94,18 @@ public class ViteProxyService : IHostedService
void CaptureLog(string line, bool isError) void CaptureLog(string line, bool isError)
{ {
if (!isRunning) if (!_isRunning)
{ {
return; return;
} }
if (isError) if (isError)
{ {
logger.LogWarning(line); _logger.LogWarning(line);
} }
else else
{ {
logger.LogInformation(line); _logger.LogInformation(line);
} }
} }
} }
+15 -8
View File
@@ -1,39 +1,46 @@
using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ViteProxy; namespace ViteProxy;
public static class ViteProxyServiceCollectionExtensions public static class ViteProxyServiceCollectionExtensions
{ {
public static IServiceCollection AddViteProxy(this IServiceCollection services) public static IServiceCollection AddViteProxy(this IServiceCollection services, string configSectionPath = "Vite")
{ {
services.AddLogging(); services.AddLogging();
services.AddOptions(); services.AddOptions();
services.AddHostedService<ViteProxyService>(); services.AddHostedService<ViteProxyService>();
services.AddOptions<ViteProxyOptions>().BindConfiguration("Vite"); services.AddOptions<ViteProxyOptions>().BindConfiguration(configSectionPath);
return services; return services;
} }
public static IServiceCollection AddViteProxy(this IServiceCollection services, Action<ViteProxyOptions> configure) public static IServiceCollection AddViteProxy(this IServiceCollection services, Action<ViteProxyOptions> configure, string configSectionPath = "Vite")
{ {
services.AddLogging(); services.AddLogging();
services.AddOptions(); services.AddOptions();
services.AddHostedService<ViteProxyService>(); services.AddHostedService<ViteProxyService>();
services.AddOptions<ViteProxyOptions>().BindConfiguration("Vite"); services.AddOptions<ViteProxyOptions>().BindConfiguration(configSectionPath);
services.PostConfigure(configure); services.PostConfigure(configure);
return services; return services;
} }
public static IServiceCollection AddViteProxy(this IServiceCollection services, IConfiguration namedConfigurationSection) public static IServiceCollection AddViteProxy(this IServiceCollection services, string configName, IConfiguration namedConfigurationSection)
{ {
services.AddLogging(); services.AddLogging();
services.AddOptions(); services.AddOptions();
services.AddHostedService<ViteProxyService>(); services.AddHostedService((svc) => new ViteProxyService(
services.AddOptions<ViteProxyOptions>().Bind(namedConfigurationSection); env: svc.GetService<IWebHostEnvironment>(),
logger: svc.GetService<ILogger<ViteProxyService>>(),
options: svc.GetService<IOptionsSnapshot<ViteProxyOptions>>().Get(configName)
));
services.AddOptions<ViteProxyOptions>(configName).Bind(namedConfigurationSection);
return services; return services;
} }
+25
View File
@@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Hosting;
namespace ViteProxy;
internal class ViteWorkingDirectory
{
public string Path { get; protected set; }
public string InputPath { get; protected set; }
public ViteWorkingDirectory(IWebHostEnvironment env, string inputPath)
{
InputPath = inputPath;
string path = inputPath.Replace('\\', '/').Trim().TrimEnd('/');
if (System.IO.Path.IsPathFullyQualified(path))
{
Path = path;
}
else
{
Path = System.IO.Path.Combine(env.ContentRootPath, path);
}
}
}