@ngrs/vite 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrs/vite",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Native Rust Angular compiler & Ivy linker plugins for Vite, powered by @ngrs/compiler",
5
5
  "type": "module",
6
6
  "main": "./src/index.cjs",
@@ -23,7 +23,7 @@
23
23
  "src"
24
24
  ],
25
25
  "dependencies": {
26
- "@ngrs/compiler": "0.2.1"
26
+ "@ngrs/compiler": "0.3.0"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "happy-dom": ">=15.0.0 || ^20.0.0",
package/src/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { NapiDiagnostic, NapiFileReplacement } from '@ngrs/compiler';
1
+ import type { FileReplacement, NgrsDiagnostic } from '@ngrs/compiler';
2
2
  import type { Plugin } from 'vite';
3
3
 
4
4
  export interface AngularStylePreprocessorOptions {
@@ -32,7 +32,7 @@ export interface AngularVitePluginOptions {
32
32
  /**
33
33
  * File replacements (`angular.json` `fileReplacements` array).
34
34
  */
35
- fileReplacements?: NapiFileReplacement[];
35
+ fileReplacements?: FileReplacement[];
36
36
  /**
37
37
  * Enable Angular Hot Module Replacement (defaults to `true` in `serve`, `false` in `build`).
38
38
  */
@@ -72,13 +72,13 @@ export interface AngularVitePluginOptions {
72
72
  /**
73
73
  * Optional observer callback receiving compiler diagnostics after each build/rebuild.
74
74
  */
75
- onDiagnostics?: (diagnostics: NapiDiagnostic[]) => void;
75
+ onDiagnostics?: (diagnostics: NgrsDiagnostic[]) => void;
76
76
  /**
77
77
  * Optional observer callback receiving component stylesheet byte sizes (used for budget checks).
78
78
  */
79
79
  onComponentStylesCollected?: (styles: CollectedComponentStyle[]) => void;
80
80
  /**
81
- * Emit `.d.ts` declaration files in `NapiProjectCompiler` (defaults to `false` for bundler builds).
81
+ * Emit `.d.ts` declaration files in `NgrsProgram` (defaults to `false` for bundler builds).
82
82
  */
83
83
  emitDts?: boolean;
84
84
  /**
@@ -108,12 +108,12 @@ export interface AngularVitePluginOptions {
108
108
  export declare const isRolldownVite: boolean;
109
109
 
110
110
  export declare function formatDiagnostics(
111
- diagnostics: NapiDiagnostic[],
111
+ diagnostics: NgrsDiagnostic[],
112
112
  rootDir?: string,
113
113
  ): {
114
114
  warnings: string[];
115
115
  errors: string[];
116
- firstError?: NapiDiagnostic;
116
+ firstError?: NgrsDiagnostic;
117
117
  };
118
118
 
119
119
  export declare function createRolldownLinkerPlugin(options?: AngularLinkerOptions): {
package/src/index.mjs CHANGED
@@ -10,10 +10,11 @@ const require = createRequire(import.meta.url);
10
10
  const napi = require('@ngrs/compiler');
11
11
 
12
12
  const {
13
- NapiProjectCompiler,
13
+ NgrsProgram,
14
14
  needsLinking,
15
15
  linkFile,
16
16
  linkFileAsync,
17
+ linkFilesAsync,
17
18
  compileSassWithDeps,
18
19
  version: getCompilerVersion,
19
20
  } = napi;
@@ -21,10 +22,59 @@ const {
21
22
  const COMPILER_CACHE_VERSION =
22
23
  typeof getCompilerVersion === 'function' ? getCompilerVersion() : '0.2.0';
23
24
 
24
- const linkFileAsyncFn =
25
- typeof linkFileAsync === 'function'
26
- ? linkFileAsync
27
- : (filePath, source, opts) => Promise.resolve(linkFile(filePath, source, opts));
25
+ /**
26
+ * Coalesces concurrent `transform()` calls arriving within the same JS microtask tick into a single
27
+ * multi-core Rayon `linkFilesAsync` batch so all CPU cores link `@angular/*` bundles in parallel
28
+ * without being throttled by Node's 4-thread libuv pool.
29
+ */
30
+ const pendingLinkerBatches = new Map();
31
+
32
+ function enqueueLinkFileRayon(filePath, source, opts) {
33
+ if (typeof linkFilesAsync !== 'function') {
34
+ return typeof linkFileAsync === 'function'
35
+ ? linkFileAsync(filePath, source, opts)
36
+ : Promise.resolve(linkFile(filePath, source, opts));
37
+ }
38
+ const optsKey = `${opts?.sourceMapping ? 1 : 0}:${opts?.linkerJitMode ? 1 : 0}:${opts?.unknownDeclarationVersionHandling ?? ''}:${opts?.optimizeForBundling ? 1 : 0}`;
39
+ let batch = pendingLinkerBatches.get(optsKey);
40
+ if (!batch) {
41
+ batch = { opts, items: [] };
42
+ pendingLinkerBatches.set(optsKey, batch);
43
+ queueMicrotask(() => {
44
+ pendingLinkerBatches.delete(optsKey);
45
+ const items = batch.items;
46
+ if (items.length === 1) {
47
+ const single = items[0];
48
+ const p =
49
+ typeof linkFileAsync === 'function'
50
+ ? linkFileAsync(single.path, single.content, batch.opts)
51
+ : Promise.resolve(linkFile(single.path, single.content, batch.opts));
52
+ p.then(single.resolve, single.reject);
53
+ return;
54
+ }
55
+ linkFilesAsync(
56
+ items.map((it) => ({ path: it.path, content: it.content })),
57
+ batch.opts,
58
+ ).then(
59
+ (results) => {
60
+ for (let i = 0; i < items.length; i++) {
61
+ items[i].resolve(results[i]);
62
+ }
63
+ },
64
+ (err) => {
65
+ for (const it of items) {
66
+ it.reject(err);
67
+ }
68
+ },
69
+ );
70
+ });
71
+ }
72
+ return new Promise((resolve, reject) => {
73
+ batch.items.push({ path: filePath, content: source, resolve, reject });
74
+ });
75
+ }
76
+
77
+ const linkFileAsyncFn = enqueueLinkFileRayon;
28
78
 
29
79
  /**
30
80
  * True when running under Vite 8+ powered by native Rust Rolldown (`'rolldownVersion' in vite`).
@@ -380,9 +430,9 @@ async function compileSassResource(filePath, includePaths, sassOptions, workspac
380
430
  /**
381
431
  * Formats an array of `@ngrs/compiler` diagnostics into human-readable compiler messages.
382
432
  *
383
- * @param {import('@ngrs/compiler').NapiDiagnostic[]} diagnostics
433
+ * @param {import('@ngrs/compiler').NgrsDiagnostic[]} diagnostics
384
434
  * @param {string} [rootDir]
385
- * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NapiDiagnostic }}
435
+ * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NgrsDiagnostic }}
386
436
  */
387
437
  export function formatDiagnostics(diagnostics, rootDir = process.cwd()) {
388
438
  const warnings = [];
@@ -528,7 +578,7 @@ export function createEsbuildLinkerPlugin(options = {}) {
528
578
  * Plugin 1: `ngrs:angular-compiler`
529
579
  *
530
580
  * Stateful incremental Angular TypeScript + Ivy template/style compiler backed by
531
- * `NapiProjectCompiler` (`@ngrs/compiler`).
581
+ * `NgrsProgram` (`@ngrs/compiler`).
532
582
  *
533
583
  * @param {import('./index.js').AngularVitePluginOptions} [options]
534
584
  * @returns {import('vite').Plugin}
@@ -576,6 +626,13 @@ export function angularCompilerPlugin(options = {}) {
576
626
  /** @type {Map<string, string>} normalizedAbsFilePath -> last compiled disk contents */
577
627
  const fileContentSnapshots = new Map();
578
628
 
629
+ const initialIsTestMode = Boolean(options.test || process.env.VITEST);
630
+ const initialSkipResolveId =
631
+ Boolean(options._skipBuildTransform) &&
632
+ loadTsconfigPathMappings(
633
+ resolveDefaultTsconfig(workspaceRoot, options.tsconfig, initialIsTestMode),
634
+ ).length === 0;
635
+
579
636
  /** @type {Set<string>} clean paths already served via `load` during one-shot build */
580
637
  const servedViaLoad = new Set();
581
638
  let pendingDeferredTypecheck = false;
@@ -755,19 +812,26 @@ export function angularCompilerPlugin(options = {}) {
755
812
  continue;
756
813
  }
757
814
  const norm = toPosixPath(path.resolve(workspaceRoot, resPath));
758
- let cssText = compiledComponentStyleCss.get(norm);
759
- if (cssText === undefined) {
815
+ const cssText = compiledComponentStyleCss.get(norm);
816
+ if (cssText !== undefined) {
817
+ collected.push({
818
+ file: norm,
819
+ css: cssText,
820
+ size: Buffer.byteLength(cssText, 'utf8'),
821
+ });
822
+ } else {
823
+ let size = 0;
760
824
  try {
761
- cssText = fs.readFileSync(norm, 'utf8');
825
+ size = fs.statSync(norm).size;
762
826
  } catch {
763
- cssText = '';
827
+ size = 0;
764
828
  }
829
+ collected.push({
830
+ file: norm,
831
+ css: '',
832
+ size,
833
+ });
765
834
  }
766
- collected.push({
767
- file: norm,
768
- css: cssText,
769
- size: Buffer.byteLength(cssText, 'utf8'),
770
- });
771
835
  }
772
836
  options.onComponentStylesCollected(collected);
773
837
  }
@@ -1044,7 +1108,7 @@ export function angularCompilerPlugin(options = {}) {
1044
1108
  !isTestMode &&
1045
1109
  modeName !== 'experimental-local' &&
1046
1110
  (options.deferTypecheck ?? true) &&
1047
- typeof NapiProjectCompiler.prototype.finishDeferredTypecheckAsync === 'function';
1111
+ typeof NgrsProgram.prototype.finishDeferredTypecheckAsync === 'function';
1048
1112
 
1049
1113
  const hasCustomJsSass = Boolean(
1050
1114
  options.stylePreprocessorOptions?.sass?.functions !== undefined ||
@@ -1052,9 +1116,9 @@ export function angularCompilerPlugin(options = {}) {
1052
1116
  );
1053
1117
  const canUseNativeExternalSass =
1054
1118
  !hasCustomJsSass &&
1055
- typeof NapiProjectCompiler.prototype.getUncompiledExternalSassFiles === 'function';
1119
+ typeof NgrsProgram.prototype.getUncompiledExternalSassFiles === 'function';
1056
1120
 
1057
- compiler = NapiProjectCompiler.open(tsconfigPath, {
1121
+ compiler = NgrsProgram.open(tsconfigPath, {
1058
1122
  fileReplacements: normalizedReplacements,
1059
1123
  hmr: enableHmr,
1060
1124
  sourceMap: enableSourceMap,
@@ -1085,32 +1149,34 @@ export function angularCompilerPlugin(options = {}) {
1085
1149
  }
1086
1150
 
1087
1151
  if (canUseNativeExternalSass) {
1088
- for (const rawRes of allResources) {
1089
- if (!SASS_FILE_RE.test(rawRes)) continue;
1090
- const absRes = path.resolve(workspaceRoot, rawRes);
1091
- const normStylePath = toPosixPath(absRes);
1092
- const compiledCss = compiler.getCompiledStyleCss(absRes);
1093
- if (compiledCss !== null && compiledCss !== undefined) {
1094
- compiledComponentStyleCss.set(normStylePath, compiledCss);
1095
- }
1096
- const partials = compiler.getSassPartialsForStyle(absRes) || [];
1097
- const nextPartials = new Set();
1098
- for (const loaded of partials) {
1099
- const normLoaded = toPosixPath(loaded);
1100
- if (normLoaded !== normStylePath) {
1101
- nextPartials.add(normLoaded);
1102
- if (!oneShot) {
1103
- recordSnapshot(normLoaded);
1104
- }
1105
- let dependents = partialToComponentStyles.get(normLoaded);
1106
- if (!dependents) {
1107
- dependents = new Set();
1108
- partialToComponentStyles.set(normLoaded, dependents);
1152
+ if (!oneShot || typeof options.onComponentStylesCollected === 'function') {
1153
+ for (const rawRes of allResources) {
1154
+ if (!SASS_FILE_RE.test(rawRes)) continue;
1155
+ const absRes = path.resolve(workspaceRoot, rawRes);
1156
+ const normStylePath = toPosixPath(absRes);
1157
+ const compiledCss = compiler.getCompiledStyleCss(absRes);
1158
+ if (compiledCss !== null && compiledCss !== undefined) {
1159
+ compiledComponentStyleCss.set(normStylePath, compiledCss);
1160
+ }
1161
+ if (!oneShot) {
1162
+ const partials = compiler.getSassPartialsForStyle(absRes) || [];
1163
+ const nextPartials = new Set();
1164
+ for (const loaded of partials) {
1165
+ const normLoaded = toPosixPath(loaded);
1166
+ if (normLoaded !== normStylePath) {
1167
+ nextPartials.add(normLoaded);
1168
+ recordSnapshot(normLoaded);
1169
+ let dependents = partialToComponentStyles.get(normLoaded);
1170
+ if (!dependents) {
1171
+ dependents = new Set();
1172
+ partialToComponentStyles.set(normLoaded, dependents);
1173
+ }
1174
+ dependents.add(normStylePath);
1175
+ }
1109
1176
  }
1110
- dependents.add(normStylePath);
1177
+ componentStyleToPartials.set(normStylePath, nextPartials);
1111
1178
  }
1112
1179
  }
1113
- componentStyleToPartials.set(normStylePath, nextPartials);
1114
1180
  }
1115
1181
 
1116
1182
  const fallbackScss = compiler.getUncompiledExternalSassFiles();
@@ -1154,36 +1220,47 @@ export function angularCompilerPlugin(options = {}) {
1154
1220
  }
1155
1221
  },
1156
1222
 
1157
- resolveId(source) {
1158
- if (
1159
- !tsconfigPathMappings.length ||
1160
- !source ||
1161
- source.startsWith('.') ||
1162
- source.startsWith('/') ||
1163
- source.startsWith('\0')
1164
- ) {
1165
- return null;
1166
- }
1167
- if (tsconfigResolveCache.has(source)) {
1168
- return tsconfigResolveCache.get(source);
1169
- }
1170
- let mayMatch = tsconfigExactPatterns.has(source);
1171
- if (!mayMatch) {
1172
- for (let i = 0; i < tsconfigWildcardPrefixes.length; i++) {
1173
- if (source.startsWith(tsconfigWildcardPrefixes[i])) {
1174
- mayMatch = true;
1175
- break;
1176
- }
1177
- }
1178
- }
1179
- if (!mayMatch) {
1180
- tsconfigResolveCache.set(source, null);
1181
- return null;
1182
- }
1183
- const resolved = resolveViaTsconfigPaths(source, tsconfigPathMappings);
1184
- tsconfigResolveCache.set(source, resolved);
1185
- return resolved;
1186
- },
1223
+ ...(initialSkipResolveId
1224
+ ? {}
1225
+ : {
1226
+ resolveId: {
1227
+ filter: {
1228
+ id: {
1229
+ exclude: /^(?:\.\.?\/|\/|\0)/,
1230
+ },
1231
+ },
1232
+ handler(source) {
1233
+ if (
1234
+ !tsconfigPathMappings.length ||
1235
+ !source ||
1236
+ source.startsWith('.') ||
1237
+ source.startsWith('/') ||
1238
+ source.startsWith('\0')
1239
+ ) {
1240
+ return null;
1241
+ }
1242
+ if (tsconfigResolveCache.has(source)) {
1243
+ return tsconfigResolveCache.get(source);
1244
+ }
1245
+ let mayMatch = tsconfigExactPatterns.has(source);
1246
+ if (!mayMatch) {
1247
+ for (let i = 0; i < tsconfigWildcardPrefixes.length; i++) {
1248
+ if (source.startsWith(tsconfigWildcardPrefixes[i])) {
1249
+ mayMatch = true;
1250
+ break;
1251
+ }
1252
+ }
1253
+ }
1254
+ if (!mayMatch) {
1255
+ tsconfigResolveCache.set(source, null);
1256
+ return null;
1257
+ }
1258
+ const resolved = resolveViaTsconfigPaths(source, tsconfigPathMappings);
1259
+ tsconfigResolveCache.set(source, resolved);
1260
+ return resolved;
1261
+ },
1262
+ },
1263
+ }),
1187
1264
 
1188
1265
  load: {
1189
1266
  filter: {
@@ -1218,63 +1295,67 @@ export function angularCompilerPlugin(options = {}) {
1218
1295
  },
1219
1296
  },
1220
1297
 
1221
- transform: {
1222
- filter: {
1223
- id: {
1224
- include: TS_FILE_RE,
1225
- exclude: [/\/node_modules\//, DTS_FILE_RE],
1226
- },
1227
- },
1228
- async handler(_code, id) {
1229
- if (!compiler || id.startsWith('\0')) {
1230
- return null;
1231
- }
1232
- const query = getQueryString(id);
1233
- if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1234
- return null;
1235
- }
1236
- const cleanId = stripQueryAndHash(id);
1237
- if (servedViaLoad.has(cleanId)) {
1238
- return null;
1239
- }
1240
- const posixId = toPosixPath(cleanId);
1241
- if (
1242
- posixId.includes('/node_modules/') ||
1243
- DTS_FILE_RE.test(posixId) ||
1244
- !TS_FILE_RE.test(posixId)
1245
- ) {
1246
- return null;
1247
- }
1298
+ ...(options._skipBuildTransform
1299
+ ? {}
1300
+ : {
1301
+ transform: {
1302
+ filter: {
1303
+ id: {
1304
+ include: TS_FILE_RE,
1305
+ exclude: [/\/node_modules\//, DTS_FILE_RE],
1306
+ },
1307
+ },
1308
+ async handler(_code, id) {
1309
+ if (!compiler || id.startsWith('\0')) {
1310
+ return null;
1311
+ }
1312
+ const query = getQueryString(id);
1313
+ if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1314
+ return null;
1315
+ }
1316
+ const cleanId = stripQueryAndHash(id);
1317
+ if (servedViaLoad.has(cleanId)) {
1318
+ return null;
1319
+ }
1320
+ const posixId = toPosixPath(cleanId);
1321
+ if (
1322
+ posixId.includes('/node_modules/') ||
1323
+ DTS_FILE_RE.test(posixId) ||
1324
+ !TS_FILE_RE.test(posixId)
1325
+ ) {
1326
+ return null;
1327
+ }
1248
1328
 
1249
- if (resolvedConfig?.command === 'serve') {
1250
- await syncOnDiskChangesForTs(cleanId, null);
1251
- }
1329
+ if (resolvedConfig?.command === 'serve') {
1330
+ await syncOnDiskChangesForTs(cleanId, null);
1331
+ }
1252
1332
 
1253
- const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1254
- if (!modOut) {
1255
- return null;
1256
- }
1333
+ const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1334
+ if (!modOut) {
1335
+ return null;
1336
+ }
1257
1337
 
1258
- if (!isOneShotBuild()) {
1259
- recordSnapshot(cleanId);
1260
- const resourceDeps = compiler.getResourceDependencies(cleanId);
1261
- for (const dep of resourceDeps) {
1262
- recordSnapshot(dep);
1263
- this.addWatchFile(dep);
1264
- const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1265
- const partials = componentStyleToPartials.get(normDep);
1266
- if (partials) {
1267
- for (const partialPath of partials) {
1268
- recordSnapshot(partialPath);
1269
- this.addWatchFile(partialPath);
1338
+ if (!isOneShotBuild()) {
1339
+ recordSnapshot(cleanId);
1340
+ const resourceDeps = compiler.getResourceDependencies(cleanId);
1341
+ for (const dep of resourceDeps) {
1342
+ recordSnapshot(dep);
1343
+ this.addWatchFile(dep);
1344
+ const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1345
+ const partials = componentStyleToPartials.get(normDep);
1346
+ if (partials) {
1347
+ for (const partialPath of partials) {
1348
+ recordSnapshot(partialPath);
1349
+ this.addWatchFile(partialPath);
1350
+ }
1351
+ }
1352
+ }
1270
1353
  }
1271
- }
1272
- }
1273
- }
1274
1354
 
1275
- return modOut;
1276
- },
1277
- },
1355
+ return modOut;
1356
+ },
1357
+ },
1358
+ }),
1278
1359
 
1279
1360
  async handleHotUpdate(ctx) {
1280
1361
  if (!compiler) {
@@ -1565,6 +1646,11 @@ export function angularLinkerPlugin(options = {}) {
1565
1646
  transform: {
1566
1647
  filter: {
1567
1648
  id: /\.[cm]?js(?:$|\?)/,
1649
+ ...(isRolldownVite
1650
+ ? {
1651
+ code: /(?:ngDeclare|setClassMetadata|setClassDebugInfo|static\s+ɵ|InjectionToken|\\u0275)/,
1652
+ }
1653
+ : {}),
1568
1654
  },
1569
1655
  async handler(code, id) {
1570
1656
  if (id.startsWith('\0')) {
package/src/testing.mjs CHANGED
@@ -165,7 +165,7 @@ if (!globalThis[ANGULAR_TESTBED_SETUP]) {
165
165
  /**
166
166
  * First-class Vitest plugin for Angular (`@ngrs/vite/testing`).
167
167
  * Configures Angular `TestBed` (`BrowserTestingModule` + `happy-dom` + zoneless / `zone.js/testing`),
168
- * compiles `*.spec.ts` + components/templates/SCSS via native Rust `NapiProjectCompiler`, and links
168
+ * compiles `*.spec.ts` + components/templates/SCSS via native Rust `NgrsProgram`, and links
169
169
  * all Partial-Ivy `node_modules` packages via native Rust Ivy Linker.
170
170
  *
171
171
  * @param {import('./testing.js').AngularTestingPluginOptions} [options]