@egen-civitas/egen 1.0.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.
Files changed (75) hide show
  1. package/README.md +71 -0
  2. package/bin/rspack.cjs +9 -0
  3. package/bin/webpack.cjs +6 -0
  4. package/default-rspack-config.cjs +3 -0
  5. package/default-webpack-config.cjs +3 -0
  6. package/dist/cli.d.ts +4 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +266 -0
  9. package/dist/commands/assemble.d.ts +13 -0
  10. package/dist/commands/assemble.d.ts.map +1 -0
  11. package/dist/commands/assemble.js +225 -0
  12. package/dist/commands/build.d.ts +32 -0
  13. package/dist/commands/build.d.ts.map +1 -0
  14. package/dist/commands/build.js +86 -0
  15. package/dist/commands/debug.d.ts +14 -0
  16. package/dist/commands/debug.d.ts.map +1 -0
  17. package/dist/commands/debug.js +37 -0
  18. package/dist/commands/develop.d.ts +18 -0
  19. package/dist/commands/develop.d.ts.map +1 -0
  20. package/dist/commands/develop.js +135 -0
  21. package/dist/commands/index.d.ts +5 -0
  22. package/dist/commands/index.d.ts.map +1 -0
  23. package/dist/commands/index.js +4 -0
  24. package/dist/commands/start.d.ts +9 -0
  25. package/dist/commands/start.d.ts.map +1 -0
  26. package/dist/commands/start.js +44 -0
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +2 -0
  30. package/dist/runner.d.ts +2 -0
  31. package/dist/runner.d.ts.map +1 -0
  32. package/dist/runner.js +14 -0
  33. package/dist/utils/config.d.ts +24 -0
  34. package/dist/utils/config.d.ts.map +1 -0
  35. package/dist/utils/config.js +75 -0
  36. package/dist/utils/debugger.d.ts +2 -0
  37. package/dist/utils/debugger.d.ts.map +1 -0
  38. package/dist/utils/debugger.js +66 -0
  39. package/dist/utils/dependencies.d.ts +9 -0
  40. package/dist/utils/dependencies.d.ts.map +1 -0
  41. package/dist/utils/dependencies.js +37 -0
  42. package/dist/utils/devserver.d.ts +5 -0
  43. package/dist/utils/devserver.d.ts.map +1 -0
  44. package/dist/utils/devserver.js +30 -0
  45. package/dist/utils/helpers.d.ts +4 -0
  46. package/dist/utils/helpers.d.ts.map +1 -0
  47. package/dist/utils/helpers.js +16 -0
  48. package/dist/utils/importmap.d.ts +53 -0
  49. package/dist/utils/importmap.d.ts.map +1 -0
  50. package/dist/utils/importmap.js +312 -0
  51. package/dist/utils/index.d.ts +10 -0
  52. package/dist/utils/index.d.ts.map +1 -0
  53. package/dist/utils/index.js +9 -0
  54. package/dist/utils/logger.d.ts +4 -0
  55. package/dist/utils/logger.d.ts.map +1 -0
  56. package/dist/utils/logger.js +10 -0
  57. package/dist/utils/npmConfig.d.ts +14 -0
  58. package/dist/utils/npmConfig.d.ts.map +1 -0
  59. package/dist/utils/npmConfig.js +39 -0
  60. package/dist/utils/packages.d.ts +15 -0
  61. package/dist/utils/packages.d.ts.map +1 -0
  62. package/dist/utils/packages.js +92 -0
  63. package/dist/utils/port.d.ts +15 -0
  64. package/dist/utils/port.d.ts.map +1 -0
  65. package/dist/utils/port.js +44 -0
  66. package/dist/utils/types.d.ts +16 -0
  67. package/dist/utils/types.d.ts.map +1 -0
  68. package/dist/utils/types.js +1 -0
  69. package/dist/utils/untar.d.ts +5 -0
  70. package/dist/utils/untar.d.ts.map +1 -0
  71. package/dist/utils/untar.js +14 -0
  72. package/dist/utils/variables.d.ts +2 -0
  73. package/dist/utils/variables.d.ts.map +1 -0
  74. package/dist/utils/variables.js +5 -0
  75. package/package.json +116 -0
