forked from microsoft/aspire
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNodeExtensions.cs
More file actions
221 lines (191 loc) · 10.5 KB
/
NodeExtensions.cs
File metadata and controls
221 lines (191 loc) · 10.5 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable ASPIREDOCKERFILEBUILDER001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.NodeJs;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.Hosting;
namespace Aspire.Hosting;
/// <summary>
/// Provides extension methods for adding Node applications to an <see cref="IDistributedApplicationBuilder"/>.
/// </summary>
public static class NodeAppHostingExtension
{
/// <summary>
/// Adds a node application to the application model. Node should available on the PATH.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param>
/// <param name="name">The name of the resource.</param>
/// <param name="scriptPath">The path to the script that Node will execute.</param>
/// <param name="workingDirectory">The working directory to use for the command. If null, the working directory of the current process is used.</param>
/// <param name="args">The arguments to pass to the command.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<NodeAppResource> AddNodeApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string scriptPath, string? workingDirectory = null, string[]? args = null)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(scriptPath);
args ??= [];
string[] effectiveArgs = [scriptPath, .. args];
workingDirectory ??= Path.GetDirectoryName(scriptPath)!;
workingDirectory = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, workingDirectory));
var resource = new NodeAppResource(name, "node", workingDirectory);
return builder.AddResource(resource)
.WithNodeDefaults()
.WithArgs(effectiveArgs)
.WithIconName("CodeJsRectangle");
}
/// <summary>
/// Adds a node application to the application model. Executes the npm command with the specified script name.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param>
/// <param name="name">The name of the resource.</param>
/// <param name="workingDirectory">The working directory to use for the command. If null, the working directory of the current process is used.</param>
/// <param name="scriptName">The npm script to execute. Defaults to "start".</param>
/// <param name="args">The arguments to pass to the command.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<NodeAppResource> AddNpmApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string workingDirectory, string scriptName = "start", string[]? args = null)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(workingDirectory);
ArgumentException.ThrowIfNullOrEmpty(scriptName);
string[] allArgs = args is { Length: > 0 }
? ["run", scriptName, "--", .. args]
: ["run", scriptName];
workingDirectory = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, workingDirectory));
var resource = new NodeAppResource(name, "npm", workingDirectory);
return builder.AddResource(resource)
.WithNodeDefaults()
.WithArgs(allArgs)
.WithIconName("CodeJsRectangle");
}
private static IResourceBuilder<TResource> WithNodeDefaults<TResource>(this IResourceBuilder<TResource> builder) where TResource : NodeAppResource =>
builder.WithOtlpExporter()
.WithEnvironment("NODE_ENV", builder.ApplicationBuilder.Environment.IsDevelopment() ? "development" : "production")
.WithExecutableCertificateTrustCallback((ctx) =>
{
if (ctx.Scope == CertificateTrustScope.Append)
{
ctx.CertificateBundleEnvironment.Add("NODE_EXTRA_CA_CERTS");
}
else
{
ctx.CertificateTrustArguments.Add("--use-openssl-ca");
ctx.CertificateBundleEnvironment.Add("SSL_CERT_FILE");
}
return Task.CompletedTask;
});
/// <summary>
/// Adds a Vite app to the distributed application builder.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/> to add the resource to.</param>
/// <param name="name">The name of the Vite app.</param>
/// <param name="workingDirectory">The working directory of the Vite app.</param>
/// <param name="useHttps">When true use HTTPS for the endpoints, otherwise use HTTP.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <example>
/// The following example creates a Vite app using npm as the package manager.
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddViteApp("frontend", "./frontend")
/// .WithNpmPackageManager();
///
/// builder.Build().Run();
/// </code>
/// </example>
/// </remarks>
public static IResourceBuilder<ViteAppResource> AddViteApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string workingDirectory, bool useHttps = false)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(workingDirectory);
workingDirectory = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, workingDirectory));
var resource = new ViteAppResource(name, "node", workingDirectory);
var resourceBuilder = builder.AddResource(resource)
.WithNodeDefaults()
.WithIconName("CodeJsRectangle")
.WithArgs(c =>
{
if (resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManagerAnnotation))
{
foreach (var arg in packageManagerAnnotation.RunCommandLineArgs)
{
c.Args.Add(arg);
}
}
c.Args.Add("dev");
if (packageManagerAnnotation?.CommandSeparator is string separator)
{
c.Args.Add(separator);
}
var targetEndpoint = resource.GetEndpoint("https");
if (!targetEndpoint.Exists)
{
targetEndpoint = resource.GetEndpoint("http");
}
c.Args.Add("--port");
c.Args.Add(targetEndpoint.Property(EndpointProperty.TargetPort));
});
_ = useHttps
? resourceBuilder.WithHttpsEndpoint(env: "PORT")
: resourceBuilder.WithHttpEndpoint(env: "PORT");
return resourceBuilder
.PublishAsDockerFile(c =>
{
c.WithDockerfileBuilder(workingDirectory, dockerfileContext =>
{
if (c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManagerAnnotation)
&& packageManagerAnnotation.BuildCommandLineArgs is { Length: > 0 })
{
var dockerBuilder = dockerfileContext.Builder
.From("node:22-slim")
.WorkDir("/app")
.Copy(".", ".");
if (packageManagerAnnotation.InstallCommandLineArgs is { Length: > 0 })
{
dockerBuilder
.Run($"{resourceBuilder.Resource.Command} {string.Join(' ', packageManagerAnnotation.InstallCommandLineArgs)}");
}
dockerBuilder
.Run($"{resourceBuilder.Resource.Command} {string.Join(' ', packageManagerAnnotation.BuildCommandLineArgs)}");
}
});
});
}
/// <summary>
/// Ensures the Node.js packages are installed before the application starts using npm as the package manager.
/// </summary>
/// <param name="resource">The NodeAppResource.</param>
/// <param name="useCI">When true, use <code>npm ci</code>, otherwise use <code>npm install</code> when installing packages.</param>
/// <param name="configureInstaller">Configure the npm installer resource.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<TResource> WithNpmPackageManager<TResource>(this IResourceBuilder<TResource> resource, bool useCI = false, Action<IResourceBuilder<NodeInstallerResource>>? configureInstaller = null) where TResource : NodeAppResource
{
resource.WithCommand("npm");
resource.WithAnnotation(new JavaScriptPackageManagerAnnotation("npm")
{
InstallCommandLineArgs = [useCI ? "ci" : "install"],
RunCommandLineArgs = ["run"],
BuildCommandLineArgs = ["run", "build"]
});
// Only install packages during development, not in publish mode
if (!resource.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
var installerName = $"{resource.Resource.Name}-npm-install";
var installer = new NodeInstallerResource(installerName, resource.Resource.WorkingDirectory);
var installerBuilder = resource.ApplicationBuilder.AddResource(installer)
.WithCommand("npm")
.WithArgs([useCI ? "ci" : "install"])
.WithParentRelationship(resource.Resource)
.ExcludeFromManifest();
// Make the parent resource wait for the installer to complete
resource.WaitForCompletion(installerBuilder);
configureInstaller?.Invoke(installerBuilder);
resource.WithAnnotation(new JavaScriptPackageInstallerAnnotation(installer));
}
return resource;
}
}