Skip to content

Commit f346ee8

Browse files
committedSep 17, 2024·
feat(@angular/ssr): add isMainModule function
Adds a new function `isMainModule` that checks if the current module is the main entry point of the application. This is useful to ensure that server listener handlers are only registered when the module is executed directly and not when it's imported as a dependency such as the dev-server. This prevents potential issues with multiple listeners being registered unintentionally.
1 parent 09d2eb9 commit f346ee8

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed
 

‎goldens/public-api/angular/ssr/node/index.api.md

+3
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ export interface CommonEngineRenderOptions {
4646
// @public
4747
export function createWebRequestFromNodeRequest(nodeRequest: IncomingMessage): Request;
4848

49+
// @public
50+
export function isMainModule(url: string): boolean;
51+
4952
// @public
5053
export function writeResponseToNodeResponse(source: Response, destination: ServerResponse): Promise<void>;
5154

‎packages/angular/ssr/node/public_api.ts

+1
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ export { AngularNodeAppEngine } from './src/app-engine';
1616

1717
export { writeResponseToNodeResponse } from './src/response';
1818
export { createWebRequestFromNodeRequest } from './src/request';
19+
export { isMainModule } from './src/module';
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { argv } from 'node:process';
10+
import { fileURLToPath } from 'node:url';
11+
12+
/**
13+
* Determines whether the provided URL represents the main entry point module.
14+
*
15+
* This function checks if the provided URL corresponds to the main ESM module being executed directly.
16+
* It's useful for conditionally executing code that should only run when a module is the entry point,
17+
* such as starting a server or initializing an application.
18+
*
19+
* It performs two key checks:
20+
* 1. Verifies if the URL starts with 'file:', ensuring it is a local file.
21+
* 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),
22+
* which points to the file being executed.
23+
*
24+
* @param url The URL of the module to check. This should typically be `import.meta.url`.
25+
* @returns `true` if the provided URL represents the main entry point, otherwise `false`.
26+
* @developerPreview
27+
*/
28+
export function isMainModule(url: string): boolean {
29+
return url.startsWith('file:') && argv[1] === fileURLToPath(url);
30+
}

0 commit comments

Comments
 (0)
Please sign in to comment.