-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViteHelper.cs
292 lines (244 loc) · 11.4 KB
/
ViteHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using Microsoft.AspNetCore.SpaServices;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;
namespace Net6_Controller_And_VIte
{
public static class ViteHelper
{
private static bool PlatformIsWindows => OperatingSystem.IsWindows();
private static ILogger ViteLogger;
/// <summary>
/// Adds Connection to Vite Hosted VueApplication
/// configured per <seealso cref="SpaOptions"/> on the <paramref name="spa"/>.
/// NOTE: (this will create devcert.pfx and vite.config.js in your Vue Application on first run)
/// </summary>
/// <param name="port">Vite hosting port</param>
/// <param name="sourcePath">Vite app source path</param>
public static void UseViteDevelopmentServer(this ISpaBuilder spa, int? port = null, string sourcePath = null)
{
// throw error if node.js not installed.
EnsureNodeJSAlreadyInstalled();
// Default HostingPort
if (!port.HasValue)
port = 3000;
spa.Options.DevServerPort = port.Value;
if (!string.IsNullOrWhiteSpace(sourcePath))
spa.Options.SourcePath = sourcePath;
else if (string.IsNullOrWhiteSpace(spa.Options.SourcePath))
throw new ArgumentNullException("ISpaBuilder.Options.SourcePath", "Must specific Spa Client App path");
var devServerEndpoint = new Uri($"https://localhost:{spa.Options.DevServerPort}");
var webHostEnvironment = spa.ApplicationBuilder.ApplicationServices.GetService<IWebHostEnvironment>();
ViteLogger = spa.ApplicationBuilder.ApplicationServices.GetService<ILoggerFactory>()?.CreateLogger("Vite");
// If port not in used , launch vite dev server
if (!CheckPortInUsed(spa.Options.DevServerPort))
{
// export dev cert
var spaFolder = Path.Combine(webHostEnvironment.ContentRootPath, spa.Options.SourcePath);
if (!Directory.Exists(spaFolder))
throw new DirectoryNotFoundException(spaFolder);
var viteConfigPath = GetViteConfigFile(spaFolder);
var devCert = Path.Combine(spaFolder, "devcert.pfx");
var serverOptionFile = Path.Combine(spaFolder, $"serverOption{new FileInfo(viteConfigPath).Extension}");
// Check dev pfx exist
if (!File.Exists(serverOptionFile) || !File.Exists(devCert))
{
var pwd = CreateCertPfxKey(devCert);
// Create serverOption file
File.WriteAllText(serverOptionFile, BuildServerOption(devCert, pwd));
ViteLogger?.LogInformation($"Creating Vite config: {serverOptionFile}");
InjectionViteConfig(viteConfigPath, serverOptionFile);
}
EnsureNodeModuleAlreadyInstalled(spa.Options.SourcePath);
// launch Vite development server
RunDevServer(spa.Options.SourcePath, spa.Options.DevServerPort, spa.Options.StartupTimeout);
}
spa.UseProxyToSpaDevelopmentServer(devServerEndpoint);
}
/// <summary>
/// Injection vite.config file to use serverOption file
/// </summary>
private static void InjectionViteConfig(string viteConfigPath, string serverOptionFile)
{
var optionFile = new FileInfo(serverOptionFile);
var serverOption = optionFile.Name[..^optionFile.Extension.Length];
var data = File.ReadAllLines(viteConfigPath).ToList();
// Already injection
if (data.Any(x => x.Contains($"./{serverOption}")))
return;
data.Insert(0, $"import serverOption from './{serverOption}'");
var exportDefaultLine = data.FindIndex(x => x.Contains("export default"));
if (exportDefaultLine == -1)
return;
data.Insert(exportDefaultLine + 1, " server : serverOption,");
File.WriteAllLines(viteConfigPath, data);
}
/// <summary>
/// Get vite.config file Path (support .ts and .js)
/// </summary>
private static string GetViteConfigFile(string rootPath)
{
var configFile = Directory.GetFiles(rootPath)
.Where(x =>
{
var file = new FileInfo(x);
var fileName = file.Name[..^file.Extension.Length];
return fileName.Equals("vite.config",
StringComparison.OrdinalIgnoreCase);
})
.Single();
return configFile;
}
/// <summary>
/// Build Vite https server option
/// </summary>
private static string BuildServerOption(string certfile, string pass)
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("export default {");
sb.AppendLine($"https: {{ pfx: '{Path.GetFileName(certfile)}', passphrase: '{pass}' }}");
sb.AppendLine("}");
sb.AppendLine();
return sb.ToString();
}
private static bool CheckPortInUsed(int port)
=> IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpListeners()
.Select(x => x.Port)
.Contains(port);
/// <summary>
/// if 'node_module' not exist than run 'npm install'
/// </summary>
private static void EnsureNodeModuleAlreadyInstalled(string sourcePath)
{
// Check Node_Module exists
if (!Directory.Exists(Path.Combine(sourcePath, "node_modules")))
{
ViteLogger?.LogWarning($"node_modules not found , run npm install...");
// Install node modules
var ps = Process.Start(new ProcessStartInfo()
{
FileName = PlatformIsWindows ? "cmd" : "npm",
Arguments = $"{(PlatformIsWindows ? "/c npm " : "")}install",
WorkingDirectory = sourcePath,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
});
ps.WaitForExit();
ViteLogger?.LogWarning($"npm install done.");
}
}
/// <summary>
/// Throw exception if 'node --version' catch error
/// </summary>
/// <exception cref="Exception"></exception>
private static void EnsureNodeJSAlreadyInstalled()
{
var ps = Process.Start(new ProcessStartInfo()
{
FileName = PlatformIsWindows ? "cmd" : "node",
Arguments = $"{(PlatformIsWindows ? "/c node " : "")}--version",
//WorkingDirectory = /*SourcePath*/,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
});
ps.WaitForExit();
if (ps.ExitCode == 0)
return;
throw new Exception("Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE.");
}
/// <summary>
/// Create pfx key and return password
/// </summary>
private static string CreateCertPfxKey(string fileName)
{
var pfxPassword = Guid.NewGuid().ToString("N");
ViteLogger?.LogInformation($"Exporting dotnet dev cert to {fileName} for Vite");
ViteLogger?.LogDebug($"Export password: {pfxPassword}");
var certExport = new ProcessStartInfo
{
FileName = PlatformIsWindows ? "cmd" : "dotnet",
Arguments = $"{(PlatformIsWindows ? "/c dotnet " : "")}dev-certs https -v -ep {fileName} -p {pfxPassword}",
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
};
var exportProcess = Process.Start(certExport);
exportProcess.WaitForExit();
if (exportProcess.ExitCode == 0)
ViteLogger?.LogInformation(exportProcess.StandardOutput.ReadToEnd());
else
ViteLogger?.LogError(exportProcess.StandardError.ReadToEnd());
return pfxPassword;
}
private static void RunDevServer(string sourcePath, int port, TimeSpan timeout)
{
var runningPort = $" -- --port {port}";
var processInfo = new ProcessStartInfo
{
FileName = PlatformIsWindows ? "cmd" : "npm",
Arguments = $"{(PlatformIsWindows ? "/c npm " : "")}run dev{runningPort}",
WorkingDirectory = sourcePath,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
};
var process = Process.Start(processInfo);
var tcs = new TaskCompletionSource<int>();
_ = Task.Run(() =>
{
try
{
string? line;
while ((line = process?.StandardOutput.ReadLine()?.Trim()) != null)
{
// Wait for done message
if (!string.IsNullOrEmpty(line))
{
ViteLogger?.LogInformation(line);
if (!tcs.Task.IsCompleted && line.Contains("VITE", StringComparison.OrdinalIgnoreCase))
if (line.Contains("ready in", StringComparison.OrdinalIgnoreCase) || // for VITE v3
line.Contains("Dev server running at:", StringComparison.OrdinalIgnoreCase)) // for VITE v2
{
tcs.SetResult(1);
}
}
}
}
catch (EndOfStreamException ex)
{
ViteLogger?.LogError(ex.ToString());
tcs.SetException(new InvalidOperationException("'npm run dev' failed.", ex));
}
});
_ = Task.Run(() =>
{
try
{
string? line;
while ((line = process?.StandardError.ReadLine()?.Trim()) != null)
{
ViteLogger?.LogError(line);
}
}
catch (EndOfStreamException ex)
{
ViteLogger?.LogError(ex.ToString());
tcs.SetException(new InvalidOperationException("'npm run dev' failed.", ex));
}
});
if (!tcs.Task.Wait(timeout))
{
throw new TimeoutException();
}
}
}
}