@@ -0,0 +1,30 @@
1
+ import { resolve } from "path";
2
+ import { fork } from "child_process";
3
+ export function startDevServer(source, port, cwd = process.cwd(), useRspack = false) {
4
+ const runner = resolve(import.meta.dirname, 'debugger.js');
5
+ const ps = fork(runner, [], {
6
+ cwd
7
+ });
8
+ ps.send({
9
+ source,
10
+ port,
11
+ useRspack
12
+ });
13
+ const ready = new Promise((resolve, reject)=>{
14
+ ps.on('message', (msg)=>{
15
+ if (msg.type === 'compilation-complete') {
16
+ resolve();
17
+ }
18
+ });
19
+ ps.on('error', reject);
20
+ ps.on('exit', (code)=>{
21
+ if (code !== 0) {
22
+ reject(new Error(`Dev server process exited with code ${code}`));
23
+ }
24
+ });
25
+ });
26
+ return {
27
+ process: ps,
28
+ ready
29
+ };
30
+ }
@@ -0,0 +1,4 @@
1
+ export declare function trimEnd(text: string, chr: string): string;
2
+ export declare function removeTrailingSlash(path: string): string;
3
+ export declare function contentHash(obj: object): string;
4
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/utils/helpers.ts"],"names":[],"mappings":"AAEA,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAKzD;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGxD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,UAItC"}
@@ -0,0 +1,16 @@
1
+ import { util } from "@rspack/core";
2
+ export function trimEnd(text, chr) {
3
+ while(text.endsWith(chr)){
4
+ text = text.slice(0, text.length - chr.length);
5
+ }
6
+ return text;
7
+ }
8
+ export function removeTrailingSlash(path) {
9
+ const i = path.length - 1;
10
+ return path[i] === '/' ? removeTrailingSlash(path.slice(0, i)) : path;
11
+ }
12
+ export function contentHash(obj) {
13
+ const hash = util.createHash('xxhash64');
14
+ hash.update(JSON.stringify(obj), 'UTF-8');
15
+ return hash.digest().toString('hex');
16
+ }
@@ -0,0 +1,53 @@
1
+ export interface ImportmapDeclaration {
2
+ type: 'inline' | 'url';
3
+ value: string;
4
+ }
5
+ export interface RoutesDeclaration {
6
+ type: 'inline' | 'url';
7
+ value: string;
8
+ }
9
+ export interface ImportmapAndRoutes {
10
+ importMap: ImportmapDeclaration;
11
+ routes: RoutesDeclaration;
12
+ }
13
+ export interface ImportmapAndRoutesWithWatches extends ImportmapAndRoutes {
14
+ importMap: ImportmapDeclaration;
15
+ routes: RoutesDeclaration;
16
+ watchedRoutesPaths: Record<string, string>;
17
+ }
18
+ export declare function checkImportmapJson(value: string): boolean;
19
+ export declare function checkRoutesJson(value: string): boolean;
20
+ export declare function runProject(basePort: number, sourceDirectoryPatterns: Array<string>, useRspack?: boolean): Promise<{
21
+ importMap: Record<string, string>;
22
+ routes: Record<string, unknown>;
23
+ watchedRoutesPaths: Record<string, string>;
24
+ }>;
25
+ /**
26
+ * @param importAndRoutes An ImportmapAndRoutes object that holds the current import map and routes registries
27
+ * @param additionalImportsAndRoutes An object containing any import map entries, routes, and watched route files to add to the setup
28
+ * @param backend The URL for the backend
29
+ * @param spaPath The spaPath for this instance
30
+ * @returns The import map declaration with the new imports added in. If
31
+ * there are new imports to add, and if the original import map declaration
32
+ * had type "url", it is downloaded and resolved to one of type "inline".
33
+ */
34
+ export declare function mergeImportmapAndRoutes(importAndRoutes: ImportmapAndRoutes, additionalImportsAndRoutes: {
35
+ importMap: Record<string, string>;
36
+ routes: Record<string, unknown>;
37
+ watchedRoutesPaths: Record<string, string>;
38
+ } | false, backend?: string, spaPath?: string): Promise<ImportmapAndRoutesWithWatches>;
39
+ export declare function getImportmapAndRoutes(importMapPath: string, routesPath: string, basePort?: number): Promise<ImportmapAndRoutes>;
40
+ export declare function getImportMap(importMapPath: string, basePort?: number): Promise<ImportmapDeclaration>;
41
+ export declare function getRoutes(routesPath: string): Promise<RoutesDeclaration>;
42
+ /**
43
+ * @param importmapAndRoutes An ImportmapAndRoutes object that holds the import map and routes registry
44
+ * @param backend The URL for the backend
45
+ * @param spaPath The spaPath for this instance
46
+ * @returns The same import map declaration but with all imports changed to the appropriate path
47
+ */
48
+ export declare function proxyImportmapAndRoutes(importmapAndRoutes: ImportmapAndRoutesWithWatches, backend: string, spaPath: string): {
49
+ importmap: ImportmapDeclaration;
50
+ routes: RoutesDeclaration;
51
+ watchedRoutesPaths: Record<string, string>;
52
+ };
53
+ //# sourceMappingURL=importmap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"importmap.d.ts","sourceRoot":"","sources":["../../src/utils/importmap.ts"],"names":[],"mappings":"AA8FA,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,QAAQ,GAAG,KAAK,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,QAAQ,GAAG,KAAK,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,oBAAoB,CAAC;IAChC,MAAM,EAAE,iBAAiB,CAAC;CAC3B;AAED,MAAM,WAAW,6BAA8B,SAAQ,kBAAkB;IACvE,SAAS,EAAE,oBAAoB,CAAC;IAChC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5C;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,WAO/C;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,WAe5C;AA4BD,wBAAsB,UAAU,CAC9B,QAAQ,EAAE,MAAM,EAChB,uBAAuB,EAAE,KAAK,CAAC,MAAM,CAAC,EACtC,SAAS,CAAC,EAAE,OAAO,GAClB,OAAO,CAAC;IACT,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5C,CAAC,CAgFD;AAED;;;;;;;;GAQG;AACH,wBAAsB,uBAAuB,CAC3C,eAAe,EAAE,kBAAkB,EACnC,0BAA0B,EACtB;IACE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5C,GACD,KAAK,EACT,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,6BAA6B,CAAC,CAuCxC;AAED,wBAAsB,qBAAqB,CACzC,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,CAAC,CAI7B;AAED,wBAAsB,YAAY,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAuC1G;AAED,wBAAsB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA4B9E;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,kBAAkB,EAAE,6BAA6B,EACjD,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM;;;;EA6BhB"}
@@ -0,0 +1,312 @@
1
+ import { createRequire } from "node:module";
2
+ import { glob } from "glob";
3
+ import { URL } from "url";
4
+ import { resolve } from "path";
5
+ import { existsSync, readFileSync } from "fs";
6
+ import { exec } from "child_process";
7
+ import { logFail, logInfo, logWarn } from "./logger.js";
8
+ import { startDevServer } from "./devserver.js";
9
+ import { getMainBundle, getAppRoutes } from "./dependencies.js";
10
+ import { getAvailablePort } from "./port.js";
11
+ async function readImportmap(path, backend, spaPath) {
12
+ if (path.startsWith('http://') || path.startsWith('https://')) {
13
+ return fetchRemoteImportmap(path);
14
+ } else if (path === 'importmap.json') {
15
+ // Try the configured backend first (local dev server only)
16
+ if (backend && spaPath) {
17
+ try {
18
+ return await fetchRemoteImportmap(`${backend}${spaPath}importmap.json`);
19
+ } catch (e) {
20
+ logWarn(`Could not read importmap from ${backend}${spaPath}importmap.json. ` + `Using empty importmap — only locally-built apps will be loaded.`);
21
+ }
22
+ }
23
+ // No fallback to any remote server. Return an empty importmap.
24
+ // Locally-built apps are loaded via coreImportmap in rspack.config.js.
25
+ logInfo('Using empty importmap. Locally-built core apps will still load.');
26
+ return '{"imports":{}}';
27
+ }
28
+ return '{"imports":{}}';
29
+ }
30
+ async function readRoutes(path, backend, spaPath) {
31
+ if (path.startsWith('http://') || path.startsWith('https://')) {
32
+ return fetchRemoteRoutes(path);
33
+ } else if (path === 'routes.registry.json') {
34
+ // Try the configured backend first (local dev server only)
35
+ if (backend && spaPath) {
36
+ try {
37
+ return await fetchRemoteRoutes(`${backend}${spaPath}routes.registry.json`);
38
+ } catch (e) {
39
+ logWarn(`Could not read routes registry from ${backend}${spaPath}routes.registry.json. ` + `Using local routes only — routes from locally-built apps will still load.`);
40
+ }
41
+ }
42
+ // No fallback to any remote server. Return empty routes.
43
+ // Locally-built apps inject their own routes via coreRoutes in rspack.config.js.
44
+ logInfo('Using empty routes registry. Locally-built core apps will still register their routes.');
45
+ return '{}';
46
+ }
47
+ return '{}';
48
+ }
49
+ async function fetchRemoteImportmap(fetchUrl) {
50
+ const res = await fetch(fetchUrl);
51
+ if (!res.ok) {
52
+ throw new Error(`Failed to fetch import map from ${fetchUrl}: ${res.status} ${res.statusText}`);
53
+ }
54
+ const m = await res.json();
55
+ if (typeof m === 'object' && m !== null && 'imports' in m && typeof m.imports === 'object' && m.imports !== null) {
56
+ const imports = m.imports;
57
+ Object.keys(imports).forEach((key)=>{
58
+ const url = imports[key];
59
+ if (typeof url === 'string') {
60
+ imports[key] = new URL(url, fetchUrl).href;
61
+ }
62
+ });
63
+ }
64
+ return JSON.stringify(m);
65
+ }
66
+ async function fetchRemoteRoutes(fetchUrl) {
67
+ const res = await fetch(fetchUrl);
68
+ if (!res.ok) {
69
+ throw new Error(`Failed to fetch routes from ${fetchUrl}: ${res.status} ${res.statusText}`);
70
+ }
71
+ const m = await res.json();
72
+ return JSON.stringify(m);
73
+ }
74
+ export function checkImportmapJson(value) {
75
+ try {
76
+ const content = JSON.parse(value);
77
+ return typeof content === 'object' && typeof content.imports === 'object';
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+ export function checkRoutesJson(value) {
83
+ try {
84
+ const content = JSON.parse(value);
85
+ return typeof content === 'object' && content !== null && !Array.isArray(content) && Object.entries(content).every(([key, value])=>typeof key === 'string' && typeof value === 'object' && value !== null && !Array.isArray(value));
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+ async function matchAny(baseDir, patterns) {
91
+ const results = await Promise.all(patterns.map((pattern)=>glob(pattern, {
92
+ cwd: baseDir
93
+ })));
94
+ return results.flat();
95
+ }
96
+ const defaultConfigPath = resolve(import.meta.dirname, '..', '..', 'default-rspack-config.cjs');
97
+ function runProjectDevServer(configPath, port, project, sourceDirectory, importMap, routes, useRspack = false) {
98
+ const bundle = getMainBundle(project);
99
+ const host = `http://localhost:${port}`;
100
+ const { ready } = startDevServer(configPath, port, sourceDirectory, useRspack);
101
+ importMap[project.name] = `${host}/${bundle.name}`;
102
+ routes[project.name] = getAppRoutes(sourceDirectory, project);
103
+ return ready;
104
+ }
105
+ export async function runProject(basePort, sourceDirectoryPatterns, useRspack) {
106
+ const baseDir = process.cwd();
107
+ const sourceDirectories = await matchAny(baseDir, sourceDirectoryPatterns);
108
+ const importMap = {};
109
+ const routes = {};
110
+ const watchedRoutesPaths = {};
111
+ const devServerReadyPromises = [];
112
+ // Track the starting port, which is one more than the last used port
113
+ let nextPortToCheck = basePort + 1;
114
+ logInfo('Loading dynamic import map and routes ...');
115
+ for (const sourceDir of sourceDirectories){
116
+ const sourceDirectory = resolve(baseDir, sourceDir);
117
+ const projectFile = resolve(sourceDirectory, 'package.json');
118
+ const routesFile = resolve(sourceDirectory, 'src', 'routes.json');
119
+ const configPath = resolve(sourceDirectory, 'webpack.config.js');
120
+ const rspackConfigPath = resolve(sourceDirectory, 'rspack.config.js');
121
+ const hasConfig = typeof useRspack !== 'undefined' ? !useRspack : existsSync(configPath);
122
+ const hasRspackConfig = typeof useRspack !== 'undefined' ? useRspack : existsSync(rspackConfigPath);
123
+ logInfo(`Looking in directory "${sourceDirectory}" ...`);
124
+ if (!existsSync(projectFile)) {
125
+ logFail(`No "package.json" found in directory "${sourceDirectory}". Skipping ...`);
126
+ continue;
127
+ }
128
+ const require = createRequire(import.meta.url);
129
+ const project = require(projectFile);
130
+ const startup = project['egen:develop'];
131
+ if (existsSync(routesFile)) {
132
+ watchedRoutesPaths[project.name] = routesFile;
133
+ }
134
+ if (typeof startup === 'object') {
135
+ // detected specialized startup command
136
+ const cp = exec(startup.command, {
137
+ cwd: sourceDirectory
138
+ });
139
+ cp.stdout?.pipe(process.stdout);
140
+ cp.stderr?.pipe(process.stderr);
141
+ // connect to either startup.url or a computed value based on startup.host
142
+ const bundle = getMainBundle(project);
143
+ importMap[project.name] = startup.url || `${startup.host}/${bundle.name}`;
144
+ } else if (!hasConfig && !hasRspackConfig) {
145
+ // try to locate and run via default webpack
146
+ logWarn(`No "webpack.config.js" found in directory "${sourceDirectory}". Trying to use default config ...`);
147
+ // Find next available port
148
+ const port = await getAvailablePort(nextPortToCheck);
149
+ nextPortToCheck = port + 1;
150
+ devServerReadyPromises.push(runProjectDevServer(defaultConfigPath, port, project, sourceDirectory, importMap, routes));
151
+ } else {
152
+ // Find next available port
153
+ const port = await getAvailablePort(nextPortToCheck);
154
+ nextPortToCheck = port + 1;
155
+ if (hasConfig) {
156
+ // run via specialized webpack.config.js
157
+ devServerReadyPromises.push(runProjectDevServer(configPath, port, project, sourceDirectory, importMap, routes));
158
+ } else {
159
+ devServerReadyPromises.push(runProjectDevServer(rspackConfigPath, port, project, sourceDirectory, importMap, routes, true));
160
+ }
161
+ }
162
+ }
163
+ await Promise.all(devServerReadyPromises);
164
+ logInfo(`Assembled dynamic import map and routes for packages (${Object.keys(importMap).join(', ')}).`);
165
+ return {
166
+ importMap,
167
+ routes,
168
+ watchedRoutesPaths
169
+ };
170
+ }
171
+ /**
172
+ * @param importAndRoutes An ImportmapAndRoutes object that holds the current import map and routes registries
173
+ * @param additionalImportsAndRoutes An object containing any import map entries, routes, and watched route files to add to the setup
174
+ * @param backend The URL for the backend
175
+ * @param spaPath The spaPath for this instance
176
+ * @returns The import map declaration with the new imports added in. If
177
+ * there are new imports to add, and if the original import map declaration
178
+ * had type "url", it is downloaded and resolved to one of type "inline".
179
+ */ export async function mergeImportmapAndRoutes(importAndRoutes, additionalImportsAndRoutes, backend, spaPath) {
180
+ const { importMap: importDecl, routes: routesDecl } = importAndRoutes;
181
+ const { importMap: additionalImports, routes: additionalRoutes, watchedRoutesPaths = {} } = additionalImportsAndRoutes || {};
182
+ if (additionalImports && Object.keys(additionalImports).length > 0) {
183
+ if (importDecl.type === 'url') {
184
+ importDecl.type = 'inline';
185
+ importDecl.value = await readImportmap(importDecl.value, backend, spaPath);
186
+ }
187
+ const map = JSON.parse(importDecl.value);
188
+ importDecl.value = JSON.stringify({
189
+ imports: {
190
+ ...map.imports,
191
+ ...additionalImports
192
+ }
193
+ });
194
+ }
195
+ if (additionalRoutes && Object.keys(additionalRoutes).length > 0) {
196
+ if (routesDecl.type === 'url') {
197
+ routesDecl.type = 'inline';
198
+ routesDecl.value = await readRoutes(routesDecl.value, backend, spaPath);
199
+ }
200
+ const routes = JSON.parse(routesDecl.value);
201
+ routesDecl.value = JSON.stringify({
202
+ ...routes,
203
+ ...additionalRoutes
204
+ });
205
+ }
206
+ return {
207
+ importMap: importDecl,
208
+ routes: routesDecl,
209
+ watchedRoutesPaths
210
+ };
211
+ }
212
+ export async function getImportmapAndRoutes(importMapPath, routesPath, basePort) {
213
+ return Promise.all([
214
+ getImportMap(importMapPath, basePort),
215
+ getRoutes(routesPath)
216
+ ]).then(([importMap, routes])=>{
217
+ return {
218
+ importMap,
219
+ routes
220
+ };
221
+ });
222
+ }
223
+ export async function getImportMap(importMapPath, basePort) {
224
+ if (importMapPath === '@' && basePort) {
225
+ logWarn('Using the "@" import map is deprecated. Switch to use the "--run-project" flag.');
226
+ const imports = await runProject(basePort, [
227
+ '.'
228
+ ]);
229
+ return {
230
+ type: 'inline',
231
+ value: JSON.stringify({
232
+ imports
233
+ })
234
+ };
235
+ } else if (!/^https?:\/\//.test(importMapPath)) {
236
+ const path = resolve(process.cwd(), importMapPath);
237
+ if (existsSync(path)) {
238
+ const content = readFileSync(path, 'utf8');
239
+ const valid = checkImportmapJson(content);
240
+ if (!valid) {
241
+ logWarn(`The import map provided in "${importMapPath}" does not seem right. Skipping.`);
242
+ }
243
+ return {
244
+ type: 'inline',
245
+ value: valid ? content : ''
246
+ };
247
+ } else if (checkImportmapJson(importMapPath)) {
248
+ return {
249
+ type: 'inline',
250
+ value: importMapPath
251
+ };
252
+ }
253
+ }
254
+ return {
255
+ type: 'url',
256
+ value: importMapPath
257
+ };
258
+ }
259
+ export async function getRoutes(routesPath) {
260
+ if (!/^https?:\/\//.test(routesPath)) {
261
+ const path = resolve(process.cwd(), routesPath);
262
+ if (existsSync(path)) {
263
+ const content = readFileSync(path, 'utf8');
264
+ const valid = checkRoutesJson(content);
265
+ if (!valid) {
266
+ logWarn(`The routes provided provided in "${routesPath}" does not seem right. Skipping.`);
267
+ }
268
+ return {
269
+ type: 'inline',
270
+ value: valid ? content : ''
271
+ };
272
+ } else if (checkRoutesJson(routesPath)) {
273
+ return {
274
+ type: 'inline',
275
+ value: routesPath
276
+ };
277
+ }
278
+ }
279
+ return {
280
+ type: 'url',
281
+ value: routesPath
282
+ };
283
+ }
284
+ /**
285
+ * @param importmapAndRoutes An ImportmapAndRoutes object that holds the import map and routes registry
286
+ * @param backend The URL for the backend
287
+ * @param spaPath The spaPath for this instance
288
+ * @returns The same import map declaration but with all imports changed to the appropriate path
289
+ */ export function proxyImportmapAndRoutes(importmapAndRoutes, backend, spaPath) {
290
+ const { importMap: importMapDecl, routes: routesDecl, watchedRoutesPaths } = importmapAndRoutes;
291
+ if (importMapDecl.type != 'inline') {
292
+ throw new Error('proxyImportmapAndRoutes called on non-inline import map. This is a programming error. Value: ' + importMapDecl.value);
293
+ }
294
+ if (routesDecl.type != 'inline') {
295
+ throw new Error('proxyImportmapAndRoutes called on non-inline routes. This is a programming error. Value: ' + routesDecl.value);
296
+ }
297
+ const backendUrl = new URL(backend);
298
+ const importmap = JSON.parse(importMapDecl.value);
299
+ const spaPathRegEx = new RegExp('^' + spaPath.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'));
300
+ Object.keys(importmap.imports).forEach((key)=>{
301
+ const url = new URL(importmap.imports[key], backendUrl);
302
+ if (url.protocol === backendUrl.protocol && url.host === backendUrl.host) {
303
+ importmap.imports[key] = `./${url.pathname.replace(spaPathRegEx, '')}${url.search}${url.hash}`;
304
+ }
305
+ });
306
+ importMapDecl.value = JSON.stringify(importmap);
307
+ return {
308
+ importmap: importMapDecl,
309
+ routes: routesDecl,
310
+ watchedRoutesPaths
311
+ };
312
+ }
@@ -0,0 +1,10 @@
1
+ export * from './config';
2
+ export * from './helpers';
3
+ export * from './importmap';
4
+ export * from './logger';
5
+ export * from './packages';
6
+ export * from './port';
7
+ export * from './untar';
8
+ export * from './types';
9
+ export * from './variables';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"}
@@ -0,0 +1,9 @@
1
+ export * from "./config.js";
2
+ export * from "./helpers.js";
3
+ export * from "./importmap.js";
4
+ export * from "./logger.js";
5
+ export * from "./packages.js";
6
+ export * from "./port.js";
7
+ export * from "./untar.js";
8
+ export * from "./types.js";
9
+ export * from "./variables.js";
@@ -0,0 +1,4 @@
1
+ export declare function logInfo(message: string): void;
2
+ export declare function logWarn(message: string): void;
3
+ export declare function logFail(message: string): void;
4
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/utils/logger.ts"],"names":[],"mappings":"AAGA,wBAAgB,OAAO,CAAC,OAAO,EAAE,MAAM,QAEtC;AAED,wBAAgB,OAAO,CAAC,OAAO,EAAE,MAAM,QAEtC;AAED,wBAAgB,OAAO,CAAC,OAAO,EAAE,MAAM,QAEtC"}
@@ -0,0 +1,10 @@
1
+ /* eslint-disable no-console */ import chalk from "chalk";
2
+ export function logInfo(message) {
3
+ console.log(`${chalk.green.bold('[egen]')} ${message}`);
4
+ }
5
+ export function logWarn(message) {
6
+ console.warn(`${chalk.yellow.bold('[egen]')} ${chalk.yellow(message)}`);
7
+ }
8
+ export function logFail(message) {
9
+ console.error(`${chalk.red.bold('[egen]')} ${chalk.red(message)}`);
10
+ }
@@ -0,0 +1,14 @@
1
+ import type npmRegistryFetch from 'npm-registry-fetch';
2
+ /**
3
+ * Utility function to load the appropriate configuration for npmRegistryFetch
4
+ * from the .npmrc configuration chain. Essentially, this allows us to use .npmrc
5
+ * files to configure reading from the NPM registry, which is useful when using
6
+ * a custom registry, especially for private packages.
7
+ *
8
+ * This uses the @pnpm/npm-conf library for reading .npmrc files as its both
9
+ * maintained and sane to work with.
10
+ *
11
+ * @param registry The NPM registry to use, if any
12
+ */
13
+ export declare function getNpmRegistryConfiguration(registry?: string | null | undefined): npmRegistryFetch.Options;
14
+ //# sourceMappingURL=npmConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"npmConfig.d.ts","sourceRoot":"","sources":["../../src/utils/npmConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,gBAAgB,MAAM,oBAAoB,CAAC;AAGvD;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,gBAAgB,CAAC,OAAO,CAmC1G"}
@@ -0,0 +1,39 @@
1
+ import npmConfig from "@pnpm/npm-conf";
2
+ /**
3
+ * Utility function to load the appropriate configuration for npmRegistryFetch
4
+ * from the .npmrc configuration chain. Essentially, this allows us to use .npmrc
5
+ * files to configure reading from the NPM registry, which is useful when using
6
+ * a custom registry, especially for private packages.
7
+ *
8
+ * This uses the @pnpm/npm-conf library for reading .npmrc files as its both
9
+ * maintained and sane to work with.
10
+ *
11
+ * @param registry The NPM registry to use, if any
12
+ */ export function getNpmRegistryConfiguration(registry) {
13
+ const conf = npmConfig();
14
+ if (!conf) {
15
+ return {};
16
+ }
17
+ if (conf.warnings.length >= 1) {
18
+ throw new Error(`Warnings while loading .npmrc:\n ${conf.warnings.join('\n ')}`);
19
+ }
20
+ if (!conf.config) {
21
+ return {};
22
+ }
23
+ // the returned config object uses getters with no list of keys
24
+ // so to convert this to a "normal" object, we combine all the settings
25
+ // found; note this relies on the internal structure of the config
26
+ // object and may not be stable
27
+ const configuration = Object.assign({}, ...conf.config.list.slice().reverse() ?? []);
28
+ if (configuration.__source__) {
29
+ delete configuration.__source__;
30
+ }
31
+ if ('strict-ssl' in configuration) {
32
+ configuration.strictSSL = configuration['strict-ssl'];
33
+ delete configuration['strict-ssl'];
34
+ }
35
+ if (registry) {
36
+ configuration.registry = registry;
37
+ }
38
+ return configuration;
39
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Resolve package names to their source directories.
3
+ *
4
+ * First checks the current directory's package.json for a direct match,
5
+ * which handles single-package repos efficiently. If any requested
6
+ * packages remain unresolved, walks up the directory tree to find a
7
+ * workspace root and globs its workspace patterns to build a complete
8
+ * package map.
9
+ *
10
+ * @returns Absolute paths to the resolved package directories.
11
+ * @throws If any requested package name cannot be resolved, with a list
12
+ * of available packages.
13
+ */
14
+ export declare function resolvePackages(packageNames: Array<string>): Promise<Array<string>>;
15
+ //# sourceMappingURL=packages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"packages.d.ts","sourceRoot":"","sources":["../../src/utils/packages.ts"],"names":[],"mappings":"AAqCA;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CA6DzF"}
@@ -0,0 +1,92 @@
1
+ import { glob } from "glob";
2
+ import { dirname, resolve } from "path";
3
+ import { existsSync, readFileSync } from "fs";
4
+ import { logInfo } from "./logger.js";
5
+ function readPackageJson(pkgPath) {
6
+ return JSON.parse(readFileSync(pkgPath, 'utf8'));
7
+ }
8
+ function getWorkspacePatterns(pkg) {
9
+ const workspaces = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? null;
10
+ return workspaces && workspaces.length > 0 ? workspaces : null;
11
+ }
12
+ /**
13
+ * Walk up the directory tree from startDir looking for a package.json
14
+ * with a workspaces field, which indicates a monorepo root.
15
+ */ function findWorkspaceRoot(startDir) {
16
+ let dir = startDir;
17
+ for(;;){
18
+ const pkgPath = resolve(dir, 'package.json');
19
+ if (existsSync(pkgPath)) {
20
+ const pkg = readPackageJson(pkgPath);
21
+ if (getWorkspacePatterns(pkg)) {
22
+ return dir;
23
+ }
24
+ }
25
+ const parent = dirname(dir);
26
+ if (parent === dir) {
27
+ return null;
28
+ }
29
+ dir = parent;
30
+ }
31
+ }
32
+ /**
33
+ * Resolve package names to their source directories.
34
+ *
35
+ * First checks the current directory's package.json for a direct match,
36
+ * which handles single-package repos efficiently. If any requested
37
+ * packages remain unresolved, walks up the directory tree to find a
38
+ * workspace root and globs its workspace patterns to build a complete
39
+ * package map.
40
+ *
41
+ * @returns Absolute paths to the resolved package directories.
42
+ * @throws If any requested package name cannot be resolved, with a list
43
+ * of available packages.
44
+ */ export async function resolvePackages(packageNames) {
45
+ const cwd = process.cwd();
46
+ const packageMap = new Map();
47
+ // Check the nearest package.json first (fast path for single-package repos)
48
+ const cwdPkgPath = resolve(cwd, 'package.json');
49
+ if (existsSync(cwdPkgPath)) {
50
+ const cwdPkg = readPackageJson(cwdPkgPath);
51
+ if (cwdPkg.name) {
52
+ packageMap.set(cwdPkg.name, cwd);
53
+ }
54
+ }
55
+ // If all requested packages are already resolved, skip workspace discovery
56
+ if (!packageNames.every((name)=>packageMap.has(name))) {
57
+ const workspaceRoot = findWorkspaceRoot(cwd);
58
+ if (workspaceRoot) {
59
+ const rootPkg = readPackageJson(resolve(workspaceRoot, 'package.json'));
60
+ const patterns = getWorkspacePatterns(rootPkg);
61
+ const results = await Promise.all(patterns.map((pattern)=>glob(pattern, {
62
+ cwd: workspaceRoot
63
+ })));
64
+ const workspaceDirs = results.flat();
65
+ for (const dir of workspaceDirs){
66
+ const pkgPath = resolve(workspaceRoot, dir, 'package.json');
67
+ if (existsSync(pkgPath)) {
68
+ const pkg = readPackageJson(pkgPath);
69
+ if (pkg.name) {
70
+ packageMap.set(pkg.name, resolve(workspaceRoot, dir));
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ const resolved = [];
77
+ const notFound = [];
78
+ for (const name of packageNames){
79
+ const dir = packageMap.get(name);
80
+ if (dir) {
81
+ logInfo(`Resolved package "${name}" to "${dir}"`);
82
+ resolved.push(dir);
83
+ } else {
84
+ notFound.push(name);
85
+ }
86
+ }
87
+ if (notFound.length > 0) {
88
+ const available = Array.from(packageMap.keys()).sort((a, b)=>a.localeCompare(b, 'en'));
89
+ throw new Error(`Could not resolve the following package(s):\n` + notFound.map((n)=>` - ${n}`).join('\n') + (available.length > 0 ? `\n\nAvailable packages:\n` + available.map((n)=>` - ${n}`).join('\n') : '\n\nNo packages were found in the current directory.'));
90
+ }
91
+ return resolved;
92
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Checks if a port is available for use by attempting to bind to it.
3
+ * Checks both IPv4 (0.0.0.0) and IPv6 (::) to ensure the port is truly available.
4
+ * @param port The port number to check
5
+ * @returns A promise that resolves to true if the port is available, false otherwise
6
+ */
7
+ export declare function isPortAvailable(port: number): Promise<boolean>;
8
+ /**
9
+ * Finds the next available port starting from the given port.
10
+ * @param startPort The port number to start searching from
11
+ * @returns A promise that resolves to an available port number
12
+ * @throws Error if no available port is found up to port 65535
13
+ */
14
+ export declare function getAvailablePort(startPort: number): Promise<number>;
15
+ //# sourceMappingURL=port.d.ts.map