Repository navigation
Expand file tree
/
Copy pathJavaScriptHostingExtensions.cs
More file actions
3359 lines (2983 loc) · 168 KB
/
Copy pathJavaScriptHostingExtensions.cs
File metadata and controls
3359 lines (2983 loc) · 168 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 ASPIREDENO001 // AddDenoApp and its implementation use the experimental Deno resource
#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";
// Default to the public npm registry so generated Dockerfiles work for customers out of the box.
// Operators who want an internal mirror can override it at build time via `--build-arg NPM_REGISTRY=...`.
// See https://github.com/microsoft/aspire/issues/19370.
private const string DefaultNpmRegistry = "https://registry.npmjs.org/";
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 DenoHelpLink = "https://docs.deno.com/runtime/getting_started/installation/";
private const string YarnHelpLink = "https://yarnpkg.com/getting-started/install";
private const string PnpmHelpLink = "https://pnpm.io/installation";
private const string DenoDefaultUser = "deno";
private const string DenoDefaultUserAndGroup = "deno:deno";
// Deno's dependency store. Pinned to a known path so multi-stage builds can copy it from the
// build stage into the runtime stage. See https://docs.deno.com/runtime/reference/docker/.
private const string DenoCacheDirectory = "/deno-dir";
// 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. A caller can configure only a runtime
// image, which leaves BuildImage null, so fall back to the package manager's own image
// before the Node.js default - bun and deno are absent from the Node.js images.
dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation);
resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager);
var baseBuildImage = baseImageAnnotation?.BuildImage
?? packageManager?.DefaultBuildImage
?? defaultBaseImage.Value;
var builderStage = dockerfileContext.Builder
.From(baseBuildImage, "build")
.EmptyLine()
.WorkDir("/app");
if (packageManager is not null)
{
// 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))
{
copiedAllSource = builderStage.CopyPackageFilesForInstall(packageManager);
builderStage.AddInstallCommand(packageManager, installCommand);
}
if (!copiedAllSource)
{
// Copy application source code after dependencies are installed
builderStage.Copy(".", ".");
}
if (resource.TryGetLastAnnotation<JavaScriptBuildScriptAnnotation>(out var buildCommand))
{
builderStage.EmptyLine()
.Run(BuildPackageScriptCommand(packageManager, buildCommand));
}
}
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,
"deno" => DenoHelpLink,
"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))
{
copiedAllSource = builderStage.CopyPackageFilesForInstall(packageManager);
builderStage.AddInstallCommand(packageManager, installCommand);
}
if (!copiedAllSource)
{
builderStage.Copy(".", ".");
}
if (resource.TryGetLastAnnotation<JavaScriptBuildScriptAnnotation>(out var buildCommand))
{
builderStage.EmptyLine()
.Run(BuildPackageScriptCommand(packageManager, buildCommand));
}
}
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 = BuildProductionInstallCommand(pm, install);
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;
});
// The default Docker image used for AddDenoApp build and runtime stages.
// Pin to a concrete tag because denoland/deno does not publish floating major tags.
// The official image provides a non-root `deno` user.
private const string DefaultDenoImage = "denoland/deno:2.9.0";
// Default .dockerignore content emitted alongside the generated Deno Dockerfile using
// BuildKit's per-Dockerfile ignore convention. The runtime stage copies source from the
// build stage, but an ignore file keeps local .git, dotenv files, and Aspire artifacts out
// of the build context. Deno can still materialize node_modules for npm compatibility
// (`--node-modules-dir=auto` or `manual`), so keep local dependency folders out of
// the build context just like the Bun/Node variants.
private const string DefaultDenoBuildContextIgnoreContent = """
# Generated by Aspire. Author <contextRoot>/.dockerignore to override.
node_modules
.git
.gitignore
.DS_Store
.env
.env.*
.aspire
aspire-output
Dockerfile
Dockerfile.*
*.Dockerfile.dockerignore
.dockerignore
*.tsbuildinfo
""";
/// <summary>
/// Adds a Deno application to the application model. Deno 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 Deno application.</param>
/// <param name="scriptPath">The path to the script (for example, <c>main.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>
/// In run mode this method executes the script directly using <c>deno run -A <script></c>. Generated
/// containers use the more restrictive <c>deno run --allow-net --allow-env <script></c> default. Deno
/// natively runs JavaScript and TypeScript files so no transpile step is required. Deno's built-in OpenTelemetry
/// integration is enabled via the <c>OTEL_DENO</c> environment variable, so traces, metrics, and logs flow to the
/// Aspire dashboard with no application-level SDK wiring.
///
/// The full Deno flag surface (granular permissions, <c>--config</c>/<c>--import-map</c>/<c>--lock</c>, unstable
/// features, <c>--watch</c>, inspector flags, script args, and the <c>run</c>/<c>task</c>/<c>serve</c> sub-command
/// modes) can be configured with the fluent <c>WithDeno*</c> methods (for example <see cref="WithDenoAllow"/>,
/// <see cref="WithDenoConfig"/>, <see cref="WithDenoUnstable"/>, <see cref="WithDenoServe"/>). Configuring any of
/// these fully replaces the default arg vector, so a Deno workload never has to fall back to <c>AddExecutable</c>.
///
/// If the application directory contains a <c>package.json</c>, <c>deno.json</c>, or <c>deno.jsonc</c> file, Deno will
/// be added as the default package manager. When publishing to a container, the default base image is
/// <c>denoland/deno:2.9.0</c> for both the build and runtime stages.
/// </remarks>
/// <example>
/// Add a Deno app to the application model:
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddDenoApp("api", "../api", "main.ts");
///
/// builder.Build().Run();
/// </code>
/// </example>
[AspireExport]
[Experimental("ASPIREDENO001", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
public static IResourceBuilder<DenoAppResource> AddDenoApp(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);
ValidateDenoScriptPath(scriptPath);
var resource = new DenoAppResource(name, "deno", appDirectory);
var resourceBuilder = builder.AddResource(resource)
.WithDenoDefaults()
.WithArgs(c =>
{
// An explicit Deno command-line annotation (configured via the WithDeno* fluent flag methods)
// composes with WithRunScript. If no fluent mode method selected run/task/serve explicitly,
// a run script still launches through `deno task <name>` and the Deno flags that are valid for
// task launches are preserved.
if (c.Resource.TryGetLastAnnotation<DenoCommandLineAnnotation>(out var denoCommandLine))
{
var serveEndpointArguments = denoCommandLine.Mode == DenoCommandMode.Serve
? GetDenoServeEndpointArguments(c.Resource, c.ExecutionContext.IsPublishMode)
: null;
c.Resource.TryGetLastAnnotation<JavaScriptRunScriptAnnotation>(out var runScript);
c.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager);
foreach (var arg in BuildDenoArgs(
denoCommandLine,
scriptPath,
serveEndpointArguments,
runScript: runScript,
packageManager: packageManager))
{
c.Args.Add(arg);
}
}
// If the JavaScriptRunScriptAnnotation is present, use that to run the app via `deno task <name>`.
else 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
{
// Direct execution differs from Node/Bun: Deno requires the `run` subcommand and, unlike
// Node/Bun, runs under a deny-by-default permission model. Aspire injects configuration via
// environment variables (PORT, OTLP endpoints, cert paths) and the app reads them with
// Deno.env / opens sockets with Deno.serve, both of which throw NotCapable without an explicit
// grant. `-A` (allow-all) is used to keep the developer experience on par with Node/Bun, whose
// runtimes are permissive by default. Users who want least-privilege can opt out with
// WithDenoAllowAll(false) and add explicit permission flags via the WithDeno* methods.
c.Args.Add("run");
c.Args.Add("-A");
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 emitted alongside the generated Dockerfile using
// BuildKit's per-Dockerfile ignore convention (<dockerfile-name>.dockerignore). The
// runtime stage copies source from the build stage, so an ignore file keeps the user's
// local .git, dotenv files, and Aspire output out of the image.
if (dockerfileContext.Resource.TryGetLastAnnotation<DockerfileBuildAnnotation>(out var dockerfileBuildAnnotation))
{
dockerfileBuildAnnotation.BuildContextIgnoreContent ??= DefaultDenoBuildContextIgnoreContent;
}
ThrowIfUnsupportedDenoDockerfileOptions(dockerfileContext.Resource);
// Deno ships its own runtime, so both stages default to the same Deno image. Unlike the Bun
// variant there is no separate production-dependency install stage: Deno caches remote and
// npm dependencies under DENO_DIR. Direct run/serve entrypoints pre-populate that cache in
// the build stage and use --cached-only at runtime. Task entrypoints are opaque shell
// commands in deno.json, so Aspire cannot safely infer their module graph.
var baseBuildImage = baseImageAnnotation?.BuildImage ?? DefaultDenoImage;
var buildStage = dockerfileContext.Builder
.From(baseBuildImage, "build");
// Package-script builds install from the manifest layer before copying the remaining source.
// Direct run/serve builds copy the full module graph first, then cache it with the same
// resolution and lock flags used by the runtime entrypoint.
dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptPublishModeAnnotation>(out var publishMode);
if (publishMode?.Mode == JavaScriptPublishMode.PackageScript)
{
if (!dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager) ||
!dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptInstallCommandAnnotation>(out var installCommand))
{
throw new InvalidOperationException("PublishAsPackageScript requires a Deno package manager. Add a deno.json file or call WithDeno().");
}
buildStage.EmptyLine();
packageManager.InitializeDockerBuildStage?.Invoke(buildStage);
buildStage
.EmptyLine()
.WorkDir("/app");
var copiedAllSource = buildStage.CopyPackageFilesForInstall(packageManager);
buildStage.AddInstallCommand(packageManager, installCommand);
if (!copiedAllSource)
{
buildStage.Copy(".", ".");
}
}
else
{
var denoCacheCommand = BuildDenoCacheCommand(dockerfileContext.Resource, scriptPath, resource.WorkingDirectory);
buildStage
.EmptyLine()
// Pin DENO_DIR to a deterministic path so the runtime stage can copy the cache
// regardless of the base image's own default. The official denoland/deno image
// already uses /deno-dir, but a custom build image (WithDockerfileBaseImage) may not.
.Env("DENO_DIR", "/deno-dir")
.EmptyLine()
.WorkDir("/app")
.Copy(".", ".")
.EmptyLine()
.Run(denoCacheCommand);
}
if (dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptBuildScriptAnnotation>(out var buildCommand))
{
if (!dockerfileContext.Resource.TryGetLastAnnotation<JavaScriptPackageManagerAnnotation>(out var packageManager))
{
throw new InvalidOperationException("WithBuildScript requires a Deno package manager. Add a deno.json file or call WithDeno().");
}
buildStage
.EmptyLine()
.Run(BuildPackageScriptCommand(packageManager, buildCommand));
}
var logger = dockerfileContext.Services.GetService<ILogger<JavaScriptAppResource>>();
dockerfileContext.Builder.AddContainerFilesStages(dockerfileContext.Resource, logger);
var hasCustomRuntimeImage = baseImageAnnotation?.RuntimeImage is not null;
var baseRuntimeImage = baseImageAnnotation?.RuntimeImage ?? DefaultDenoImage;
var runtimeStage = dockerfileContext.Builder
.From(baseRuntimeImage, "runtime")
.EmptyLine()
// Match the build stage's DENO_DIR so the copied cache is discovered at runtime.
.Env("DENO_DIR", "/deno-dir")
.EmptyLine()
.WorkDir("/app");
if (hasCustomRuntimeImage)
{
runtimeStage
.CopyFrom("build", "/app", "/app")
// Ship the pre-populated dependency cache so direct run/serve container starts
// resolve everything locally instead of re-fetching from the network.
.CopyFrom("build", "/deno-dir", "/deno-dir");
}
else
{
runtimeStage
.CopyFrom("build", "/app", "/app", DenoDefaultUserAndGroup)
// Ship the pre-populated dependency cache so direct run/serve container starts
// resolve everything locally instead of re-fetching from the network.
.CopyFrom("build", "/deno-dir", "/deno-dir", DenoDefaultUserAndGroup);
}
runtimeStage