-
Notifications
You must be signed in to change notification settings - Fork 861
Expand file tree
/
Copy pathJavaScriptHostingExtensions.cs
More file actions
1949 lines (1724 loc) · 93.6 KB
/
JavaScriptHostingExtensions.cs
File metadata and controls
1949 lines (1724 loc) · 93.6 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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
#pragma warning disable ASPIREPIPELINES001
#pragma warning disable ASPIRECERTIFICATES001
#pragma warning disable ASPIREEXTENSION001
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.ApplicationModel.Docker;
using Aspire.Hosting.JavaScript;
using Aspire.Hosting.Pipelines;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Aspire.Hosting;
/// <summary>
/// Provides extension methods for adding JavaScript applications to an <see cref="IDistributedApplicationBuilder"/>.
/// </summary>
public static class JavaScriptHostingExtensions
{
private const string BrowserCapability = "browser";
private const string DefaultNodeVersion = "22";
private const string DefaultYarpImage = Yarp.YarpContainerImageTags.Registry + "/" + Yarp.YarpContainerImageTags.Image + ":" + Yarp.YarpContainerImageTags.Tag;
// This is the order of config files that Vite will look for by default
// See https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts#L97
private static readonly string[] s_defaultConfigFiles = ["vite.config.js", "vite.config.mjs", "vite.config.ts", "vite.config.cjs", "vite.config.mts", "vite.config.cts"];
// The token to replace with the relative path to the user's Vite config file
private const string AspireViteRelativeConfigToken = "%%ASPIRE_VITE_RELATIVE_CONFIG_PATH%%";
// The token to replace with the absolute path to the original Vite config file
private const string AspireViteAbsoluteConfigToken = "%%ASPIRE_VITE_ABSOLUTE_CONFIG_PATH%%";
// A template Vite config that loads an existing config provides a default https configuration if one isn't present
// Uses environment variables to configure a TLS certificate in PFX format and its password if specified
// The value of %%ASPIRE_VITE_RELATIVE_CONFIG_PATH%% is replaced with the path to the user's actual Vite config file at runtime
// Vite only supports module style config files, so we don't have to handle commonjs style imports or exports here
private const string AspireViteConfig = """
import { defineConfig } from 'vite'
import config from '%%ASPIRE_VITE_RELATIVE_CONFIG_PATH%%'
console.log('Applying Aspire specific Vite configuration for HTTPS support.')
console.log('Found original Vite configuration at "%%ASPIRE_VITE_ABSOLUTE_CONFIG_PATH%%"')
const aspireHttpsConfig = process.env['TLS_CONFIG_PFX'] ? {
pfx: process.env['TLS_CONFIG_PFX'],
passphrase: process.env['TLS_CONFIG_PASSWORD'],
} : undefined
const wrapConfig = (innerConfig) => ({
...innerConfig,
server: {
...innerConfig.server,
https: innerConfig.server?.https ?? aspireHttpsConfig,
}
})
let finalConfig = config
try {
if (typeof config === 'function') {
finalConfig = defineConfig((cfg) => {
let innerConfig = config(cfg)
return wrapConfig(innerConfig)
});
} else if (typeof config === 'object' && config !== null) {
let innerConfig = config
finalConfig = defineConfig(wrapConfig(innerConfig))
} else {
console.warn('Unexpected Vite config format. Falling back to original configuration without Aspire HTTPS modifications.')
finalConfig = config
}
} catch {
console.warn('Error applying Aspire Vite configuration. Falling back to original configuration without Aspire HTTPS modifications.')
finalConfig = config
}
export default finalConfig
""";
/// <summary>
/// Adds a node application to the application model. Node should be 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="appDirectory">The path to the directory containing the node application.</param>
/// <param name="scriptPath">The path to the script relative to the app directory to run.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// This method executes a Node script directly using <c>node script.js</c>. If you want to use a package manager
/// you can add one and configure the install and run scripts using the provided extension methods.
///
/// If the application directory contains a <c>package.json</c> file, npm will be added as the default package manager.
/// </remarks>
/// <example>
/// Add a Node app to the application model using yarn and 'yarn run dev' for running during development:
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddNodeApp("frontend", "../frontend", "app.js")
/// .WithYarn()
/// .WithRunScript("dev");
///
/// builder.Build().Run();
/// </code>
/// </example>
[AspireExport(Description = "Adds a Node.js application resource")]
public static IResourceBuilder<NodeAppResource> AddNodeApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string scriptPath)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(scriptPath);
appDirectory = Path.GetFullPath(appDirectory, builder.AppHostDirectory);
var resource = new NodeAppResource(name, "node", appDirectory);
var resourceBuilder = builder.AddResource(resource)
.WithNodeDefaults()
.WithArgs(c =>
{
// If the JavaScriptRunScriptAnnotation is present, use that to run the app
if (c.Resource.TryGetLastAnnotation<JavaScriptRunScriptAnnotation>(out var runCommand) &&
c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
if (!string.IsNullOrEmpty(packageManager.ScriptCommand))
{
c.Args.Add(packageManager.ScriptCommand);
}
c.Args.Add(runCommand.ScriptName);
foreach (var arg in runCommand.Args)
{
c.Args.Add(arg);
}
}
else
{
c.Args.Add(scriptPath);
}
})
.WithIconName("CodeJsRectangle")
.PublishAsDockerFile(c =>
{
// Only generate a Dockerfile if one doesn't already exist in the app directory
if (File.Exists(Path.Combine(resource.WorkingDirectory, "Dockerfile")))
{
return;
}
c.WithDockerfileBuilder(resource.WorkingDirectory, dockerfileContext =>
{
var defaultBaseImage = new Lazy<string>(() => GetDefaultBaseImage(appDirectory, "alpine", dockerfileContext.Services));
// Get custom base image from annotation, if present
dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation);
var baseBuildImage = baseImageAnnotation?.BuildImage ?? defaultBaseImage.Value;
var builderStage = dockerfileContext.Builder
.From(baseBuildImage, "build")
.EmptyLine()
.WorkDir("/app");
if (resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
// Initialize the Docker build stage with package manager-specific setup commands.
// This allows package managers to add prerequisite commands (e.g., enabling pnpm via corepack)
// before package installation and build steps.
packageManager.InitializeDockerBuildStage?.Invoke(builderStage);
var copiedAllSource = false;
if (resource.TryGetLastAnnotation<JavaScriptInstallCommandAnnotation>(out var installCommand))
{
// Copy package files first for better layer caching
if (packageManager.PackageFilesPatterns.Count > 0)
{
foreach (var packageFilePattern in packageManager.PackageFilesPatterns)
{
builderStage.Copy(packageFilePattern.Source, packageFilePattern.Destination);
}
}
else
{
builderStage.Copy(".", ".");
copiedAllSource = true;
}
builderStage.AddInstallCommand(packageManager, installCommand);
}
if (!copiedAllSource)
{
// Copy application source code after dependencies are installed
builderStage.Copy(".", ".");
}
if (resource.TryGetLastAnnotation<JavaScriptBuildScriptAnnotation>(out var buildCommand))
{
var commandArgs = new List<string>() { packageManager.ExecutableName };
if (!string.IsNullOrEmpty(packageManager.ScriptCommand))
{
commandArgs.Add(packageManager.ScriptCommand);
}
commandArgs.Add(buildCommand.ScriptName);
commandArgs.AddRange(buildCommand.Args);
builderStage.EmptyLine()
.Run(string.Join(' ', commandArgs));
}
}
else
{
// No package manager, just copy everything
builderStage.Copy(".", ".");
}
var logger = dockerfileContext.Services.GetService<ILogger<JavaScriptAppResource>>();
dockerfileContext.Builder.AddContainerFilesStages(dockerfileContext.Resource, logger);
var baseRuntimeImage = baseImageAnnotation?.RuntimeImage ?? defaultBaseImage.Value;
var runtimeBuilder = dockerfileContext.Builder
.From(baseRuntimeImage, "runtime")
.EmptyLine()
.WorkDir("/app")
.CopyFrom("build", "/app", "/app")
.AddContainerFiles(dockerfileContext.Resource, "/app", logger)
.EmptyLine()
.Env("NODE_ENV", "production")
.EmptyLine()
.User("node")
.EmptyLine()
.Entrypoint([resource.Command, scriptPath]);
});
});
// Configure pipeline to ensure container file sources are built first
resourceBuilder.WithPipelineConfiguration(context =>
{
if (resourceBuilder.Resource.TryGetAnnotationsOfType<ContainerFilesDestinationAnnotation>(out var containerFilesAnnotations))
{
var buildSteps = context.GetSteps(resourceBuilder.Resource, WellKnownPipelineTags.BuildCompute);
foreach (var containerFile in containerFilesAnnotations)
{
buildSteps.DependsOn(context.GetSteps(containerFile.Source, WellKnownPipelineTags.BuildCompute));
}
}
});
if (File.Exists(Path.Combine(appDirectory, "package.json")))
{
// Automatically add npm as the package manager if a package.json file exists
resourceBuilder.WithNpm();
}
resourceBuilder.WithVSCodeDebugging(scriptPath);
if (builder.ExecutionContext.IsRunMode)
{
builder.OnBeforeStart((_, _) =>
{
// set the command to the package manager executable if the JavaScriptRunScriptAnnotation is present
if (resourceBuilder.Resource.TryGetLastAnnotation<JavaScriptRunScriptAnnotation>(out _) &&
resourceBuilder.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
resourceBuilder.WithCommand(packageManager.ExecutableName);
}
return Task.CompletedTask;
});
}
return resourceBuilder;
}
private static IResourceBuilder<TResource> WithNodeDefaults<TResource>(this IResourceBuilder<TResource> builder) where TResource : JavaScriptAppResource =>
builder.WithOtlpExporter()
.WithRequiredCommand("node", "https://nodejs.org/en/download/")
.WithEnvironment("NODE_ENV", builder.ApplicationBuilder.Environment.IsDevelopment() ? "development" : "production")
.WithCertificateTrustConfiguration((ctx) =>
{
if (ctx.Scope == CertificateTrustScope.Append)
{
ctx.EnvironmentVariables["NODE_EXTRA_CA_CERTS"] = ctx.CertificateBundlePath;
}
else
{
if (ctx.EnvironmentVariables.TryGetValue("NODE_OPTIONS", out var existingOptionsObj))
{
ctx.EnvironmentVariables["NODE_OPTIONS"] = existingOptionsObj switch
{
// Attempt to append to existing NODE_OPTIONS if possible, otherwise overwrite
string s when !string.IsNullOrEmpty(s) => $"{s} --use-openssl-ca",
ReferenceExpression re => ReferenceExpression.Create($"{re} --use-openssl-ca"),
_ => "--use-openssl-ca",
};
}
else
{
ctx.EnvironmentVariables["NODE_OPTIONS"] = "--use-openssl-ca";
}
}
return Task.CompletedTask;
});
/// <summary>
/// Adds a JavaScript application resource to the distributed application using the specified app directory and
/// run script.
/// </summary>
/// <param name="builder">The distributed application builder to which the JavaScript application resource will be added.</param>
/// <param name="name">The unique name of the JavaScript application resource. Cannot be null or empty.</param>
/// <param name="appDirectory">The path to the directory containing the JavaScript application.</param>
/// <param name="runScriptName">The name of the npm script to run when starting the application. Defaults to "dev". Cannot be null or empty.</param>
/// <returns>A resource builder for the newly added JavaScript application resource.</returns>
/// <remarks>
/// If a Dockerfile does not exist in the application's directory, one will be generated
/// automatically when publishing. The method configures the resource with Node.js defaults and sets up npm
/// integration.
/// </remarks>
[AspireExport(Description = "Adds a JavaScript application resource")]
public static IResourceBuilder<JavaScriptAppResource> AddJavaScriptApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string runScriptName = "dev")
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(appDirectory);
ArgumentException.ThrowIfNullOrEmpty(runScriptName);
appDirectory = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, appDirectory));
var resource = new JavaScriptAppResource(name, "npm", appDirectory);
return builder.CreateDefaultJavaScriptAppBuilder(resource, appDirectory, runScriptName);
}
/// <summary>
/// Configures the JavaScript application to publish as a standalone static website served by YARP.
/// </summary>
/// <typeparam name="TResource">The JavaScript resource type.</typeparam>
/// <param name="builder">The JavaScript resource builder.</param>
/// <param name="configure">Optional callback to configure <see cref="PublishAsStaticWebsiteOptions"/>.</param>
/// <returns>The updated resource builder.</returns>
/// <remarks>
/// <para>
/// The published container uses a YARP reverse proxy image for static file serving.
/// To add an API reverse-proxy, use the overload that accepts an <c>apiPath</c> and <c>apiTarget</c>.
/// </para>
/// </remarks>
[Experimental("ASPIREEXTENSION001", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
[AspireExportIgnore(Reason = "Use the polyglot-compatible overload instead.")]
public static IResourceBuilder<TResource> PublishAsStaticWebsite<TResource>(
this IResourceBuilder<TResource> builder,
Action<PublishAsStaticWebsiteOptions>? configure = null)
where TResource : JavaScriptAppResource
{
var options = new PublishAsStaticWebsiteOptions();
configure?.Invoke(options);
return PublishAsStaticWebsiteCore(builder, null, null, options);
}
/// <summary>
/// Configures the JavaScript application to publish as a standalone static website served by YARP,
/// with an API reverse-proxy to the specified resource.
/// </summary>
/// <typeparam name="TResource">The JavaScript resource type.</typeparam>
/// <param name="builder">The JavaScript resource builder.</param>
/// <param name="apiPath">
/// A path prefix to reverse-proxy to a backend API. For example, <c>/api</c> proxies all requests
/// matching <c>/api/{"{**catch-all}"}</c> to the backend resource.
/// </param>
/// <param name="apiTarget">
/// The backend resource to proxy API requests to. YARP uses service discovery to resolve the
/// appropriate endpoint, preferring HTTPS when available.
/// </param>
/// <param name="configure">Optional callback to configure <see cref="PublishAsStaticWebsiteOptions"/>.</param>
/// <returns>The updated resource builder.</returns>
/// <remarks>
/// <para>
/// The published container uses a YARP reverse proxy image for static file serving and API
/// reverse-proxy. YARP natively supports HTTPS backends and service discovery, so API proxy requests
/// work correctly across all deployment targets (Docker Compose, Azure App Service, etc.).
/// </para>
/// </remarks>
[Experimental("ASPIREEXTENSION001", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
[AspireExportIgnore(Reason = "Use the polyglot-compatible overload instead.")]
public static IResourceBuilder<TResource> PublishAsStaticWebsite<TResource>(
this IResourceBuilder<TResource> builder,
string apiPath,
IResourceBuilder<IResourceWithServiceDiscovery> apiTarget,
Action<PublishAsStaticWebsiteOptions>? configure = null)
where TResource : JavaScriptAppResource
{
ArgumentNullException.ThrowIfNull(apiTarget);
var options = new PublishAsStaticWebsiteOptions();
configure?.Invoke(options);
return PublishAsStaticWebsiteCore(builder, apiPath, apiTarget, options);
}
/// <summary>
/// Polyglot-compatible overload. All parameters are optional so the TS codegen wraps them
/// in a single options object rather than positional args.
/// </summary>
#pragma warning disable ASPIREEXPORT009 // Polyglot entry point — collision is intentional
[AspireExport("publishAsStaticWebsite", Description = "Publishes the JavaScript application as a standalone static website using YARP.")]
internal static IResourceBuilder<TResource> PublishAsStaticWebsitePolyglot<TResource>(
#pragma warning restore ASPIREEXPORT009
this IResourceBuilder<TResource> builder,
string? apiPath = null,
IResourceBuilder<IResourceWithServiceDiscovery>? apiTarget = null,
string outputPath = "dist",
bool stripPrefix = false,
string? targetEndpointName = null)
where TResource : JavaScriptAppResource
{
var options = new PublishAsStaticWebsiteOptions
{
OutputPath = outputPath,
StripPrefix = stripPrefix,
TargetEndpointName = targetEndpointName
};
return PublishAsStaticWebsiteCore(builder, apiPath, apiTarget, options);
}
private static IResourceBuilder<TResource> PublishAsStaticWebsiteCore<TResource>(
IResourceBuilder<TResource> builder,
string? apiPath,
IResourceBuilder<IResourceWithServiceDiscovery>? apiTarget,
PublishAsStaticWebsiteOptions options)
where TResource : JavaScriptAppResource
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(options.OutputPath);
if (apiPath is not null && apiTarget is null)
{
throw new ArgumentException("apiTarget is required when apiPath is specified.", nameof(apiTarget));
}
if (apiTarget is not null && apiPath is null)
{
throw new ArgumentException("apiPath is required when apiTarget is specified.", nameof(apiPath));
}
if (apiPath is not null && apiTarget is not null)
{
if (!apiPath.StartsWith('/'))
{
throw new ArgumentException("The apiPath must start with '/'.", nameof(apiPath));
}
apiPath = apiPath.TrimEnd('/');
if (apiPath.Length == 0)
{
throw new ArgumentException("The apiPath must not be '/' — it would match all requests and make the static site unreachable.", nameof(apiPath));
}
ValidateApiPath(apiPath);
builder.WithReference(apiTarget);
}
if (!builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return builder;
}
// YARP listens on port 5000 by default in the base image, so configure an endpoint for that port
// and set ASPNETCORE_URLS to ensure Kestrel listens on the correct port as well for static file serving and API reverse-proxy to work correctly.
builder.WithEndpoint("http", e => e.TargetPort = 5000, createIfNotExists: true);
var annotation = new JavaScriptPublishModeAnnotation(JavaScriptPublishMode.StaticWebsite)
{
OutputPath = options.OutputPath,
};
builder.WithEnvironment(ctx =>
{
ctx.EnvironmentVariables["YARP_ENABLE_STATIC_FILES"] = "true";
if (apiPath is not null && apiTarget is not null)
{
// Resolve the destination address — use a specific endpoint if configured, otherwise service discovery
var destinationAddress = options.TargetEndpointName is not null
? apiTarget.Resource.GetEndpoint(options.TargetEndpointName)
: (object)BuildServiceDiscoveryUrl(apiTarget.Resource);
ctx.EnvironmentVariables["REVERSEPROXY__ROUTES__api__CLUSTERID"] = "api";
ctx.EnvironmentVariables["REVERSEPROXY__ROUTES__api__MATCH__PATH"] = $"{apiPath}/{{**catch-all}}";
ctx.EnvironmentVariables["REVERSEPROXY__CLUSTERS__api__DESTINATIONS__destination1__ADDRESS"] = destinationAddress;
if (options.StripPrefix)
{
ctx.EnvironmentVariables["REVERSEPROXY__ROUTES__api__TRANSFORMS__0__PATHREMOVEPREFIX"] = apiPath;
}
}
});
builder.WithAnnotation(annotation)
.ClearContainerFilesSources()
.WithContainerFilesSource(GetContainerFilesSourcePath(options.OutputPath))
.WithOtlpExporter();
if (builder.Resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerfileBuildAnnotation))
{
dockerfileBuildAnnotation.HasEntrypoint = true;
}
return builder;
}
/// <summary>
/// Configures the JavaScript application to publish as a standalone Node.js server that runs a built artifact directly.
/// </summary>
/// <typeparam name="TResource">The JavaScript resource type.</typeparam>
/// <param name="builder">The JavaScript resource builder.</param>
/// <param name="entryPoint">
/// The relative path to the Node.js entry point to execute in the published container after the build completes,
/// such as <c>.output/server/index.mjs</c> or <c>build/index.js</c>.
/// </param>
/// <param name="outputPath">
/// The relative path containing the built runtime files to copy into the published container. Defaults to the application root.
/// </param>
/// <returns>The updated resource builder.</returns>
/// <remarks>
/// <para>
/// Use this method for frameworks that produce a Node.js server artifact during the build and recommend
/// running that artifact directly in production rather than invoking a package manager script at runtime.
/// The application source is still built using the configured package manager and build script; this method
/// only changes the publish-time runtime container shape.
/// </para>
/// <para>
/// The container files source path is automatically set to <paramref name="outputPath"/> so that only
/// the built output directory is copied into the runtime container, not the full application source.
/// </para>
/// </remarks>
[AspireExport(Description = "Publishes the JavaScript application as a standalone Node.js server that runs a built artifact directly.")]
public static IResourceBuilder<TResource> PublishAsNodeServer<TResource>(this IResourceBuilder<TResource> builder, string entryPoint, string outputPath = ".")
where TResource : JavaScriptAppResource
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(entryPoint);
ArgumentException.ThrowIfNullOrEmpty(outputPath);
if (!builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return builder;
}
var annotation = new JavaScriptPublishModeAnnotation(JavaScriptPublishMode.NodeServer)
{
EntryPoint = entryPoint,
OutputPath = outputPath
};
builder.WithAnnotation(annotation)
.ClearContainerFilesSources()
.WithContainerFilesSource(GetContainerFilesSourcePath(outputPath))
.WithOtlpExporter()
.WithEnvironment("HOST", "0.0.0.0")
.WithEnvironment("HOSTNAME", "0.0.0.0");
if (builder.Resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerfileBuildAnnotation))
{
dockerfileBuildAnnotation.HasEntrypoint = true;
}
return builder;
}
/// <summary>
/// Configures the JavaScript application to publish as a Node.js server that uses a package manager script at runtime.
/// </summary>
/// <typeparam name="TResource">The JavaScript resource type.</typeparam>
/// <param name="builder">The JavaScript resource builder.</param>
/// <param name="startScriptName">
/// The name of the package manager script to run in the published container.
/// For example, <c>start</c> runs <c>npm run start</c>.
/// </param>
/// <param name="runScriptArguments">
/// Optional arguments appended after the script name at runtime,
/// such as <c>-- --port "$PORT"</c>.
/// </param>
/// <returns>The updated resource builder.</returns>
/// <remarks>
/// <para>
/// Use this method for frameworks where the production server depends on packages in <c>node_modules</c> at runtime.
/// The resulting container includes the full application with production dependencies installed.
/// </para>
/// <para>
/// This method is appropriate for frameworks like Nuxt (where <c>useAsyncData</c>/<c>useFetch</c> requires the
/// full Nitro environment), Remix (where <c>react-router-serve</c> is an npm dependency), and Astro SSR
/// (where the built entry point imports unbundled <c>@astrojs/*</c> packages).
/// </para>
/// <para>
/// For frameworks that produce a self-contained server artifact that does not require <c>node_modules</c>,
/// use <see cref="PublishAsNodeServer{TResource}"/> instead for a smaller runtime image.
/// </para>
/// </remarks>
[AspireExport(Description = "Publishes the JavaScript application as a Node.js server that uses a package manager script at runtime.")]
public static IResourceBuilder<TResource> PublishAsNpmScript<TResource>(this IResourceBuilder<TResource> builder, string startScriptName = "start", string? runScriptArguments = null)
where TResource : JavaScriptAppResource
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(startScriptName);
if (!builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return builder;
}
var annotation = new JavaScriptPublishModeAnnotation(JavaScriptPublishMode.NpmScript)
{
StartScriptName = startScriptName,
RunScriptArguments = runScriptArguments
};
builder.WithAnnotation(annotation)
.ClearContainerFilesSources()
.WithOtlpExporter()
.WithEnvironment("HOST", "0.0.0.0")
.WithEnvironment("HOSTNAME", "0.0.0.0");
if (builder.Resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerfileBuildAnnotation))
{
dockerfileBuildAnnotation.HasEntrypoint = true;
}
return builder;
}
private static void AddInstallCommand(this DockerfileStage builderStage, JavaScriptPackageManagerAnnotation packageManager, JavaScriptInstallCommandAnnotation installCommand)
{
// Use BuildKit cache mount for package manager cache if available
var installCmd = $"{packageManager.ExecutableName} {string.Join(' ', installCommand.Args)}";
if (!string.IsNullOrEmpty(packageManager.CacheMount))
{
builderStage.Run($"--mount=type=cache,target={packageManager.CacheMount} {installCmd}");
}
else
{
builderStage.Run(installCmd);
}
}
private static IResourceBuilder<TResource> CreateDefaultJavaScriptAppBuilder<TResource>(
this IDistributedApplicationBuilder builder,
TResource resource,
string appDirectory,
string runScriptName,
Action<CommandLineArgsCallbackContext>? argsCallback = null) where TResource : JavaScriptAppResource
{
var resourceBuilder = builder.AddResource(resource)
.WithNodeDefaults()
.WithArgs(c =>
{
if (c.Resource.TryGetLastAnnotation<JavaScriptRunScriptAnnotation>(out var runCommand))
{
if (c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager) &&
!string.IsNullOrEmpty(packageManager.ScriptCommand))
{
c.Args.Add(packageManager.ScriptCommand);
}
c.Args.Add(runCommand.ScriptName);
foreach (var arg in runCommand.Args)
{
c.Args.Add(arg);
}
}
argsCallback?.Invoke(c);
})
.WithIconName("CodeJsRectangle")
.WithNpm()
.PublishAsDockerFile(c =>
{
// Only generate a Dockerfile if one doesn't already exist in the app directory
if (File.Exists(Path.Combine(appDirectory, "Dockerfile")))
{
return;
}
c.WithDockerfileBuilder(appDirectory, dockerfileContext =>
{
dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptPublishModeAnnotation>(out var publishMode);
if (c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
// Get custom base image from annotation, if present
dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation);
var baseImage = baseImageAnnotation?.BuildImage ?? GetDefaultBaseImage(appDirectory, "slim", dockerfileContext.Services);
var dockerBuilder = publishMode is not null
? dockerfileContext.Builder.From(baseImage, "build").WorkDir("/app")
: dockerfileContext.Builder.From(baseImage).WorkDir("/app");
// Initialize the Docker build stage with package manager-specific setup commands
// for the default JavaScript app builder (used by Vite and other build-less apps).
packageManager.InitializeDockerBuildStage?.Invoke(dockerBuilder);
var copiedAllSource = false;
// Copy package files first for better layer caching
if (packageManager.PackageFilesPatterns.Count > 0)
{
foreach (var packageFilePattern in packageManager.PackageFilesPatterns)
{
dockerBuilder.Copy(packageFilePattern.Source, packageFilePattern.Destination);
}
}
else
{
dockerBuilder.Copy(".", ".");
copiedAllSource = true;
}
if (c.Resource.TryGetLastAnnotation<JavaScriptInstallCommandAnnotation>(out var installCommand))
{
dockerBuilder.AddInstallCommand(packageManager, installCommand);
}
if (!copiedAllSource)
{
// Copy application source code after dependencies are installed
dockerBuilder.Copy(".", ".");
}
if (c.Resource.TryGetLastAnnotation<JavaScriptBuildScriptAnnotation>(out var buildCommand))
{
var commandArgs = new List<string>() { packageManager.ExecutableName };
if (!string.IsNullOrEmpty(packageManager.ScriptCommand))
{
commandArgs.Add(packageManager.ScriptCommand);
}
commandArgs.Add(buildCommand.ScriptName);
commandArgs.AddRange(buildCommand.Args);
dockerBuilder.Run(string.Join(' ', commandArgs));
}
switch (publishMode?.Mode)
{
case JavaScriptPublishMode.StaticWebsite:
{
var runtimeImage = baseImageAnnotation?.RuntimeImage ?? DefaultYarpImage;
var distPath = GetContainerFilesSourcePath(publishMode.OutputPath);
dockerfileContext.Builder
.From(runtimeImage, "runtime")
.WorkDir("/app")
.CopyFrom("build", distPath, "/app/wwwroot")
.Entrypoint(["dotnet", "/app/yarp.dll"]);
break;
}
case JavaScriptPublishMode.NodeServer:
{
var runtimeImage = baseImageAnnotation?.RuntimeImage ?? GetDefaultBaseImage(appDirectory, "alpine", dockerfileContext.Services);
var outputPath = GetContainerFilesSourcePath(publishMode.OutputPath);
dockerfileContext.Builder
.From(runtimeImage, "runtime")
.WorkDir("/app")
.CopyFrom("build", outputPath, outputPath)
.Env("NODE_ENV", "production")
.User("node")
.Entrypoint(["node", NormalizeRelativePath(publishMode.EntryPoint!)]);
break;
}
case JavaScriptPublishMode.NpmScript:
{
var runtimeImage = baseImageAnnotation?.RuntimeImage ?? GetDefaultBaseImage(appDirectory, "alpine", dockerfileContext.Services);
// Production dependencies stage for optimized image
var prodDepsStage = dockerfileContext.Builder
.From(baseImage, "prod-deps")
.WorkDir("/app");
packageManager.InitializeDockerBuildStage?.Invoke(prodDepsStage);
if (packageManager.PackageFilesPatterns.Count > 0)
{
foreach (var packageFilePattern in packageManager.PackageFilesPatterns)
{
prodDepsStage.Copy(packageFilePattern.Source, packageFilePattern.Destination);
}
}
else
{
prodDepsStage.Copy("package*.json", "./");
}
// Install production-only dependencies using the same base install
// command as the build stage (e.g. 'ci' for npm, 'install --frozen-lockfile'
// for pnpm) plus the production-only flag (e.g. '--omit=dev').
var installAnnotation = c.Resource.TryGetLastAnnotation<JavaScriptInstallCommandAnnotation>(out var installCmd) ? installCmd : null;
if (string.IsNullOrEmpty(installAnnotation?.ProductionInstallArgs))
{
throw new InvalidOperationException($"Package manager '{packageManager.ExecutableName}' does not have ProductionInstallArgs configured, which is required for PublishAsNpmScript.");
}
var prodInstallCmd = $"{packageManager.ExecutableName} {string.Join(' ', installAnnotation.Args)} {installAnnotation.ProductionInstallArgs}";
if (!string.IsNullOrEmpty(packageManager.CacheMount))
{
prodDepsStage.Run($"--mount=type=cache,target={packageManager.CacheMount} {prodInstallCmd}");
}
else
{
prodDepsStage.Run(prodInstallCmd);
}
// Runtime stage: copy build output then overlay prod deps
var runCommand = string.IsNullOrWhiteSpace(publishMode.RunScriptArguments)
? $"{packageManager.ExecutableName} {packageManager.ScriptCommand ?? "run"} {publishMode.StartScriptName}"
: $"{packageManager.ExecutableName} {packageManager.ScriptCommand ?? "run"} {publishMode.StartScriptName} {publishMode.RunScriptArguments}";
dockerfileContext.Builder
.From(runtimeImage, "runtime")
.WorkDir("/app")
.CopyFrom("build", "/app", "/app")
.CopyFrom("prod-deps", "/app/node_modules", "./node_modules")
.Env("NODE_ENV", "production")
.Entrypoint(["sh", "-c", $"exec {runCommand}"]);
break;
}
case JavaScriptPublishMode.NextStandalone:
{
var runtimeImage = baseImageAnnotation?.RuntimeImage ?? GetDefaultBaseImage(appDirectory, "alpine", dockerfileContext.Services);
dockerfileContext.Builder
.From(runtimeImage, "runtime")
.WorkDir("/app")
.Env("NODE_ENV", "production")
.CopyFrom("build", "/app/public", "./public")
.CopyFrom("build", "/app/.next/standalone", "./")
.CopyFrom("build", "/app/.next/static", "./.next/static")
.User("node")
.Entrypoint(["node", "server.js"]);
break;
}
}
}
});
// JavaScript apps default to build-only publishing unless a standalone runtime is enabled.
if (resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerFileAnnotation))
{
dockerFileAnnotation.HasEntrypoint =
resource.TryGetLastAnnotation<JavaScriptPublishModeAnnotation>(out _);
}
else
{
throw new InvalidOperationException("DockerfileBuildAnnotation should exist after calling PublishAsDockerFile.");
}
})
.WithAnnotation(new ContainerFilesSourceAnnotation() { SourcePath = "/app/dist" })
.WithBuildScript("build")
.WithRunScript(runScriptName);
resourceBuilder.WithVSCodeDebugging();
// ensure the package manager command is set before starting the resource
if (builder.ExecutionContext.IsRunMode)
{
builder.OnBeforeStart((_, _) =>
{
if (resourceBuilder.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
resourceBuilder.WithCommand(packageManager.ExecutableName);
}
return Task.CompletedTask;
});
}
return resourceBuilder;
}
/// <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="appDirectory">The path to the directory containing the Vite app.</param>
/// <param name="runScriptName">The name of the script that runs the Vite app. Defaults to "dev".</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");
///
/// builder.Build().Run();
/// </code>
/// </example>
/// </remarks>
[AspireExport(Description = "Adds a Vite application resource")]
public static IResourceBuilder<ViteAppResource> AddViteApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string runScriptName = "dev")
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(appDirectory);
appDirectory = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, appDirectory));
var resource = new ViteAppResource(name, "npm", appDirectory);
var resourceBuilder = builder.CreateDefaultJavaScriptAppBuilder(
resource,
appDirectory,
runScriptName,
argsCallback: c =>
{
// pnpm does not strip the -- separator and passes it to the script, causing Vite to ignore subsequent arguments.
// npm and yarn both strip the -- separator before passing arguments to the script.
// Only add the separator for when necessary.
if (c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager) &&
packageManager.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));
if (!string.IsNullOrEmpty(resource.ViteConfigPath))
{
c.Args.Add("--config");
c.Args.Add(resource.ViteConfigPath);
}
})
.WithHttpEndpoint(env: "PORT")
// Making TLS opt-in for Vite for now
.WithoutHttpsCertificate()
.WithHttpsCertificateConfiguration(async ctx =>
{
string? configTarget = resource.ViteConfigPath;
// First we need to determine if there's an existing --config argument specified
var cfgIndex = ctx.Arguments.IndexOf("--config");
if (cfgIndex >= 0 && cfgIndex + 1 < ctx.Arguments.Count)
{
configTarget = ctx.Arguments[cfgIndex + 1] switch
{
string s when !string.IsNullOrEmpty(s) && !s.StartsWith("--") => s,
ReferenceExpression re => await re.GetValueAsync(ctx.CancellationToken).ConfigureAwait(false),
_ => null,
};
if (string.IsNullOrEmpty(configTarget))
{
// Couldn't determine the config target, so don't modify anything
return;
}
// Remove the original --config argument and its value
ctx.Arguments.RemoveAt(cfgIndex);
ctx.Arguments.RemoveAt(cfgIndex);
}
else if (cfgIndex >= 0)
{
// --config argument is present but is missing a value
return;
}
if (string.IsNullOrEmpty(configTarget))
{
// The user didn't specify a specific vite config file, so we need to look for one of the default config files
foreach (var configFile in s_defaultConfigFiles)
{
var candidatePath = Path.GetFullPath(Path.Join(appDirectory, configFile));
if (File.Exists(candidatePath))
{
configTarget = candidatePath;
break;
}
}
}
if (configTarget is not null)
{
try
{
// Determine the absolute path to the original config file
var absoluteConfigPath = Path.GetFullPath(configTarget, appDirectory);