@ngrs/build 0.0.0-stage → 0.1.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/src/index.d.ts ADDED
@@ -0,0 +1,158 @@
1
+ import type { ViteDevServer } from 'vite';
2
+ import type {
3
+ BudgetEntry,
4
+ NormalizedApplicationOptions,
5
+ NormalizedDevServerOptions,
6
+ } from './workspace.mjs';
7
+
8
+ export * from './workspace.mjs';
9
+
10
+ export declare const BuilderSymbol: unique symbol;
11
+ export declare const BuilderVersionSymbol: unique symbol;
12
+
13
+ export interface BuilderOutput {
14
+ success: boolean;
15
+ error?: string;
16
+ [key: string]: unknown;
17
+ }
18
+
19
+ export interface ApplicationBuildOutput extends BuilderOutput {
20
+ outputPath: string;
21
+ browserOutputPath: string;
22
+ stats?: {
23
+ chunks: Array<{ files: string[]; names: string[]; initial: boolean }>;
24
+ assets: Array<{ name: string; size: number; componentStyle?: boolean }>;
25
+ initialTotalBytes: number;
26
+ };
27
+ budgetResults?: BudgetCalculatorResult[];
28
+ }
29
+
30
+ export interface DevServerBuilderOutput extends BuilderOutput {
31
+ port: number;
32
+ baseUrl: string;
33
+ server?: ViteDevServer;
34
+ close?: () => Promise<void>;
35
+ }
36
+
37
+ export interface BudgetCalculatorResult {
38
+ severity: 'warning' | 'error';
39
+ label?: string;
40
+ message: string;
41
+ }
42
+
43
+ export declare function createBuilder<OptT = Record<string, any>, OutT = BuilderOutput>(
44
+ handlerFn: (options: OptT, context: any) => AsyncIterable<OutT> | Promise<OutT> | OutT,
45
+ ): any;
46
+
47
+ export declare function createConsoleLogger(verbose?: boolean): Record<string, any>;
48
+ export declare function createWorkspaceBuilderContext(options: {
49
+ workspaceRoot: string;
50
+ workspace: Record<string, any>;
51
+ target?: { project: string; target: string; configuration?: string };
52
+ builderName?: string;
53
+ logger?: Record<string, any>;
54
+ }): any;
55
+
56
+ export declare function formatSize(bytes: number): string;
57
+ export declare function calculateBytes(
58
+ input: string,
59
+ baseline?: string,
60
+ factor?: 1 | -1,
61
+ ): number;
62
+ export declare function checkBudgets(
63
+ budgets: BudgetEntry[],
64
+ stats: {
65
+ chunks?: Array<{ files?: string[]; names?: string[]; initial?: boolean }>;
66
+ assets?: Array<{ name: string; size: number; componentStyle?: boolean }>;
67
+ },
68
+ ): BudgetCalculatorResult[];
69
+
70
+ export declare function transformIndexHtmlContent(params: {
71
+ html: string;
72
+ baseHref?: string;
73
+ deployUrl?: string;
74
+ crossOrigin?: 'none' | 'anonymous' | 'use-credentials';
75
+ sri?: boolean;
76
+ styles?: Array<{ href: string; content?: string }>;
77
+ scripts?: Array<{ src: string; isModule?: boolean; defer?: boolean; content?: string }>;
78
+ }): string;
79
+
80
+ export declare function loadProxyConfiguration(
81
+ workspaceRoot: string,
82
+ proxyConfig?: string,
83
+ ): Promise<Record<string, object> | undefined>;
84
+
85
+ export declare function normalizeProxyConfiguration(
86
+ rawProxy: Record<string, object> | object[],
87
+ ): Record<string, object>;
88
+
89
+ export declare function makeUrlRegExpFromGlob(globPattern: string): string;
90
+
91
+ export declare function executeApplicationBuild(
92
+ appOptions: NormalizedApplicationOptions,
93
+ logger?: Record<string, any>,
94
+ extensions?: Record<string, any>,
95
+ ): Promise<ApplicationBuildOutput>;
96
+
97
+ export declare function buildApplication(
98
+ options?: Record<string, any>,
99
+ context?: any,
100
+ extensions?: Record<string, any>,
101
+ ): AsyncGenerator<ApplicationBuildOutput>;
102
+
103
+ export declare function startDevServer(
104
+ serveOptions: NormalizedDevServerOptions,
105
+ appOptions: NormalizedApplicationOptions,
106
+ logger?: Record<string, any>,
107
+ extensions?: Record<string, any>,
108
+ ): Promise<{ server: ViteDevServer; port: number; baseUrl: string }>;
109
+
110
+ export declare function executeDevServerBuilder(
111
+ options?: Record<string, any>,
112
+ context?: any,
113
+ extensions?: Record<string, any>,
114
+ ): AsyncGenerator<DevServerBuilderOutput>;
115
+
116
+ export declare function serveApplication(
117
+ options?: Record<string, any>,
118
+ context?: any,
119
+ extensions?: Record<string, any>,
120
+ ): AsyncGenerator<DevServerBuilderOutput>;
121
+
122
+ export declare function executeExtractI18nBuilder(
123
+ options: Record<string, any>,
124
+ context: any,
125
+ ): Promise<{ success: boolean; outputFiles: string[] }>;
126
+
127
+ export declare const applicationBuilder: any;
128
+ export declare const devServerBuilder: any;
129
+ export declare const extractI18nBuilder: any;
130
+ export declare const unitTestBuilder: any;
131
+ export declare function executeUnitTestBuilder(
132
+ options?: Record<string, any>,
133
+ context?: any,
134
+ ): AsyncGenerator<BuilderOutput>;
135
+
136
+ export declare const BUILDER_MIGRATIONS: Readonly<Record<string, string>>;
137
+ export declare function migrateWorkspaceJsoncText(
138
+ rawText: string,
139
+ options?: { project?: string },
140
+ ): {
141
+ updatedText: string;
142
+ changed: boolean;
143
+ updates: Array<{ project: string; target: string; from: string; to: string }>;
144
+ alreadyConfiguredCount: number;
145
+ };
146
+ export declare function ngAdd(options?: { project?: string }): (tree: any, context?: any) => any;
147
+ export declare function initWorkspaceWithNgrsBuild(options?: {
148
+ workspaceRoot?: string;
149
+ project?: string;
150
+ dryRun?: boolean;
151
+ logger?: Record<string, any>;
152
+ }): Promise<{
153
+ workspaceFile: string;
154
+ updatedText: string;
155
+ changed: boolean;
156
+ updates: Array<{ project: string; target: string; from: string; to: string }>;
157
+ alreadyConfiguredCount: number;
158
+ }>;
package/src/index.mjs ADDED
@@ -0,0 +1,71 @@
1
+ export {
2
+ BuilderSymbol,
3
+ BuilderVersionSymbol,
4
+ createBuilder,
5
+ createConsoleLogger,
6
+ createWorkspaceBuilderContext,
7
+ } from './architect-compat.mjs';
8
+ export {
9
+ BYTES_IN_KILOBYTE,
10
+ calculateBytes,
11
+ checkBudgets,
12
+ formatSize,
13
+ } from './budgets.mjs';
14
+ export {
15
+ ansiColors,
16
+ calculateEstimatedTransferSizes,
17
+ formatBuildMessage,
18
+ generateEsbuildBuildStatsTable,
19
+ getEntryPointName,
20
+ resolveColorsOption,
21
+ supportColor,
22
+ withProgress,
23
+ } from './stats-table.mjs';
24
+ export { transformIndexHtmlContent } from './index-html.mjs';
25
+ export {
26
+ loadProxyConfiguration,
27
+ makeUrlRegExpFromGlob,
28
+ normalizeProxyConfiguration,
29
+ } from './proxy.mjs';
30
+ export {
31
+ findWorkspaceFile,
32
+ isSubDirectory,
33
+ loadWorkspace,
34
+ normalizeApplicationOptions,
35
+ normalizeAssetPatterns,
36
+ normalizeDevServerOptions,
37
+ normalizeGlobalEntries,
38
+ normalizeOptimization,
39
+ normalizeSourceMaps,
40
+ parseTargetString,
41
+ resolveAssets,
42
+ resolveProjectName,
43
+ resolveTargetOptions,
44
+ toPosixPath,
45
+ } from './workspace.mjs';
46
+ export {
47
+ applicationBuilder,
48
+ buildApplication,
49
+ executeApplicationBuild,
50
+ } from './builders/application/index.mjs';
51
+ export {
52
+ devServerBuilder,
53
+ executeDevServer,
54
+ executeDevServerBuilder,
55
+ serveApplication,
56
+ startDevServer,
57
+ } from './builders/dev-server/index.mjs';
58
+ export {
59
+ executeExtractI18nBuilder,
60
+ extractI18nBuilder,
61
+ } from './builders/extract-i18n/index.mjs';
62
+ export {
63
+ executeUnitTestBuilder,
64
+ unitTestBuilder,
65
+ } from './builders/unit-test/index.mjs';
66
+ export {
67
+ BUILDER_MIGRATIONS,
68
+ initWorkspaceWithNgrsBuild,
69
+ migrateWorkspaceJsoncText,
70
+ ngAdd,
71
+ } from './ng-add.mjs';
package/src/ng-add.mjs ADDED
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { findWorkspaceFile } from './workspace.mjs';
5
+
6
+ const localRequire = createRequire(import.meta.url);
7
+ const {
8
+ BUILDER_MIGRATIONS,
9
+ HAPPY_DOM_VERSION,
10
+ migratePackageJsonForHappyDom,
11
+ migrateWorkspaceJsoncText,
12
+ ngAdd,
13
+ } = localRequire('../schematics/ng-add/index.cjs');
14
+
15
+ export {
16
+ BUILDER_MIGRATIONS,
17
+ HAPPY_DOM_VERSION,
18
+ migratePackageJsonForHappyDom,
19
+ migrateWorkspaceJsoncText,
20
+ ngAdd,
21
+ };
22
+
23
+ /**
24
+ * Configures an Angular workspace (`angular.json` / `workspace.json` + `package.json`) on disk to
25
+ * use `@ngrs/build` and `happy-dom`.
26
+ * Shared by `ngrs init` / `ngrs-build init` and programmatic callers.
27
+ *
28
+ * @param {{ workspaceRoot?: string, project?: string, dryRun?: boolean, logger?: object }} [options]
29
+ */
30
+ export async function initWorkspaceWithNgrsBuild(options = {}) {
31
+ const startDir = options.workspaceRoot || process.cwd();
32
+ const workspaceFile = findWorkspaceFile(startDir);
33
+ if (!workspaceFile) {
34
+ throw new Error(
35
+ `Could not find an Angular workspace file ('angular.json' or 'workspace.json') starting from "${path.resolve(startDir)}".`,
36
+ );
37
+ }
38
+
39
+ const rawText = await fs.readFile(workspaceFile, 'utf8');
40
+ const result = migrateWorkspaceJsoncText(rawText, { project: options.project });
41
+
42
+ if (result.changed && !options.dryRun) {
43
+ await fs.writeFile(workspaceFile, result.updatedText, 'utf8');
44
+ }
45
+
46
+ const pkgFile = path.join(path.dirname(workspaceFile), 'package.json');
47
+ let packageJsonUpdated = false;
48
+ try {
49
+ const rawPkg = await fs.readFile(pkgFile, 'utf8');
50
+ const pkgRes = migratePackageJsonForHappyDom(rawPkg);
51
+ if (pkgRes.changed) {
52
+ packageJsonUpdated = true;
53
+ if (!options.dryRun) {
54
+ await fs.writeFile(pkgFile, pkgRes.updatedText, 'utf8');
55
+ }
56
+ if (pkgRes.removedJsdom) {
57
+ options.logger?.info?.('Removed legacy jsdom dependency from package.json');
58
+ }
59
+ if (pkgRes.addedHappyDom) {
60
+ options.logger?.info?.(`Added happy-dom (${HAPPY_DOM_VERSION}) to devDependencies`);
61
+ }
62
+ }
63
+ } catch {
64
+ // Optional package.json in synthetic fixtures
65
+ }
66
+
67
+ const relFile = path.relative(process.cwd(), workspaceFile) || path.basename(workspaceFile);
68
+ if (result.changed) {
69
+ for (const item of result.updates) {
70
+ options.logger?.info?.(
71
+ `Configured ${item.project}:${item.target} builder (${item.from} -> ${item.to})`,
72
+ );
73
+ }
74
+ options.logger?.info?.(
75
+ options.dryRun
76
+ ? `[dry-run] Would update ${relFile}`
77
+ : `UPDATE ${relFile} (${Buffer.byteLength(result.updatedText, 'utf8')} bytes)`,
78
+ );
79
+ } else if (result.alreadyConfiguredCount > 0) {
80
+ options.logger?.info?.('Workspace targets are already configured to use @ngrs/build.');
81
+ } else {
82
+ options.logger?.warn?.(
83
+ 'No compatible Angular application build/serve targets were found to update.',
84
+ );
85
+ }
86
+
87
+ return {
88
+ workspaceFile,
89
+ packageJsonUpdated,
90
+ ...result,
91
+ };
92
+ }
package/src/proxy.mjs ADDED
@@ -0,0 +1,136 @@
1
+ import fs from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
7
+ import picomatch from 'picomatch';
8
+
9
+ function isDynamicGlob(pattern) {
10
+ return /[*?[\]{}()]/.test(pattern);
11
+ }
12
+
13
+ /**
14
+ * Converts a glob pattern to a regex source string matching URL pathnames while permitting optional
15
+ * query strings (1:1 port of `@angular/build/src/utils/load-proxy-config.ts`).
16
+ */
17
+ export function makeUrlRegExpFromGlob(globPattern) {
18
+ const { source } = picomatch.makeRe(globPattern);
19
+ return source
20
+ .replaceAll('(?=.)', '(?=[^?])')
21
+ .replaceAll('[^/]', '[^/?]')
22
+ .replaceAll('[^.\\/]', '[^.\\/?]')
23
+ .replaceAll('\\.).)*?', '\\.)[^?])*?')
24
+ .replace(/(?<!\\)\$/g, '(?:\\?.*)?$');
25
+ }
26
+
27
+ function pathRewriter(pathRewriteEntries, reqPath) {
28
+ for (const [pattern, replacement] of pathRewriteEntries) {
29
+ const updated = reqPath.replace(pattern, replacement);
30
+ if (reqPath !== updated) {
31
+ return updated;
32
+ }
33
+ }
34
+ return reqPath;
35
+ }
36
+
37
+ /**
38
+ * Normalizes Angular/Webpack object or array proxy configurations into Vite's `server.proxy` map.
39
+ */
40
+ export function normalizeProxyConfiguration(rawProxy) {
41
+ let proxyMap = {};
42
+
43
+ if (Array.isArray(rawProxy)) {
44
+ for (const entry of rawProxy) {
45
+ if (!entry || typeof entry !== 'object' || !('context' in entry)) {
46
+ continue;
47
+ }
48
+ const contexts =
49
+ typeof entry.context === 'string'
50
+ ? [entry.context]
51
+ : Array.isArray(entry.context)
52
+ ? entry.context
53
+ : [];
54
+ const cloned = { ...entry };
55
+ delete cloned.context;
56
+ for (const ctx of contexts) {
57
+ if (typeof ctx === 'string') {
58
+ proxyMap[ctx] = { ...cloned };
59
+ }
60
+ }
61
+ }
62
+ } else if (rawProxy && typeof rawProxy === 'object') {
63
+ for (const [k, v] of Object.entries(rawProxy)) {
64
+ proxyMap[k] = typeof v === 'object' && v !== null ? { ...v } : v;
65
+ }
66
+ }
67
+
68
+ const orderedProxy = {};
69
+ for (const [key, value] of Object.entries(proxyMap)) {
70
+ const contextKey =
71
+ key[0] !== '^' && isDynamicGlob(key) ? makeUrlRegExpFromGlob(key) : key;
72
+ orderedProxy[contextKey] = value;
73
+ }
74
+
75
+ for (const entry of Object.values(orderedProxy)) {
76
+ if (
77
+ entry &&
78
+ typeof entry === 'object' &&
79
+ entry.pathRewrite &&
80
+ typeof entry.pathRewrite === 'object'
81
+ ) {
82
+ const rewritePairs = Object.entries(entry.pathRewrite).map(([pat, val]) => [
83
+ new RegExp(pat),
84
+ String(val),
85
+ ]);
86
+ entry.rewrite = pathRewriter.bind(undefined, rewritePairs);
87
+ delete entry.pathRewrite;
88
+ }
89
+ }
90
+
91
+ return orderedProxy;
92
+ }
93
+
94
+ /**
95
+ * Loads `.json` (JSONC), `.js`, `.cjs`, or `.mjs` Angular proxy configuration files and converts
96
+ * them into Vite `server.proxy` format.
97
+ */
98
+ export async function loadProxyConfiguration(workspaceRoot, proxyConfig) {
99
+ if (!proxyConfig) {
100
+ return undefined;
101
+ }
102
+
103
+ const proxyPath = path.resolve(workspaceRoot, proxyConfig);
104
+ if (!fs.existsSync(proxyPath)) {
105
+ throw new Error(`Proxy configuration file ${proxyPath} does not exist.`);
106
+ }
107
+
108
+ const ext = path.extname(proxyPath).toLowerCase();
109
+ let loaded;
110
+
111
+ if (ext === '.json') {
112
+ const content = await readFile(proxyPath, 'utf8');
113
+ const parseErrors = [];
114
+ loaded = parseJsonc(content, parseErrors, { allowTrailingComma: true });
115
+ if (parseErrors.length > 0) {
116
+ const details = parseErrors
117
+ .map((e) => `${printParseErrorCode(e.error)} at offset ${e.offset}`)
118
+ .join(', ');
119
+ throw new Error(`Proxy configuration file ${proxyPath} contains parse errors: ${details}`);
120
+ }
121
+ } else if (ext === '.cjs') {
122
+ const req = createRequire(import.meta.url);
123
+ loaded = req(proxyPath);
124
+ } else {
125
+ loaded = await import(pathToFileURL(proxyPath).href);
126
+ }
127
+
128
+ if (loaded && typeof loaded === 'object' && 'default' in loaded) {
129
+ loaded = loaded.default;
130
+ }
131
+ if (typeof loaded === 'function') {
132
+ loaded = await loaded();
133
+ }
134
+
135
+ return normalizeProxyConfiguration(loaded);
136
+ }