-
-
Notifications
You must be signed in to change notification settings - Fork 240
/
angular-vite-plugin.ts
675 lines (598 loc) · 20.2 KB
/
angular-vite-plugin.ts
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
import { CompilerHost, NgtscProgram } from '@angular/compiler-cli';
import { transformAsync } from '@babel/core';
import { resolve } from 'node:path';
import * as compilerCli from '@angular/compiler-cli';
import * as ts from 'typescript';
import { createRequire } from 'node:module';
import {
ModuleNode,
normalizePath,
Plugin,
UserConfig,
ViteDevServer,
preprocessCSS,
ResolvedConfig,
} from 'vite';
import { createCompilerPlugin } from './compiler-plugin.js';
import {
StyleUrlsResolver,
TemplateUrlsResolver,
} from './component-resolvers.js';
import { augmentHostWithResources } from './host.js';
import { jitPlugin } from './angular-jit-plugin.js';
import { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';
import {
angularApplicationPreset,
createJitResourceTransformer,
SourceFileCache,
} from './utils/devkit.js';
import { angularVitestPlugin } from './angular-vitest-plugin.js';
const require = createRequire(import.meta.url);
import { getFrontmatterMetadata } from './authoring/frontmatter.js';
import {
defaultMarkdownTemplateTransforms,
MarkdownTemplateTransform,
} from './authoring/markdown-transform.js';
export interface PluginOptions {
tsconfig?: string;
workspaceRoot?: string;
inlineStylesExtension?: string;
jit?: boolean;
advanced?: {
/**
* Custom TypeScript transformers that are run before Angular compilation
*/
tsTransformers?: ts.CustomTransformers;
};
experimental?: {
/**
* Enable experimental support for Analog file extension
*/
supportAnalogFormat?:
| boolean
| {
include: string[];
};
markdownTemplateTransforms?: MarkdownTemplateTransform[];
};
supportedBrowsers?: string[];
transformFilter?: (code: string, id: string) => boolean;
/**
* Additional files to include in compilation
*/
include?: string[];
additionalContentDirs?: string[];
}
interface EmitFileResult {
content?: string;
map?: string;
dependencies: readonly string[];
hash?: Uint8Array;
errors: (string | ts.DiagnosticMessageChain)[];
warnings: (string | ts.DiagnosticMessageChain)[];
}
type FileEmitter = (file: string) => Promise<EmitFileResult | undefined>;
/**
* TypeScript file extension regex
* Match .(c or m)ts, .ts extensions with an optional ? for query params
* Ignore .tsx extensions
*/
const TS_EXT_REGEX = /\.[cm]?(ts|analog|ag)[^x]?\??/;
export function angular(options?: PluginOptions): Plugin[] {
/**
* Normalize plugin options so defaults
* are used for values not provided.
*/
const pluginOptions = {
tsconfig:
options?.tsconfig ??
(process.env['NODE_ENV'] === 'test'
? './tsconfig.spec.json'
: './tsconfig.app.json'),
workspaceRoot: options?.workspaceRoot ?? process.cwd(),
inlineStylesExtension: options?.inlineStylesExtension ?? 'css',
advanced: {
tsTransformers: {
before: options?.advanced?.tsTransformers?.before ?? [],
after: options?.advanced?.tsTransformers?.after ?? [],
afterDeclarations:
options?.advanced?.tsTransformers?.afterDeclarations ?? [],
},
},
supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],
jit: options?.experimental?.supportAnalogFormat ? false : options?.jit,
supportAnalogFormat: options?.experimental?.supportAnalogFormat ?? false,
markdownTemplateTransforms:
options?.experimental?.markdownTemplateTransforms ??
defaultMarkdownTemplateTransforms,
include: options?.include ?? [],
additionalContentDirs: options?.additionalContentDirs ?? [],
};
// The file emitter created during `onStart` that will be used during the build in `onLoad` callbacks for TS files
let fileEmitter: FileEmitter | undefined;
let compilerOptions = {};
// Temporary deep import for transformer support
const {
mergeTransformers,
replaceBootstrap,
} = require('@ngtools/webpack/src/ivy/transformation');
const {
augmentProgramWithVersioning,
augmentHostWithCaching,
} = require('@ngtools/webpack/src/ivy/host');
const ts = require('typescript');
// let compilerCli: typeof import('@angular/compiler-cli');
let userConfig: UserConfig;
let resolvedConfig: ResolvedConfig;
let rootNames: string[];
let host: ts.CompilerHost;
let nextProgram: NgtscProgram | undefined | ts.Program;
let builderProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram;
let watchMode = false;
const sourceFileCache = new SourceFileCache();
const isProd = process.env['NODE_ENV'] === 'production';
const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
const isStackBlitz = !!process.versions['webcontainer'];
const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';
const jit =
typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;
let viteServer: ViteDevServer | undefined;
let styleTransform: (
code: string,
filename: string
) => ReturnType<typeof preprocessCSS> | undefined;
const styleUrlsResolver = new StyleUrlsResolver();
const templateUrlsResolver = new TemplateUrlsResolver();
function angularPlugin(): Plugin {
return {
name: '@analogjs/vite-plugin-angular',
async config(config, { command }) {
watchMode = command === 'serve';
userConfig = config;
pluginOptions.tsconfig =
options?.tsconfig ??
resolve(
config.root || '.',
process.env['NODE_ENV'] === 'test'
? './tsconfig.spec.json'
: './tsconfig.app.json'
);
return {
esbuild: config.esbuild ?? false,
optimizeDeps: {
include: ['rxjs/operators', 'rxjs'],
exclude: ['@angular/platform-server'],
esbuildOptions: {
plugins: [
createCompilerPlugin(
{
tsconfig: pluginOptions.tsconfig,
sourcemap: !isProd,
advancedOptimizations: isProd,
jit,
incremental: watchMode,
},
isTest,
!isAstroIntegration
),
],
define: {
ngJitMode: 'false',
ngI18nClosureMode: 'false',
...(watchMode ? {} : { ngDevMode: 'false' }),
},
},
},
resolve: {
conditions: ['style'],
},
};
},
configResolved(config) {
resolvedConfig = config;
},
configureServer(server) {
viteServer = server;
server.watcher.on('add', () => setupCompilation(resolvedConfig));
server.watcher.on('unlink', () => setupCompilation(resolvedConfig));
},
async buildStart() {
setupCompilation(resolvedConfig);
// Only store cache if in watch mode
if (watchMode) {
augmentHostWithCaching(host, sourceFileCache);
}
await buildAndAnalyze();
},
async handleHotUpdate(ctx) {
// The `handleHotUpdate` hook may be called before the `buildStart`,
// which sets the compilation. As a result, the `host` may not be available
// yet for use, leading to build errors such as "cannot read properties of undefined"
// (because `host` is undefined).
if (!host) {
return;
}
if (TS_EXT_REGEX.test(ctx.file)) {
sourceFileCache.invalidate([ctx.file.replace(/\?(.*)/, '')]);
await buildAndAnalyze();
}
if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
/**
* Check to see if this was a direct request
* for an external resource (styles, html).
*/
const isDirect = ctx.modules.find(
(mod) => ctx.file === mod.file && mod.id?.includes('?direct')
);
if (isDirect) {
return ctx.modules;
}
const mods: ModuleNode[] = [];
ctx.modules.forEach((mod) => {
mod.importers.forEach((imp) => {
sourceFileCache.invalidate([imp.id as string]);
ctx.server.moduleGraph.invalidateModule(imp);
mods.push(imp);
});
});
await buildAndAnalyze();
return mods;
}
return ctx.modules;
},
async transform(code, id) {
// Skip transforming node_modules
if (id.includes('node_modules')) {
return;
}
/**
* Check for options.transformFilter
*/
if (
options?.transformFilter &&
!(options?.transformFilter(code, id) ?? true)
) {
return;
}
/**
* Check for .ts extenstions for inline script files being
* transformed (Astro).
*
* Example ID:
*
* /src/pages/index.astro?astro&type=script&index=0&lang.ts
*/
if (id.includes('type=script')) {
return;
}
/**
* Skip transforming content files
*/
if (id.includes('analog-content-')) {
return;
}
if (TS_EXT_REGEX.test(id)) {
if (id.includes('.ts?')) {
// Strip the query string off the ID
// in case of a dynamically loaded file
id = id.replace(/\?(.*)/, '');
}
/**
* Re-analyze on each transform
* for test(Vitest)
*/
if (isTest) {
const tsMod = viteServer?.moduleGraph.getModuleById(id);
if (tsMod) {
sourceFileCache.invalidate([id]);
await buildAndAnalyze();
}
}
const templateUrls = templateUrlsResolver.resolve(code, id);
const styleUrls = styleUrlsResolver.resolve(code, id);
if (watchMode) {
for (const urlSet of [...templateUrls, ...styleUrls]) {
// `urlSet` is a string where a relative path is joined with an
// absolute path using the `|` symbol.
// For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.
const [, absoluteFileUrl] = urlSet.split('|');
this.addWatchFile(absoluteFileUrl);
}
}
const typescriptResult = await fileEmitter?.(id);
if (
typescriptResult?.warnings &&
typescriptResult?.warnings.length > 0
) {
this.warn(`${typescriptResult.warnings.join('\n')}`);
}
if (typescriptResult?.errors && typescriptResult?.errors.length > 0) {
this.error(`${typescriptResult.errors.join('\n')}`);
}
// return fileEmitter
let data = typescriptResult?.content ?? '';
if (jit && data.includes('angular:jit:')) {
data = data.replace(
/angular:jit:style:inline;/g,
'virtual:angular:jit:style:inline;'
);
templateUrls.forEach((templateUrlSet) => {
const [templateFile, resolvedTemplateUrl] =
templateUrlSet.split('|');
data = data.replace(
`angular:jit:template:file;${templateFile}`,
`${resolvedTemplateUrl}?raw`
);
});
styleUrls.forEach((styleUrlSet) => {
const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');
data = data.replace(
`angular:jit:style:file;${styleFile}`,
`${resolvedStyleUrl}?inline`
);
});
}
if (jit) {
return {
code: data,
map: null,
};
}
const forceAsyncTransformation =
/for\s+await\s*\(|async\s+function\s*\*/.test(data);
const useInputSourcemap = (!isProd ? undefined : false) as undefined;
if (
(id.endsWith('.analog') || id.endsWith('.agx')) &&
pluginOptions.supportAnalogFormat &&
fileEmitter
) {
sourceFileCache.invalidate([`${id}.ts`]);
const ngFileResult = await fileEmitter!(`${id}.ts`);
data = ngFileResult?.content || '';
if (id.includes('.agx')) {
const metadata = await getFrontmatterMetadata(code);
data += metadata;
}
}
if (!forceAsyncTransformation && !isProd) {
return {
code: data,
map: null,
};
}
const babelResult = await transformAsync(data, {
filename: id,
inputSourceMap: (useInputSourcemap
? undefined
: false) as undefined,
sourceMaps: !isProd ? 'inline' : false,
compact: false,
configFile: false,
babelrc: false,
browserslistConfigFile: false,
plugins: [],
presets: [
[
angularApplicationPreset,
{
supportedBrowsers: pluginOptions.supportedBrowsers,
forceAsyncTransformation,
optimize: isProd && {},
},
],
],
});
return {
code: babelResult?.code ?? '',
map: babelResult?.map,
};
}
return undefined;
},
};
}
return [
angularPlugin(),
(isTest && !isStackBlitz && angularVitestPlugin()) as Plugin,
(jit &&
jitPlugin({
inlineStylesExtension: pluginOptions.inlineStylesExtension,
})) as Plugin,
buildOptimizerPlugin({
isProd,
supportedBrowsers: pluginOptions.supportedBrowsers,
}),
].filter(Boolean) as Plugin[];
function findAnalogFiles(config: ResolvedConfig) {
const analogConfig = pluginOptions.supportAnalogFormat;
if (!analogConfig) {
return [];
}
let extraGlobs: string[] = [];
if (typeof analogConfig === 'object') {
if (analogConfig.include) {
extraGlobs = analogConfig.include;
}
}
const fg = require('fast-glob');
const appRoot = normalizePath(
resolve(pluginOptions.workspaceRoot, config.root || '.')
);
const workspaceRoot = normalizePath(resolve(pluginOptions.workspaceRoot));
const globs = [
`${appRoot}/**/*.{analog,agx}`,
...extraGlobs.map((glob) => `${workspaceRoot}${glob}.{analog,agx}`),
...(pluginOptions.additionalContentDirs || [])?.map(
(glob) => `${workspaceRoot}${glob}/**/*.agx`
),
...pluginOptions.include.map((glob) =>
`${workspaceRoot}${glob}`.replace(/\.ts$/, '.analog')
),
];
return fg
.sync(globs, {
dot: true,
})
.map((file: string) => `${file}.ts`);
}
function findIncludes() {
const fg = require('fast-glob');
const workspaceRoot = normalizePath(resolve(pluginOptions.workspaceRoot));
const globs = [
...pluginOptions.include.map((glob) => `${workspaceRoot}${glob}`),
];
return fg.sync(globs, {
dot: true,
});
}
function setupCompilation(config: ResolvedConfig, context?: unknown) {
const analogFiles = findAnalogFiles(config);
const includeFiles = findIncludes();
const { options: tsCompilerOptions, rootNames: rn } =
compilerCli.readConfiguration(pluginOptions.tsconfig, {
suppressOutputPathCheck: true,
outDir: undefined,
sourceMap: false,
inlineSourceMap: !isProd,
inlineSources: !isProd,
declaration: false,
declarationMap: false,
allowEmptyCodegenFiles: false,
annotationsAs: 'decorators',
enableResourceInlining: false,
noEmitOnError: false,
mapRoot: undefined,
sourceRoot: undefined,
supportTestBed: false,
supportJitMode: false,
});
if (pluginOptions.supportAnalogFormat) {
// Experimental Local Compilation is necessary
// for the Angular compiler to work with
// AOT and virtually compiled .analog files.
tsCompilerOptions.compilationMode = 'experimental-local';
}
rootNames = rn.concat(analogFiles, includeFiles);
compilerOptions = tsCompilerOptions;
host = ts.createIncrementalCompilerHost(compilerOptions);
styleTransform = (code: string, filename: string) =>
preprocessCSS(code, filename, config as any);
if (!jit) {
augmentHostWithResources(host, styleTransform, {
inlineStylesExtension: pluginOptions.inlineStylesExtension,
supportAnalogFormat: pluginOptions.supportAnalogFormat,
isProd,
markdownTemplateTransforms: pluginOptions.markdownTemplateTransforms,
});
}
}
/**
* Creates a new NgtscProgram to analyze/re-analyze
* the source files and create a file emitter.
* This is shared between an initial build and a hot update.
*/
async function buildAndAnalyze() {
let builder:
| ts.BuilderProgram
| ts.EmitAndSemanticDiagnosticsBuilderProgram;
let typeScriptProgram: ts.Program;
let angularCompiler: NgtscProgram['compiler'];
if (!jit) {
// Create the Angular specific program that contains the Angular compiler
const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(
rootNames,
compilerOptions,
host as CompilerHost,
nextProgram as any
);
angularCompiler = angularProgram.compiler;
typeScriptProgram = angularProgram.getTsProgram();
augmentProgramWithVersioning(typeScriptProgram);
builder = builderProgram =
ts.createEmitAndSemanticDiagnosticsBuilderProgram(
typeScriptProgram,
host,
builderProgram
);
await angularCompiler.analyzeAsync();
nextProgram = angularProgram;
} else {
builder = builderProgram =
ts.createEmitAndSemanticDiagnosticsBuilderProgram(
rootNames,
compilerOptions,
host,
nextProgram as any
);
typeScriptProgram = builder.getProgram();
nextProgram = builderProgram as unknown as ts.Program;
}
if (!watchMode) {
// When not in watch mode, the startup cost of the incremental analysis can be avoided by
// using an abstract builder that only wraps a TypeScript program.
builder = ts.createAbstractBuilder(typeScriptProgram, host);
}
const getTypeChecker = () => builder.getProgram().getTypeChecker();
fileEmitter = createFileEmitter(
builder,
mergeTransformers(
{
before: [
replaceBootstrap(getTypeChecker),
...(jit
? [
compilerCli.constructorParametersDownlevelTransform(
builder.getProgram()
),
createJitResourceTransformer(getTypeChecker),
]
: []),
...pluginOptions.advanced.tsTransformers.before,
],
after: pluginOptions.advanced.tsTransformers.after,
afterDeclarations:
pluginOptions.advanced.tsTransformers.afterDeclarations,
},
jit ? {} : angularCompiler!.prepareEmit().transformers
),
() => [],
angularCompiler!
);
}
}
export function createFileEmitter(
program: ts.BuilderProgram,
transformers: ts.CustomTransformers = {},
onAfterEmit?: (sourceFile: ts.SourceFile) => void,
angularCompiler?: NgtscProgram['compiler']
): FileEmitter {
return async (file: string) => {
const sourceFile = program.getSourceFile(file);
if (!sourceFile) {
return undefined;
}
const diagnostics = angularCompiler
? angularCompiler.getDiagnosticsForFile(sourceFile, 1)
: [];
const errors = diagnostics
.filter((d) => d.category === ts.DiagnosticCategory?.Error)
.map((d) => d.messageText);
const warnings = diagnostics
.filter((d) => d.category === ts.DiagnosticCategory?.Warning)
.map((d) => d.messageText);
let content: string | undefined;
program.emit(
sourceFile,
(filename, data) => {
if (/\.[cm]?js$/.test(filename)) {
content = data;
}
},
undefined /* cancellationToken */,
undefined /* emitOnlyDtsFiles */,
transformers
);
onAfterEmit?.(sourceFile);
return { content, dependencies: [], errors, warnings };
};
}