Repository navigation
Expand file tree
/
Copy pathJavaScriptHostingExtensions.cs
More file actions
2651 lines (2350 loc) · 130 KB
/
Copy pathJavaScriptHostingExtensions.cs
File metadata and controls
2651 lines (2350 loc) · 130 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
#pragma warning disable ASPIRECOMMAND001
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.ApplicationModel.Docker;
using Aspire.Hosting.JavaScript;
using Aspire.Hosting.Pipelines;
using Aspire.Hosting.Publishing;
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 partial class JavaScriptHostingExtensions
{
private const string BrowserCapability = "browser";
private const string DefaultNodeVersion = "22";
private const string DefaultNpmRegistry = "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/";
private const string DefaultPnpmVersion = "10.30.1";
private const string DefaultJavaScriptRunScriptName = "dev";
private const string DefaultYarpImage = Yarp.YarpContainerImageTags.Registry + "/" + Yarp.YarpContainerImageTags.Image + ":" + Yarp.YarpContainerImageTags.Tag;
// Help links surfaced when a required command is missing, mapped to a command by ResolveHelpLink.
private const string NodeHelpLink = "https://nodejs.org/en/download/";
private const string NpmHelpLink = "https://nodejs.org/en/download";
private const string BunHelpLink = "https://bun.sh/docs/installation";
private const string YarnHelpLink = "https://yarnpkg.com/getting-started/install";
private const string PnpmHelpLink = "https://pnpm.io/installation";
// npm/yarn/pnpm are Node CLIs: whether they install packages or launch the app's run script, they spawn
// node, so node must be on PATH too. bun is a full Node replacement and needs no node.
private static readonly string[] s_nodeBasedPackageManagers = ["npm", "yarn", "pnpm"];
// 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 AspireViteConfigPathToken = "%%ASPIRE_VITE_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_CONFIG_PATH%% is replaced with the relative 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_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>
/// <ats-returns>The resource builder.</ats-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]
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, "node");
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()
.WithRequiredCommandsFromPackageManager("node")
.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;
});
// Registers a hook that materializes the resource's required commands just before start. The annotations are
// added on BeforeStartEvent in every execution context, but they only have an effect in run mode, where
// RequiredCommandValidationEventingSubscriber validates them against the local PATH on
// BeforeResourceStartedEvent (which fires after BeforeStartEvent). Resolving them here - rather than eagerly
// as each With* method runs - lets the package-manager selection settle first, so a later selection fully
// replaces an earlier one without having to remove stale RequiredCommandAnnotations.
// See https://github.com/microsoft/aspire/issues/18625.
//
// runtimeCommand is the executable the app was created to run with (node for
// AddNodeApp/AddViteApp/AddJavaScriptApp, bun for AddBunApp); it launches the app whenever the app is not
// routed through a package-manager run script.
private static IResourceBuilder<TResource> WithRequiredCommandsFromPackageManager<TResource>(
this IResourceBuilder<TResource> builder,
string runtimeCommand) where TResource : JavaScriptAppResource
{
var resource = builder.Resource;
builder.ApplicationBuilder.OnBeforeStart((_, _) =>
{
foreach (var (command, helpLink) in ResolveRequiredCommands(resource, runtimeCommand))
{
// Idempotent: skip commands already present so an unexpected second publish of BeforeStartEvent
// cannot add duplicate RequiredCommandAnnotations for the same command.
if (!resource.Annotations.OfType<RequiredCommandAnnotation>().Any(a => string.Equals(a.Command, command, StringComparison.Ordinal)))
{
resource.Annotations.Add(new RequiredCommandAnnotation(command) { HelpLink = helpLink });
}
}
return Task.CompletedTask;
});
return builder;
}
// Resolves the executables that must be on PATH for the app to install and run, from how the app is actually
// launched. Two independent axes:
// - Runtime: apps that launch via a named package-manager run script (npm run dev / bun run dev) - which is
// every AddViteApp/AddJavaScriptApp, plus AddNodeApp/AddBunApp when WithRunScript is used - are launched by
// the package manager, so the package manager is the runtime. Apps that invoke a script file directly
// (AddNodeApp "server.js" / AddBunApp "server.ts" with no run script) are launched by their fixed runtime
// (node/bun) regardless of any package manager.
// - Install: a selected package manager also runs at install time, so it must be on PATH even when a
// different runtime launches the app - e.g. AddNodeApp(...).WithBun() runs `node server.js` but installs
// with `bun`, so both node and bun are required.
// npm/yarn/pnpm additionally require node (they are Node CLIs); bun does not. This projection is what fixes
// https://github.com/microsoft/aspire/issues/18625 (AddViteApp(...).WithBun() requires only bun) without
// dropping the runtime for direct-script apps.
private static IEnumerable<(string Command, string? HelpLink)> ResolveRequiredCommands(IResource resource, string runtimeCommand)
{
resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager);
// A package manager only replaces the runtime when the app launches through a run script; otherwise the
// runtime executes the script file directly.
var launchesViaRunScript = resource.TryGetLastAnnotation<JavaScriptRunScriptAnnotation>(out _);
var runCommand = launchesViaRunScript && packageManager is not null
? packageManager.ExecutableName
: runtimeCommand;
var commands = new HashSet<string>(StringComparer.Ordinal) { runCommand };
if (packageManager is not null)
{
commands.Add(packageManager.ExecutableName);
}
if (commands.Overlaps(s_nodeBasedPackageManagers))
{
commands.Add("node");
}
return commands.Select(static command => (command, ResolveHelpLink(command)));
}
// Maps a required executable to the install/help link surfaced when the command is missing on PATH.
private static string? ResolveHelpLink(string command) => command switch
{
"node" => NodeHelpLink,
"npm" => NpmHelpLink,
"bun" => BunHelpLink,
"yarn" => YarnHelpLink,
"pnpm" => PnpmHelpLink,
// Unknown/custom package manager: no specific install help link.
_ => null,
};
// The default Docker image used for AddBunApp build and runtime stages.
// Pinned to the major version tag to keep generated Dockerfiles deterministic
// while still picking up patch updates. The image provides a non-root `bun` user.
private const string DefaultBunImage = "oven/bun:1";
// Default .dockerignore content emitted alongside the generated Bun Dockerfile using
// BuildKit's per-Dockerfile ignore convention. The runtime stage uses `COPY . .` from the
// build context so an ignore file is required to keep local node_modules, .git, dotenv
// files, etc. out of the published image. Mirrors the recommendation at
// https://bun.com/guides/ecosystem/docker.
private const string DefaultBunBuildContextIgnoreContent = """
# Generated by Aspire. Author <contextRoot>/.dockerignore to override.
node_modules
.git
.gitignore
.DS_Store
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
.env
.env.*
.aspire
aspire-output
Dockerfile
Dockerfile.*
*.Dockerfile.dockerignore
.dockerignore
*.tsbuildinfo
""";
/// <summary>
/// Adds a Bun application to the application model. Bun 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 Bun application.</param>
/// <param name="scriptPath">The path to the script (for example, <c>server.ts</c>) relative to <paramref name="appDirectory"/> to run.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <ats-returns>The resource builder.</ats-returns>
/// <remarks>
/// This method executes the script directly using <c>bun <script></c>. Bun natively runs JavaScript and TypeScript
/// files so no transpile step is required.
///
/// If the application directory contains a <c>package.json</c> file, Bun will be added as the default package manager.
/// When publishing to a container, the default base image is <c>oven/bun:1</c> for both the build and runtime stages.
/// </remarks>
/// <example>
/// Add a Bun app to the application model:
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddBunApp("api", "../api", "server.ts");
///
/// builder.Build().Run();
/// </code>
/// </example>
[AspireExport]
public static IResourceBuilder<BunAppResource> AddBunApp(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 BunAppResource(name, "bun", appDirectory);
var resourceBuilder = builder.AddResource(resource)
.WithBunDefaults()
.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 =>
{
// Get custom base image from annotation, if present
dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation);
// Provide a default .dockerignore that publishers emit alongside the generated
// Dockerfile using BuildKit's per-Dockerfile ignore convention
// (<dockerfile-name>.dockerignore). The runtime stage below copies source
// directly from the build context (`COPY . .`), so without an ignore file the
// user's local node_modules, .git, etc. would leak into the build context and
// into the image. Matches the recommendation at
// https://bun.com/guides/ecosystem/docker. The annotation lookup is guarded
// because WithDockerfileBuilder always adds a DockerfileBuildAnnotation, but
// we want to remain robust if a future refactor changes that.
if (dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerfileBuildAnnotation))
{
dockerfileBuildAnnotation.BuildContextIgnoreContent ??= DefaultBunBuildContextIgnoreContent;
}
// Bun ships its own runtime, so both stages default to the same Bun image rather than
// using a node-based image as in AddNodeApp.
var baseBuildImage = baseImageAnnotation?.BuildImage ?? DefaultBunImage;
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.
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)
{
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);
// When the package manager exposes production-only install args (e.g. bun's
// `--production`), emit a dedicated `prod-deps` stage that installs only the
// runtime dependencies. The runtime stage then overlays this stage's
// `node_modules` on top of the build output so the final image does not ship
// devDependencies. This mirrors the multi-stage pattern recommended at
// https://bun.com/guides/ecosystem/docker.
JavaScriptPackageManagerAnnotation? prodPackageManager = null;
JavaScriptInstallCommandAnnotation? prodInstallCommand = null;
var emitProdDepsStage =
resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out prodPackageManager) &&
resource.TryGetLastAnnotation<JavaScriptInstallCommandAnnotation>(out prodInstallCommand) &&
!string.IsNullOrEmpty(prodInstallCommand.ProductionInstallArgs);
if (emitProdDepsStage)
{
var pm = prodPackageManager!;
var install = prodInstallCommand!;
var prodDepsStage = dockerfileContext.Builder
.From(baseBuildImage, "prod-deps")
.EmptyLine()
.WorkDir("/app");
pm.InitializeDockerBuildStage?.Invoke(prodDepsStage);
if (pm.PackageFilesPatterns.Count > 0)
{
foreach (var packageFilePattern in pm.PackageFilesPatterns)
{
prodDepsStage.Copy(packageFilePattern.Source, packageFilePattern.Destination);
}
}
else
{
prodDepsStage.Copy("package.json", "./");
}
var prodInstallCmd = $"{pm.ExecutableName} {string.Join(' ', install.Args)} {install.ProductionInstallArgs}";
if (!string.IsNullOrEmpty(pm.CacheMount))
{
prodDepsStage.Run($"--mount=type=cache,target={pm.CacheMount} {prodInstallCmd}");
}
else
{
prodDepsStage.Run(prodInstallCmd);
}
}
var baseRuntimeImage = baseImageAnnotation?.RuntimeImage ?? DefaultBunImage;
var runtimeBuilder = dockerfileContext.Builder
.From(baseRuntimeImage, "runtime")
.EmptyLine()
.WorkDir("/app");
if (emitProdDepsStage)
{
// Mirror the multi-stage pattern recommended at https://bun.com/guides/ecosystem/docker:
// pull node_modules from the production-only install stage and the rest of the app
// source from the build context. The build stage exists for validation/caching but
// its filesystem is intentionally not copied here, because Docker's COPY --from=
// merges directories and would let devDependencies survive the overlay.
//
// A matching .dockerignore is emitted next to the published Dockerfile via the
// DockerfileBuildAnnotation.BuildContextIgnoreContent property (BuildKit's
// <dockerfile-name>.dockerignore convention) so local build artifacts
// (node_modules, .git, .aspire, etc.) do not leak into the image via COPY . . below.
runtimeBuilder
.CopyFrom("prod-deps", "/app/node_modules", "./node_modules")
.Copy(".", ".");
}
else
{
runtimeBuilder.CopyFrom("build", "/app", "/app");
}
runtimeBuilder
.AddContainerFiles(dockerfileContext.Resource, "/app", logger)
.EmptyLine()
.Env("NODE_ENV", "production")
.EmptyLine()
// The official oven/bun images provide a non-root `bun` user (UID 1000).
// See https://hub.docker.com/r/oven/bun
.User("bun")
.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 bun as the package manager if a package.json file exists
resourceBuilder.WithBun();
}
resourceBuilder.WithVSCodeDebugging(scriptPath, "bun");
if (builder.ExecutionContext.IsRunMode)
{
builder.OnBeforeStart((_, _) =>
{
// Set the command to the package manager executable if a WithRunScript was configured.
// For the default Bun package manager this is a no-op (executable is "bun"), but it correctly
// handles cases where a user opts into a different package manager (e.g., WithYarn).
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> WithBunDefaults<TResource>(this IResourceBuilder<TResource> builder) where TResource : JavaScriptAppResource =>
builder.WithOtlpExporter()
.WithRequiredCommandsFromPackageManager("bun")
// Bun honors NODE_ENV for module resolution and runtime mode the same way Node does.
// See https://bun.com/docs/runtime/env
.WithEnvironment("NODE_ENV", builder.ApplicationBuilder.Environment.IsDevelopment() ? "development" : "production")
.WithCertificateTrustConfiguration((ctx) =>
{
// Configure Bun's Node-compatible custom-CA hook for append-scope trust.
// See https://bun.com/blog/bun-v1.3-nodejs-compatibility#node-extra-ca-certs.
//
// Important: Bun 1.3.10 and 1.3.14 still fail to trust Aspire's injected
// self-signed localhost certificate for outgoing HTTPS requests with
// UNABLE_TO_VERIFY_LEAF_SIGNATURE, even when NODE_EXTRA_CA_CERTS is set.
// curl --cacert and Node.js with NODE_EXTRA_CA_CERTS accept the same cert.
// Track the Bun dependency in https://github.com/microsoft/aspire/issues/17455.
if (ctx.Scope == CertificateTrustScope.Append)
{
ctx.EnvironmentVariables["NODE_EXTRA_CA_CERTS"] = ctx.CertificateBundlePath;
}
else
{
// Bun reads NODE_OPTIONS for a subset of Node flags including --use-openssl-ca,
// which switches TLS verification to the OS trust store (matching the Override
// and System scopes here). See https://bun.com/docs/cli/run#node-options.
// This does not work around the Aspire dev-certificate issue above unless that
// certificate is trusted by the selected OS/OpenSSL store.
if (ctx.EnvironmentVariables.TryGetValue("NODE_OPTIONS", out var existingOptionsObj))
{
ctx.EnvironmentVariables["NODE_OPTIONS"] = existingOptionsObj switch
{
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]
public static IResourceBuilder<JavaScriptAppResource> AddJavaScriptApp(this IDistributedApplicationBuilder builder, [ResourceName] string name, string appDirectory, string runScriptName = DefaultJavaScriptRunScriptName)
{
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("ASPIREJAVASCRIPT001", 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("ASPIREJAVASCRIPT001", 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);
}
#pragma warning disable ASPIREEXPORT009 // Polyglot entry point — collision is intentional
/// <summary>
/// Publishes the JavaScript application as a standalone static website using YARP.
/// </summary>
[Experimental("ASPIREJAVASCRIPT001", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
[AspireExport("publishAsStaticWebsite")]
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);
}
[Experimental("ASPIREJAVASCRIPT001", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
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>