@eserstack/laroux-server 0.0.0-stage → 5.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.
- package/LICENSE +13 -0
- package/README.md +410 -2
- package/dist/adapters/react/error-chunk.d.ts +11 -0
- package/dist/adapters/react/error-chunk.js +12 -0
- package/dist/adapters/react/html-shell.d.ts +15 -0
- package/dist/adapters/react/html-shell.js +109 -0
- package/dist/adapters/react/inline-rsc-emitter.d.ts +62 -0
- package/dist/adapters/react/inline-rsc-emitter.js +120 -0
- package/dist/adapters/react/mod.d.ts +30 -0
- package/dist/adapters/react/mod.js +36 -0
- package/dist/adapters/react/render-app.d.ts +46 -0
- package/dist/adapters/react/render-app.js +44 -0
- package/dist/adapters/react/renderer.d.ts +15 -0
- package/dist/adapters/react/renderer.js +86 -0
- package/dist/adapters/react/rsc-flight-renderer.d.ts +64 -0
- package/dist/adapters/react/rsc-flight-renderer.js +623 -0
- package/dist/adapters/react/rsc-handler.d.ts +47 -0
- package/dist/adapters/react/rsc-handler.js +114 -0
- package/dist/adapters/react/script-json.d.ts +12 -0
- package/dist/adapters/react/script-json.js +18 -0
- package/dist/adapters/react/ssr-renderer.d.ts +63 -0
- package/dist/adapters/react/ssr-renderer.js +625 -0
- package/dist/bin-main.d.ts +1 -0
- package/dist/bin-main.js +18 -0
- package/dist/cli.d.ts +26 -0
- package/dist/cli.js +48 -0
- package/dist/commands/build.d.ts +78 -0
- package/dist/commands/build.js +221 -0
- package/dist/commands/dev.d.ts +50 -0
- package/dist/commands/dev.js +133 -0
- package/dist/commands/init.d.ts +29 -0
- package/dist/commands/init.js +228 -0
- package/dist/commands/serve.d.ts +47 -0
- package/dist/commands/serve.js +124 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +67 -0
- package/dist/domain/action-registry.d.ts +83 -0
- package/dist/domain/action-registry.js +124 -0
- package/dist/domain/build-module.d.ts +30 -0
- package/dist/domain/build-module.js +50 -0
- package/dist/domain/hmr-manager.d.ts +51 -0
- package/dist/domain/hmr-manager.js +90 -0
- package/dist/domain/html-shell.d.ts +56 -0
- package/dist/domain/html-shell.js +15 -0
- package/dist/domain/middleware-dispatcher.d.ts +42 -0
- package/dist/domain/middleware-dispatcher.js +150 -0
- package/dist/domain/rebuild-handler.d.ts +52 -0
- package/dist/domain/rebuild-handler.js +52 -0
- package/dist/domain/renderer.d.ts +62 -0
- package/dist/domain/renderer.js +15 -0
- package/dist/domain/route-dispatcher.d.ts +40 -0
- package/dist/domain/route-dispatcher.js +134 -0
- package/dist/domain/server-modules.d.ts +65 -0
- package/dist/domain/server-modules.js +208 -0
- package/dist/main.d.ts +40 -0
- package/dist/main.js +256 -0
- package/dist/module.d.ts +24 -0
- package/dist/module.js +140 -0
- package/dist/options.d.ts +53 -0
- package/dist/options.js +14 -0
- package/dist/package.json +98 -0
- package/dist/proxy/types.d.ts +19 -0
- package/dist/proxy/types.js +3 -0
- package/dist/runtime/action-guard.d.ts +49 -0
- package/dist/runtime/action-guard.js +115 -0
- package/dist/runtime/html-shell.d.ts +66 -0
- package/dist/runtime/html-shell.js +246 -0
- package/dist/runtime/media-types.d.ts +13 -0
- package/dist/runtime/media-types.js +83 -0
- package/dist/runtime/path-containment.d.ts +11 -0
- package/dist/runtime/path-containment.js +27 -0
- package/dist/runtime/seo/generate-meta.d.ts +16 -0
- package/dist/runtime/seo/generate-meta.js +121 -0
- package/dist/runtime/seo/index.d.ts +5 -0
- package/dist/runtime/seo/index.js +5 -0
- package/dist/runtime/seo/types.d.ts +25 -0
- package/dist/runtime/seo/types.js +5 -0
- package/dist/runtime/server.d.ts +58 -0
- package/dist/runtime/server.js +699 -0
- package/package.json +81 -3
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Imports of the modules a laroux server loads from its build output.
|
|
3
|
+
*
|
|
4
|
+
* The runtime keeps every imported module under its URL until the process
|
|
5
|
+
* exits, so importing a rebuilt file by its plain file URL returns the code it
|
|
6
|
+
* had when it was first imported. These imports add the build id to the URL:
|
|
7
|
+
* after a dev rebuild the server loads the rebuilt modules, and within one
|
|
8
|
+
* build each module loads once.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* The URL to import a module of one build by: its file URL with the build id
|
|
14
|
+
* as the `v` query parameter.
|
|
15
|
+
*
|
|
16
|
+
* @param filePath - Absolute path of the module
|
|
17
|
+
* @param buildId - Id of the build whose modules are loaded
|
|
18
|
+
* @returns The file URL with `?v=<buildId>`
|
|
19
|
+
*/
|
|
20
|
+
export declare function toBuildModuleUrl(filePath: string, buildId: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Import a module of one build, or return null when the build wrote no file
|
|
23
|
+
* at that path, such as the API route registry of an app without route.ts
|
|
24
|
+
* files. An error the import throws propagates.
|
|
25
|
+
*
|
|
26
|
+
* @param filePath - Absolute path of the module
|
|
27
|
+
* @param buildId - Id of the build whose modules are loaded
|
|
28
|
+
* @returns The module's exports, or null when the file does not exist
|
|
29
|
+
*/
|
|
30
|
+
export declare function importOptionalBuildModule(filePath: string, buildId: string): Promise<Readonly<Record<string, unknown>> | null>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Imports of the modules a laroux server loads from its build output.
|
|
4
|
+
*
|
|
5
|
+
* The runtime keeps every imported module under its URL until the process
|
|
6
|
+
* exits, so importing a rebuilt file by its plain file URL returns the code it
|
|
7
|
+
* had when it was first imported. These imports add the build id to the URL:
|
|
8
|
+
* after a dev rebuild the server loads the rebuilt modules, and within one
|
|
9
|
+
* build each module loads once.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
14
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
15
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
16
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return path;
|
|
20
|
+
};
|
|
21
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
22
|
+
import * as nodeUrl from "node:url";
|
|
23
|
+
/**
|
|
24
|
+
* The URL to import a module of one build by: its file URL with the build id
|
|
25
|
+
* as the `v` query parameter.
|
|
26
|
+
*
|
|
27
|
+
* @param filePath - Absolute path of the module
|
|
28
|
+
* @param buildId - Id of the build whose modules are loaded
|
|
29
|
+
* @returns The file URL with `?v=<buildId>`
|
|
30
|
+
*/
|
|
31
|
+
export function toBuildModuleUrl(filePath, buildId) {
|
|
32
|
+
const url = nodeUrl.pathToFileURL(filePath);
|
|
33
|
+
url.searchParams.set("v", buildId);
|
|
34
|
+
return url.href;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Import a module of one build, or return null when the build wrote no file
|
|
38
|
+
* at that path, such as the API route registry of an app without route.ts
|
|
39
|
+
* files. An error the import throws propagates.
|
|
40
|
+
*
|
|
41
|
+
* @param filePath - Absolute path of the module
|
|
42
|
+
* @param buildId - Id of the build whose modules are loaded
|
|
43
|
+
* @returns The module's exports, or null when the file does not exist
|
|
44
|
+
*/
|
|
45
|
+
export async function importOptionalBuildModule(filePath, buildId) {
|
|
46
|
+
if (!(await runtime.fs.exists(filePath))) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return await import(__rewriteRelativeImportExtension(toBuildModuleUrl(filePath, buildId)));
|
|
50
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HMR (Hot Module Replacement) Manager
|
|
3
|
+
* Handles WebSocket connections and notifies clients of updates
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* HMR message types
|
|
7
|
+
*/
|
|
8
|
+
export type HMRMessage = {
|
|
9
|
+
type: "connected";
|
|
10
|
+
} | {
|
|
11
|
+
type: "update";
|
|
12
|
+
timestamp: number;
|
|
13
|
+
changedModules?: string[];
|
|
14
|
+
} | {
|
|
15
|
+
type: "error";
|
|
16
|
+
message: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* HMR Manager
|
|
20
|
+
* Manages WebSocket connections for hot module replacement
|
|
21
|
+
*/
|
|
22
|
+
export declare class HMRManager {
|
|
23
|
+
private clients;
|
|
24
|
+
/**
|
|
25
|
+
* Handle incoming WebSocket connection
|
|
26
|
+
*/
|
|
27
|
+
handleConnection(socket: WebSocket): void;
|
|
28
|
+
/**
|
|
29
|
+
* Notify all connected clients of an update
|
|
30
|
+
*
|
|
31
|
+
* @param timestamp - When the update was built; the caller reads the clock
|
|
32
|
+
* @param changedModules - Modules the update touched, when known
|
|
33
|
+
*/
|
|
34
|
+
notifyUpdate(timestamp: number, changedModules?: string[]): void;
|
|
35
|
+
/**
|
|
36
|
+
* Send error message to all clients
|
|
37
|
+
*/
|
|
38
|
+
notifyError(errorMessage: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* Send message to specific client
|
|
41
|
+
*/
|
|
42
|
+
private sendToClient;
|
|
43
|
+
/**
|
|
44
|
+
* Get number of connected clients
|
|
45
|
+
*/
|
|
46
|
+
getClientCount(): number;
|
|
47
|
+
/**
|
|
48
|
+
* Close all connections
|
|
49
|
+
*/
|
|
50
|
+
close(): void;
|
|
51
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* HMR (Hot Module Replacement) Manager
|
|
4
|
+
* Handles WebSocket connections and notifies clients of updates
|
|
5
|
+
*/
|
|
6
|
+
import * as logging from "@eserstack/logging";
|
|
7
|
+
const hmrLogger = logging.logger.getLogger(["laroux-server", "hmr"]);
|
|
8
|
+
/**
|
|
9
|
+
* HMR Manager
|
|
10
|
+
* Manages WebSocket connections for hot module replacement
|
|
11
|
+
*/
|
|
12
|
+
export class HMRManager {
|
|
13
|
+
clients = new Set();
|
|
14
|
+
/**
|
|
15
|
+
* Handle incoming WebSocket connection
|
|
16
|
+
*/
|
|
17
|
+
handleConnection(socket) {
|
|
18
|
+
this.clients.add(socket);
|
|
19
|
+
hmrLogger.debug(`HMR client connected (${this.clients.size} total)`);
|
|
20
|
+
// Send connected message
|
|
21
|
+
this.sendToClient(socket, { type: "connected" });
|
|
22
|
+
// Handle close
|
|
23
|
+
socket.addEventListener("close", () => {
|
|
24
|
+
this.clients.delete(socket);
|
|
25
|
+
hmrLogger.debug(`HMR client disconnected (${this.clients.size} remaining)`);
|
|
26
|
+
});
|
|
27
|
+
// Handle errors
|
|
28
|
+
socket.addEventListener("error", (event) => {
|
|
29
|
+
hmrLogger
|
|
30
|
+
.with({ event })
|
|
31
|
+
.error("HMR WebSocket error; dropping the client");
|
|
32
|
+
this.clients.delete(socket);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Notify all connected clients of an update
|
|
37
|
+
*
|
|
38
|
+
* @param timestamp - When the update was built; the caller reads the clock
|
|
39
|
+
* @param changedModules - Modules the update touched, when known
|
|
40
|
+
*/
|
|
41
|
+
notifyUpdate(timestamp, changedModules) {
|
|
42
|
+
const message = { type: "update", timestamp, changedModules };
|
|
43
|
+
hmrLogger.debug(`Notifying ${this.clients.size} clients of update${changedModules !== undefined
|
|
44
|
+
? ` (${changedModules.length} modules changed)`
|
|
45
|
+
: ""}`);
|
|
46
|
+
for (const client of this.clients) {
|
|
47
|
+
this.sendToClient(client, message);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Send error message to all clients
|
|
52
|
+
*/
|
|
53
|
+
notifyError(errorMessage) {
|
|
54
|
+
const message = { type: "error", message: errorMessage };
|
|
55
|
+
hmrLogger.warn(`Notifying clients of error: ${errorMessage}`);
|
|
56
|
+
for (const client of this.clients) {
|
|
57
|
+
this.sendToClient(client, message);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Send message to specific client
|
|
62
|
+
*/
|
|
63
|
+
sendToClient(client, message) {
|
|
64
|
+
if (client.readyState === WebSocket.OPEN) {
|
|
65
|
+
try {
|
|
66
|
+
client.send(JSON.stringify(message));
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
hmrLogger
|
|
70
|
+
.with({ error })
|
|
71
|
+
.error(`send HMR ${message.type} message to a client`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Get number of connected clients
|
|
77
|
+
*/
|
|
78
|
+
getClientCount() {
|
|
79
|
+
return this.clients.size;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Close all connections
|
|
83
|
+
*/
|
|
84
|
+
close() {
|
|
85
|
+
for (const client of this.clients) {
|
|
86
|
+
client.close();
|
|
87
|
+
}
|
|
88
|
+
this.clients.clear();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML Shell Port Interface
|
|
3
|
+
* Defines the contract for HTML document generation
|
|
4
|
+
*/
|
|
5
|
+
import type { ChunkManifest } from "@eserstack/laroux-bundler";
|
|
6
|
+
/**
|
|
7
|
+
* Options for generating HTML shell
|
|
8
|
+
*/
|
|
9
|
+
export type HtmlShellOptions = {
|
|
10
|
+
/** Content for <head> section */
|
|
11
|
+
head?: string;
|
|
12
|
+
/** Content for <body> section */
|
|
13
|
+
body?: string;
|
|
14
|
+
/** Script URLs to include */
|
|
15
|
+
scripts?: string[];
|
|
16
|
+
/** Stylesheet URLs to include */
|
|
17
|
+
styles?: string[];
|
|
18
|
+
/** Critical CSS to inline */
|
|
19
|
+
criticalCss?: string;
|
|
20
|
+
/** Serialized RSC payload for hydration */
|
|
21
|
+
rscPayload?: string;
|
|
22
|
+
/** Chunk manifest for client-side loading */
|
|
23
|
+
manifest?: ChunkManifest;
|
|
24
|
+
/** Page title */
|
|
25
|
+
title?: string;
|
|
26
|
+
/** Language attribute */
|
|
27
|
+
lang?: string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* HTML Shell Builder port interface
|
|
31
|
+
* Framework adapters implement this for framework-specific HTML generation
|
|
32
|
+
*/
|
|
33
|
+
export type HtmlShellBuilder = {
|
|
34
|
+
/** Builder name for identification */
|
|
35
|
+
name: string;
|
|
36
|
+
/**
|
|
37
|
+
* Create complete HTML document
|
|
38
|
+
* @param options - Shell generation options
|
|
39
|
+
*/
|
|
40
|
+
createShell(options: HtmlShellOptions): string;
|
|
41
|
+
/**
|
|
42
|
+
* Create start of streaming HTML document (for SSR streaming)
|
|
43
|
+
* @param options - Shell generation options
|
|
44
|
+
*/
|
|
45
|
+
createStreamingStart(options: HtmlShellOptions): string;
|
|
46
|
+
/**
|
|
47
|
+
* Create end of streaming HTML document
|
|
48
|
+
* @param options - Shell generation options
|
|
49
|
+
*/
|
|
50
|
+
createStreamingEnd(options: HtmlShellOptions): string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* No-op HTML shell builder
|
|
54
|
+
* Used as default when no builder is configured
|
|
55
|
+
*/
|
|
56
|
+
export declare const noopHtmlShellBuilder: HtmlShellBuilder;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* HTML Shell Port Interface
|
|
4
|
+
* Defines the contract for HTML document generation
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* No-op HTML shell builder
|
|
8
|
+
* Used as default when no builder is configured
|
|
9
|
+
*/
|
|
10
|
+
export const noopHtmlShellBuilder = {
|
|
11
|
+
name: "noop",
|
|
12
|
+
createShell: () => "<!DOCTYPE html><html><head></head><body></body></html>",
|
|
13
|
+
createStreamingStart: () => "<!DOCTYPE html><html><head></head><body>",
|
|
14
|
+
createStreamingEnd: () => "</body></html>",
|
|
15
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ProxyResult } from "../proxy/types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Proxy entry from the generated registry
|
|
4
|
+
*/
|
|
5
|
+
export type ProxyEntry = {
|
|
6
|
+
pathPrefix: string;
|
|
7
|
+
modulePath: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Result of proxy execution
|
|
11
|
+
*/
|
|
12
|
+
export type ProxyExecutionResult = {
|
|
13
|
+
result: ProxyResult;
|
|
14
|
+
finalPathname: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Middleware Dispatcher
|
|
18
|
+
* Manages loading and executing proxies/middleware
|
|
19
|
+
*/
|
|
20
|
+
export declare class MiddlewareDispatcher {
|
|
21
|
+
private loaded;
|
|
22
|
+
/**
|
|
23
|
+
* Load the proxies of a build from its generated registry,
|
|
24
|
+
* <distDir>/server/proxy-registry.ts. A build without proxy.ts files
|
|
25
|
+
* writes no registry, so it has no proxies. Proxy modules load on the
|
|
26
|
+
* first request they run for, by URLs that carry the build id: after a
|
|
27
|
+
* rebuild, loading the new build makes requests import the rebuilt proxies.
|
|
28
|
+
*
|
|
29
|
+
* @param distDir - Build output directory
|
|
30
|
+
* @param buildId - Id of the build to load
|
|
31
|
+
*/
|
|
32
|
+
loadProxies(distDir: string, buildId: string): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Run proxies for a request
|
|
35
|
+
* Returns the final result and potentially rewritten pathname
|
|
36
|
+
*/
|
|
37
|
+
runProxies(req: Request, pathname: string): Promise<ProxyExecutionResult>;
|
|
38
|
+
/**
|
|
39
|
+
* Check if pathname matches proxy prefix
|
|
40
|
+
*/
|
|
41
|
+
private matchesPrefix;
|
|
42
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
// Middleware Dispatcher for laroux.js
|
|
3
|
+
// Handles file-based proxy/middleware (proxy.ts files)
|
|
4
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
5
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
6
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
7
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
return path;
|
|
11
|
+
};
|
|
12
|
+
import * as logging from "@eserstack/logging";
|
|
13
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
14
|
+
import * as buildModule from "./build-module.js";
|
|
15
|
+
const proxyLogger = logging.logger.getLogger([
|
|
16
|
+
"laroux-server",
|
|
17
|
+
"proxy-handler",
|
|
18
|
+
]);
|
|
19
|
+
/**
|
|
20
|
+
* Middleware Dispatcher
|
|
21
|
+
* Manages loading and executing proxies/middleware
|
|
22
|
+
*/
|
|
23
|
+
export class MiddlewareDispatcher {
|
|
24
|
+
loaded = {
|
|
25
|
+
proxies: [],
|
|
26
|
+
registryDir: "",
|
|
27
|
+
buildId: "",
|
|
28
|
+
moduleCache: new Map(),
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Load the proxies of a build from its generated registry,
|
|
32
|
+
* <distDir>/server/proxy-registry.ts. A build without proxy.ts files
|
|
33
|
+
* writes no registry, so it has no proxies. Proxy modules load on the
|
|
34
|
+
* first request they run for, by URLs that carry the build id: after a
|
|
35
|
+
* rebuild, loading the new build makes requests import the rebuilt proxies.
|
|
36
|
+
*
|
|
37
|
+
* @param distDir - Build output directory
|
|
38
|
+
* @param buildId - Id of the build to load
|
|
39
|
+
*/
|
|
40
|
+
async loadProxies(distDir, buildId) {
|
|
41
|
+
const registryDir = runtime.path.resolve(distDir, "server");
|
|
42
|
+
const registry = await buildModule.importOptionalBuildModule(runtime.path.join(registryDir, "proxy-registry.ts"), buildId);
|
|
43
|
+
const entries = registry?.["proxyRegistry"];
|
|
44
|
+
const proxies = Array.isArray(entries)
|
|
45
|
+
? entries
|
|
46
|
+
: [];
|
|
47
|
+
// Replaced in one step: a request that started before keeps the build
|
|
48
|
+
// it started with, so it never mixes the modules of two builds.
|
|
49
|
+
this.loaded = { proxies, registryDir, buildId, moduleCache: new Map() };
|
|
50
|
+
proxyLogger.debug(`Loaded ${proxies.length} proxy definition(s)`);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Run proxies for a request
|
|
54
|
+
* Returns the final result and potentially rewritten pathname
|
|
55
|
+
*/
|
|
56
|
+
async runProxies(req, pathname) {
|
|
57
|
+
const loaded = this.loaded;
|
|
58
|
+
let currentPathname = pathname;
|
|
59
|
+
for (const proxy of loaded.proxies) {
|
|
60
|
+
// Check if pathname matches this proxy's prefix
|
|
61
|
+
if (!this.matchesPrefix(currentPathname, proxy.pathPrefix)) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
proxyLogger.debug(`Running proxy: ${proxy.pathPrefix} for ${currentPathname}`);
|
|
65
|
+
try {
|
|
66
|
+
// Resolve module path relative to the registry directory
|
|
67
|
+
const resolvedPath = runtime.path.resolve(loaded.registryDir, proxy.modulePath);
|
|
68
|
+
// Load module (with caching)
|
|
69
|
+
let module = loaded.moduleCache.get(resolvedPath);
|
|
70
|
+
if (module === undefined) {
|
|
71
|
+
const moduleUrl = buildModule.toBuildModuleUrl(resolvedPath, loaded.buildId);
|
|
72
|
+
// Loaded lazily inside the chain: a proxy that an earlier one cuts
|
|
73
|
+
// off by a response or redirect is never imported.
|
|
74
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
75
|
+
module = (await import(__rewriteRelativeImportExtension(moduleUrl)));
|
|
76
|
+
loaded.moduleCache.set(resolvedPath, module);
|
|
77
|
+
}
|
|
78
|
+
const proxyFn = module.default;
|
|
79
|
+
if (typeof proxyFn !== "function") {
|
|
80
|
+
proxyLogger.warn(`Proxy ${proxy.modulePath} does not export a default function`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
// Execute proxy. Sequential on purpose: a rewrite changes the
|
|
84
|
+
// pathname the next proxy sees, and a response or redirect ends the
|
|
85
|
+
// chain.
|
|
86
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
87
|
+
const result = await proxyFn({
|
|
88
|
+
request: req,
|
|
89
|
+
pathname: currentPathname,
|
|
90
|
+
params: {},
|
|
91
|
+
});
|
|
92
|
+
// Handle result
|
|
93
|
+
if (result.type === "response") {
|
|
94
|
+
proxyLogger.debug(`Proxy ${proxy.pathPrefix} returned response`);
|
|
95
|
+
return { result, finalPathname: currentPathname };
|
|
96
|
+
}
|
|
97
|
+
if (result.type === "redirect") {
|
|
98
|
+
proxyLogger.debug(`Proxy ${proxy.pathPrefix} redirecting to ${result.url}`);
|
|
99
|
+
return { result, finalPathname: currentPathname };
|
|
100
|
+
}
|
|
101
|
+
if (result.type === "rewrite") {
|
|
102
|
+
proxyLogger.debug(`Proxy ${proxy.pathPrefix} rewriting to ${result.pathname}`);
|
|
103
|
+
currentPathname = result.pathname;
|
|
104
|
+
// Continue to next proxy with rewritten pathname
|
|
105
|
+
}
|
|
106
|
+
// type === "next" - continue to next proxy
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
// Handled here: logged once with the proxy, and the client gets a
|
|
110
|
+
// fixed message without the error's details. The chain ends with
|
|
111
|
+
// this response, so the await runs once.
|
|
112
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
113
|
+
await proxyLogger
|
|
114
|
+
.with({
|
|
115
|
+
pathPrefix: proxy.pathPrefix,
|
|
116
|
+
modulePath: proxy.modulePath,
|
|
117
|
+
error,
|
|
118
|
+
})
|
|
119
|
+
.error("proxy failed to load or threw; answered 500");
|
|
120
|
+
return {
|
|
121
|
+
result: {
|
|
122
|
+
type: "response",
|
|
123
|
+
response: new Response(JSON.stringify({
|
|
124
|
+
error: "Proxy Error",
|
|
125
|
+
}), {
|
|
126
|
+
status: 500,
|
|
127
|
+
headers: { "Content-Type": "application/json" },
|
|
128
|
+
}),
|
|
129
|
+
},
|
|
130
|
+
finalPathname: currentPathname,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// No proxy intercepted, continue normally
|
|
135
|
+
return {
|
|
136
|
+
result: { type: "next" },
|
|
137
|
+
finalPathname: currentPathname,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Check if pathname matches proxy prefix
|
|
142
|
+
*/
|
|
143
|
+
matchesPrefix(pathname, prefix) {
|
|
144
|
+
// Root prefix "/" matches everything
|
|
145
|
+
if (prefix === "/") {
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
return pathname === prefix || pathname.startsWith(prefix + "/");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebuild Handler
|
|
3
|
+
*
|
|
4
|
+
* Decides what the dev server does after each watch-mode rebuild: after one
|
|
5
|
+
* that succeeded, it loads the rebuilt server modules and then tells the HMR
|
|
6
|
+
* clients to update; after one that failed, or when the rebuilt modules fail
|
|
7
|
+
* to load, it reports the failure and sends the clients no update.
|
|
8
|
+
*/
|
|
9
|
+
import type { BuildResult } from "@eserstack/laroux-bundler/system";
|
|
10
|
+
import type { HMRManager } from "./hmr-manager.ts";
|
|
11
|
+
/**
|
|
12
|
+
* Message HMR clients get after a failed rebuild. It carries no error detail;
|
|
13
|
+
* the dev server log has the failing step and its error.
|
|
14
|
+
*/
|
|
15
|
+
export declare const REBUILD_FAILED_MESSAGE = "The rebuild failed; the dev server log names the failing step and its error";
|
|
16
|
+
/**
|
|
17
|
+
* Message HMR clients get when the rebuild succeeded but the server could not
|
|
18
|
+
* load its modules. It carries no error detail; the dev server log has it.
|
|
19
|
+
*/
|
|
20
|
+
export declare const RELOAD_FAILED_MESSAGE = "The server could not load the rebuilt modules; the dev server log has the error";
|
|
21
|
+
/** The parts of a build result the handler reads. */
|
|
22
|
+
export type RebuildOutcome = Pick<BuildResult, "success" | "buildId" | "duration" | "timestamp" | "changedFiles">;
|
|
23
|
+
/** The log calls the handler makes; a @eserstack/logging logger has them. */
|
|
24
|
+
export type RebuildLogger = {
|
|
25
|
+
/** Log a successful rebuild */
|
|
26
|
+
info(message: string): unknown;
|
|
27
|
+
/** Log a failed rebuild */
|
|
28
|
+
error(message: string): unknown;
|
|
29
|
+
/** A logger whose entries carry these attributes */
|
|
30
|
+
with(attributes: Record<string, unknown>): RebuildLogger;
|
|
31
|
+
};
|
|
32
|
+
/** Dependencies of {@link createRebuildHandler}. */
|
|
33
|
+
export type RebuildHandlerOptions = {
|
|
34
|
+
/** HMR clients to notify; null when HMR is off */
|
|
35
|
+
readonly hmr: Pick<HMRManager, "notifyUpdate" | "notifyError"> | null;
|
|
36
|
+
/**
|
|
37
|
+
* Loads the server modules of the rebuilt output, given the build id of
|
|
38
|
+
* the rebuild. Runs after a successful rebuild, before the clients update;
|
|
39
|
+
* when it rejects, the clients get an error instead of the update.
|
|
40
|
+
*/
|
|
41
|
+
readonly onRebuilt: (buildId: string) => Promise<void>;
|
|
42
|
+
/** Logger for the outcome of each rebuild */
|
|
43
|
+
readonly logger: RebuildLogger;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Create the callback that system.watch() calls after each rebuild. The
|
|
47
|
+
* watcher waits for the promise it returns before the next rebuild.
|
|
48
|
+
*
|
|
49
|
+
* @param options - HMR clients, the module loader and the logger
|
|
50
|
+
* @returns The callback for one watcher
|
|
51
|
+
*/
|
|
52
|
+
export declare function createRebuildHandler(options: RebuildHandlerOptions): (result: RebuildOutcome) => Promise<void>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Rebuild Handler
|
|
4
|
+
*
|
|
5
|
+
* Decides what the dev server does after each watch-mode rebuild: after one
|
|
6
|
+
* that succeeded, it loads the rebuilt server modules and then tells the HMR
|
|
7
|
+
* clients to update; after one that failed, or when the rebuilt modules fail
|
|
8
|
+
* to load, it reports the failure and sends the clients no update.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Message HMR clients get after a failed rebuild. It carries no error detail;
|
|
12
|
+
* the dev server log has the failing step and its error.
|
|
13
|
+
*/
|
|
14
|
+
export const REBUILD_FAILED_MESSAGE = "The rebuild failed; the dev server log names the failing step and its error";
|
|
15
|
+
/**
|
|
16
|
+
* Message HMR clients get when the rebuild succeeded but the server could not
|
|
17
|
+
* load its modules. It carries no error detail; the dev server log has it.
|
|
18
|
+
*/
|
|
19
|
+
export const RELOAD_FAILED_MESSAGE = "The server could not load the rebuilt modules; the dev server log has the error";
|
|
20
|
+
/**
|
|
21
|
+
* Create the callback that system.watch() calls after each rebuild. The
|
|
22
|
+
* watcher waits for the promise it returns before the next rebuild.
|
|
23
|
+
*
|
|
24
|
+
* @param options - HMR clients, the module loader and the logger
|
|
25
|
+
* @returns The callback for one watcher
|
|
26
|
+
*/
|
|
27
|
+
export function createRebuildHandler(options) {
|
|
28
|
+
const { hmr, onRebuilt, logger } = options;
|
|
29
|
+
return async (result) => {
|
|
30
|
+
if (!result.success) {
|
|
31
|
+
// The bundler has logged the failing step and its error; this line
|
|
32
|
+
// reports the outcome, and the clients keep the page they have.
|
|
33
|
+
await logger.error("✗ Rebuild failed, so no HMR update was sent; fix the error logged above and save to rebuild");
|
|
34
|
+
hmr?.notifyError(REBUILD_FAILED_MESSAGE);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
await onRebuilt(result.buildId);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
// Handled here: logged once, and the clients keep the page they have.
|
|
42
|
+
// ServerModules.load leaves the pages on the build loaded before.
|
|
43
|
+
await logger
|
|
44
|
+
.with({ buildId: result.buildId, error })
|
|
45
|
+
.error("✗ Loading the rebuilt server modules failed, so no HMR update was sent; fix the error and save to rebuild");
|
|
46
|
+
hmr?.notifyError(RELOAD_FAILED_MESSAGE);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
await logger.info(`✓ Compiled in ${result.duration.toFixed(0)}ms`);
|
|
50
|
+
hmr?.notifyUpdate(result.timestamp, result.changedFiles);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renderer Port Interface
|
|
3
|
+
* Defines the contract for framework-specific rendering implementations
|
|
4
|
+
*/
|
|
5
|
+
import type { AppConfig } from "@eserstack/laroux/config";
|
|
6
|
+
import type { Bundler } from "@eserstack/laroux-bundler";
|
|
7
|
+
/**
|
|
8
|
+
* Context passed to rendering methods
|
|
9
|
+
*/
|
|
10
|
+
export type RenderContext = {
|
|
11
|
+
/** Current URL pathname */
|
|
12
|
+
pathname: string;
|
|
13
|
+
/** Application configuration */
|
|
14
|
+
config: AppConfig;
|
|
15
|
+
/** Bundler instance for asset resolution */
|
|
16
|
+
bundler: Bundler;
|
|
17
|
+
/** Route parameters extracted from URL */
|
|
18
|
+
params: Record<string, string | string[]>;
|
|
19
|
+
/** Request object for headers, cookies, etc. */
|
|
20
|
+
request: Request;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Result of page rendering
|
|
24
|
+
*/
|
|
25
|
+
export type RenderResult = {
|
|
26
|
+
/** Rendered HTML content */
|
|
27
|
+
html: string;
|
|
28
|
+
/** Serialized RSC payload for hydration */
|
|
29
|
+
rscPayload?: string;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Renderer port interface
|
|
33
|
+
* Framework adapters (React, Vue, etc.) implement this interface
|
|
34
|
+
*/
|
|
35
|
+
export type Renderer = {
|
|
36
|
+
/** Renderer name for identification */
|
|
37
|
+
name: string;
|
|
38
|
+
/**
|
|
39
|
+
* Render a full HTML page with optional SSR
|
|
40
|
+
* @param Layout - Root layout component
|
|
41
|
+
* @param Page - Page component for current route
|
|
42
|
+
* @param context - Render context
|
|
43
|
+
*/
|
|
44
|
+
renderPage(Layout: unknown, Page: unknown, context: RenderContext): Promise<RenderResult>;
|
|
45
|
+
/**
|
|
46
|
+
* Render RSC streaming response
|
|
47
|
+
* @param Layout - Root layout component
|
|
48
|
+
* @param Page - Page component for current route
|
|
49
|
+
* @param context - Render context
|
|
50
|
+
*/
|
|
51
|
+
renderRSC(Layout: unknown, Page: unknown, context: RenderContext): Promise<Response>;
|
|
52
|
+
/**
|
|
53
|
+
* Generate bootstrap script for client hydration
|
|
54
|
+
* @param context - Render context
|
|
55
|
+
*/
|
|
56
|
+
generateBootstrapScript(context: RenderContext): string;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* No-op renderer implementation
|
|
60
|
+
* Used as default when no renderer is configured
|
|
61
|
+
*/
|
|
62
|
+
export declare const noopRenderer: Renderer;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Renderer Port Interface
|
|
4
|
+
* Defines the contract for framework-specific rendering implementations
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* No-op renderer implementation
|
|
8
|
+
* Used as default when no renderer is configured
|
|
9
|
+
*/
|
|
10
|
+
export const noopRenderer = {
|
|
11
|
+
name: "noop",
|
|
12
|
+
renderPage: () => Promise.resolve({ html: "" }),
|
|
13
|
+
renderRSC: () => Promise.resolve(new Response("")),
|
|
14
|
+
generateBootstrapScript: () => "",
|
|
15
|
+
};
|