@ecopages/core 0.2.0-beta.29 → 0.2.0-beta.30

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 (95) hide show
  1. package/README.md +36 -7
  2. package/package.json +2 -2
  3. package/src/adapters/README.md +6 -2
  4. package/src/adapters/abstract/segment-path-matcher.d.ts +6 -0
  5. package/src/adapters/abstract/segment-path-matcher.js +149 -0
  6. package/src/adapters/abstract/ws-pattern-matcher.d.ts +2 -50
  7. package/src/adapters/abstract/ws-pattern-matcher.js +5 -36
  8. package/src/adapters/{shared → bun}/bun-user-websocket-lifecycle.js +1 -1
  9. package/src/adapters/bun/create-app.d.ts +2 -2
  10. package/src/adapters/bun/create-app.js +2 -2
  11. package/src/adapters/bun/hmr-manager.d.ts +1 -1
  12. package/src/adapters/bun/hmr-manager.js +1 -1
  13. package/src/adapters/bun/index.d.ts +1 -1
  14. package/src/adapters/bun/index.js +25 -2
  15. package/src/adapters/bun/runtime-host.d.ts +1 -1
  16. package/src/adapters/bun/runtime-host.js +1 -1
  17. package/src/adapters/bun/server-adapter.d.ts +8 -25
  18. package/src/adapters/bun/server-adapter.js +21 -65
  19. package/src/adapters/bun/static-preview-host.d.ts +1 -1
  20. package/src/adapters/bun/static-preview-host.js +1 -1
  21. package/src/adapters/index.d.ts +1 -1
  22. package/src/adapters/index.js +25 -2
  23. package/src/adapters/node/create-app.d.ts +2 -2
  24. package/src/adapters/node/create-app.js +2 -2
  25. package/src/adapters/node/node-hmr-manager.d.ts +1 -1
  26. package/src/adapters/node/node-hmr-manager.js +1 -1
  27. package/src/adapters/node/runtime-host.d.ts +1 -1
  28. package/src/adapters/node/runtime-host.js +1 -1
  29. package/src/adapters/node/server-adapter.d.ts +2 -3
  30. package/src/adapters/node/server-adapter.js +15 -18
  31. package/src/adapters/node/static-preview-host.d.ts +1 -1
  32. package/src/adapters/node/static-preview-host.js +1 -1
  33. package/src/adapters/shared/{hmr-entrypoint-registrar.d.ts → hmr/hmr-entrypoint-registrar.d.ts} +1 -1
  34. package/src/adapters/shared/{hmr-entrypoint-registrar.js → hmr/hmr-entrypoint-registrar.js} +1 -1
  35. package/src/adapters/shared/{hmr-html-response.d.ts → hmr/hmr-html-response.d.ts} +1 -1
  36. package/src/adapters/shared/{shared-hmr-manager.d.ts → hmr/shared-hmr-manager.d.ts} +9 -8
  37. package/src/adapters/shared/{shared-hmr-manager.js → hmr/shared-hmr-manager.js} +41 -15
  38. package/src/adapters/shared/http/api-request-pipeline.d.ts +23 -0
  39. package/src/adapters/shared/http/api-request-pipeline.js +129 -0
  40. package/src/adapters/shared/{api-response.d.ts → http/api-response.d.ts} +1 -1
  41. package/src/adapters/shared/{api-response.js → http/api-response.js} +6 -23
  42. package/src/adapters/shared/http/create-body-response.d.ts +12 -0
  43. package/src/adapters/shared/http/create-body-response.js +23 -0
  44. package/src/adapters/shared/http/define-api-handler.d.ts +90 -0
  45. package/src/adapters/shared/http/define-api-handler.js +63 -0
  46. package/src/adapters/shared/{explicit-static-render-preparation.d.ts → http/explicit-static-render-preparation.d.ts} +3 -3
  47. package/src/adapters/shared/{explicit-static-route-matcher.d.ts → http/explicit-static-route-matcher.d.ts} +3 -9
  48. package/src/adapters/shared/{explicit-static-route-matcher.js → http/explicit-static-route-matcher.js} +3 -38
  49. package/src/adapters/shared/{file-route-middleware-pipeline.d.ts → http/file-route-middleware-pipeline.d.ts} +2 -2
  50. package/src/adapters/shared/{file-route-middleware-pipeline.js → http/file-route-middleware-pipeline.js} +10 -22
  51. package/src/adapters/shared/{fs-server-response-factory.d.ts → http/fs-server-response-factory.d.ts} +2 -2
  52. package/src/adapters/shared/{fs-server-response-factory.js → http/fs-server-response-factory.js} +2 -2
  53. package/src/adapters/shared/{fs-server-response-matcher.d.ts → http/fs-server-response-matcher.d.ts} +5 -5
  54. package/src/adapters/shared/{fs-server-response-matcher.js → http/fs-server-response-matcher.js} +5 -5
  55. package/src/adapters/shared/http/run-middleware-chain.d.ts +5 -0
  56. package/src/adapters/shared/http/run-middleware-chain.js +17 -0
  57. package/src/adapters/shared/{application-adapter.d.ts → runtime/application-adapter.d.ts} +2 -2
  58. package/src/adapters/shared/{application-adapter.js → runtime/application-adapter.js} +1 -1
  59. package/src/adapters/shared/{render-context.d.ts → runtime/render-context.d.ts} +2 -2
  60. package/src/adapters/shared/{render-context.js → runtime/render-context.js} +8 -17
  61. package/src/adapters/shared/{runtime-app-bootstrap.d.ts → runtime/runtime-app-bootstrap.d.ts} +2 -2
  62. package/src/adapters/shared/{runtime-app-bootstrap.js → runtime/runtime-app-bootstrap.js} +1 -1
  63. package/src/adapters/shared/{runtime-server-lifecycle.d.ts → runtime/runtime-server-lifecycle.d.ts} +13 -13
  64. package/src/adapters/shared/{runtime-server-lifecycle.js → runtime/runtime-server-lifecycle.js} +22 -15
  65. package/src/adapters/shared/{server-adapter.d.ts → runtime/server-adapter.d.ts} +20 -48
  66. package/src/adapters/shared/runtime/server-adapter.js +226 -0
  67. package/src/adapters/shared/{server-route-handler.d.ts → runtime/server-route-handler.d.ts} +6 -36
  68. package/src/adapters/shared/{server-route-handler.js → runtime/server-route-handler.js} +6 -47
  69. package/src/adapters/shared/{server-static-builder.d.ts → runtime/server-static-builder.d.ts} +6 -6
  70. package/src/adapters/shared/{server-static-builder.js → runtime/server-static-builder.js} +8 -8
  71. package/src/adapters/shared/{static-preview-host.d.ts → runtime/static-preview-host.d.ts} +1 -1
  72. package/src/adapters/shared/{node-http-websocket-upgrades.d.ts → ws/node-http-websocket-upgrades.d.ts} +1 -1
  73. package/src/adapters/shared/{node-http-websocket-upgrades.js → ws/node-http-websocket-upgrades.js} +2 -2
  74. package/src/adapters/shared/{websocket-lifecycle.d.ts → ws/websocket-lifecycle.d.ts} +1 -1
  75. package/src/adapters/shared/{websocket-lifecycle.js → ws/websocket-lifecycle.js} +1 -1
  76. package/src/build/app-build-manifest-runtime.d.ts +4 -0
  77. package/src/build/app-build-manifest-runtime.js +19 -9
  78. package/src/index.d.ts +1 -1
  79. package/src/index.js +24 -1
  80. package/src/static-site-generator/static-site-generator.js +1 -1
  81. package/src/types/internal-types.d.ts +8 -2
  82. package/src/types/public-types.d.ts +9 -1
  83. package/src/adapters/shared/define-api-handler.d.ts +0 -25
  84. package/src/adapters/shared/define-api-handler.js +0 -15
  85. package/src/adapters/shared/server-adapter.js +0 -452
  86. /package/src/adapters/{shared → bun}/bun-user-websocket-lifecycle.d.ts +0 -0
  87. /package/src/adapters/shared/{hmr-html-response.js → hmr/hmr-html-response.js} +0 -0
  88. /package/src/adapters/shared/{explicit-static-render-preparation.js → http/explicit-static-render-preparation.js} +0 -0
  89. /package/src/adapters/shared/{copy-runtime-public-dir.d.ts → runtime/copy-runtime-public-dir.d.ts} +0 -0
  90. /package/src/adapters/shared/{copy-runtime-public-dir.js → runtime/copy-runtime-public-dir.js} +0 -0
  91. /package/src/adapters/shared/{port-manager.d.ts → runtime/port-manager.d.ts} +0 -0
  92. /package/src/adapters/shared/{port-manager.js → runtime/port-manager.js} +0 -0
  93. /package/src/adapters/shared/{runtime-host.d.ts → runtime/runtime-host.d.ts} +0 -0
  94. /package/src/adapters/shared/{runtime-host.js → runtime/runtime-host.js} +0 -0
  95. /package/src/adapters/shared/{static-preview-host.js → runtime/static-preview-host.js} +0 -0
@@ -1,5 +1,5 @@
1
- import type { RenderContext } from '../../types/public-types.js';
2
- import type { AnyIntegrationPlugin } from '../../plugins/integration-plugin.js';
1
+ import type { RenderContext } from '../../../types/public-types.js';
2
+ import type { AnyIntegrationPlugin } from '../../../plugins/integration-plugin.js';
3
3
  export interface CreateRenderContextOptions {
4
4
  integrations: AnyIntegrationPlugin[];
5
5
  rendererModules?: unknown;
@@ -1,5 +1,6 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { invariant } from "../../utils/invariant.js";
2
+ import { invariant } from "../../../utils/invariant.js";
3
+ import { createBodyResponse } from "../http/create-body-response.js";
3
4
  function resolveServerModulePath(filePath) {
4
5
  return filePath instanceof URL ? fileURLToPath(filePath) : filePath;
5
6
  }
@@ -64,25 +65,15 @@ function createRenderContext(options) {
64
65
  return renderer.renderToResponse(view, mergedProps, ctx);
65
66
  },
66
67
  json(data, responseOptions) {
67
- const headers = new Headers({ "Content-Type": "application/json; charset=utf-8" });
68
- if (responseOptions?.headers) {
69
- const incomingHeaders = new Headers(responseOptions.headers);
70
- incomingHeaders.forEach((value, key) => headers.set(key, value));
71
- }
72
- return new Response(JSON.stringify(data), {
73
- status: responseOptions?.status ?? 200,
74
- headers
68
+ return createBodyResponse("json", data, {
69
+ status: responseOptions?.status,
70
+ headers: responseOptions?.headers
75
71
  });
76
72
  },
77
73
  html(content, responseOptions) {
78
- const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" });
79
- if (responseOptions?.headers) {
80
- const incomingHeaders = new Headers(responseOptions.headers);
81
- incomingHeaders.forEach((value, key) => headers.set(key, value));
82
- }
83
- return new Response(content, {
84
- status: responseOptions?.status ?? 200,
85
- headers
74
+ return createBodyResponse("html", content, {
75
+ status: responseOptions?.status,
76
+ headers: responseOptions?.headers
86
77
  });
87
78
  }
88
79
  };
@@ -1,5 +1,5 @@
1
- import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
2
- import type { EcoPagesAppConfig } from '../../types/internal-types.js';
1
+ import type { ReturnParseCliArgs } from '../../../utils/parse-cli-args.js';
2
+ import type { EcoPagesAppConfig } from '../../../types/internal-types.js';
3
3
  export type RuntimeBinding = {
4
4
  preferredPort: number;
5
5
  preferredHostname: string;
@@ -1,4 +1,4 @@
1
- import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from "../../config/constants.js";
1
+ import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from "../../../config/constants.js";
2
2
  function normalizeOriginHostname(hostname) {
3
3
  if (hostname.includes(":") && !hostname.startsWith("[") && !hostname.endsWith("]")) {
4
4
  return `[${hostname}]`;
@@ -1,6 +1,6 @@
1
- import type { EcoPagesAppConfig } from '../../types/internal-types.js';
2
- import type { IHmrManager } from '../../types/public-types.js';
3
- import type { ProjectWatcher } from '../../watchers/project-watcher.js';
1
+ import type { EcoPagesAppConfig } from '../../../types/internal-types.js';
2
+ import type { IHmrManager } from '../../../types/public-types.js';
3
+ import type { ProjectWatcher } from '../../../watchers/project-watcher.js';
4
4
  /**
5
5
  * Copies source `public/` into dist and ensures the resolved assets directory exists.
6
6
  */
@@ -14,17 +14,17 @@ export declare function prepareRuntimePublicDir(appConfig: EcoPagesAppConfig): v
14
14
  */
15
15
  export declare function attachHmrToIntegrations(appConfig: EcoPagesAppConfig, hmrManager: IHmrManager): void;
16
16
  /**
17
- * @deprecated Use {@link attachHmrToIntegrations} instead.
18
- */
19
- export declare function wireIntegrationHmrManagers(appConfig: EcoPagesAppConfig, hmrManager: IHmrManager): void;
20
- /**
21
- * Injects the dev HMR runtime into adapter-level HTML responses when watch mode is active.
17
+ * Starts background activation of every configured integration after watch-mode HMR is ready.
18
+ *
19
+ * @remarks
20
+ * Fire-and-forget: overlaps with watcher setup so first-page render can join the same
21
+ * coalesced {@link ensureIntegrationRuntimeReady} promise instead of paying a cold vendor build.
22
+ * Failures are logged and do not crash the server.
22
23
  */
23
- export declare function maybeInjectAdapterHmrHtmlResponse(response: Response, options: {
24
- watch: boolean;
25
- hmrManager?: Pick<IHmrManager, 'isEnabled'>;
26
- hostOwnsDevClient: boolean;
27
- }): Promise<Response>;
24
+ export declare function startConfiguredIntegrationRuntimePrewarm(options: {
25
+ appConfig: EcoPagesAppConfig;
26
+ runtimeOrigin: string;
27
+ }): void;
28
28
  /**
29
29
  * Releases shared dev resources in a consistent order across server adapters.
30
30
  *
@@ -1,11 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { fileSystem } from "@ecopages/file-system";
3
- import { RESOLVED_ASSETS_DIR } from "../../config/constants.js";
4
- import { disposeAppBuildRuntime } from "../../build/runtime/build-runtime.js";
3
+ import { RESOLVED_ASSETS_DIR } from "../../../config/constants.js";
4
+ import { disposeAppBuildRuntime } from "../../../build/runtime/build-runtime.js";
5
+ import { ensureIntegrationRuntimeReady } from "../../../build/app-build-manifest-runtime.js";
6
+ import { appLogger } from "../../../global/app-logger.js";
5
7
  import { copyRuntimePublicDirIfChanged } from "./copy-runtime-public-dir.js";
6
- import { clearAppDevClientBridge } from "../../dev/client-bridge-registry.js";
7
- import { clearAppHmrManager } from "../../dev/hmr-manager-registry.js";
8
- import { injectHmrRuntimeIntoHtmlResponse, isHtmlResponse, shouldInjectHmrHtmlResponse } from "./hmr-html-response.js";
8
+ import { clearAppDevClientBridge } from "../../../dev/client-bridge-registry.js";
9
+ import { clearAppHmrManager } from "../../../dev/hmr-manager-registry.js";
9
10
  function prepareRuntimePublicDir(appConfig) {
10
11
  const srcPublicDir = path.join(appConfig.rootDir, appConfig.srcDir, appConfig.publicDir);
11
12
  if (fileSystem.exists(srcPublicDir)) {
@@ -23,14 +24,21 @@ function attachHmrToIntegrations(appConfig, hmrManager) {
23
24
  integration.setHmrManager(hmrManager);
24
25
  }
25
26
  }
26
- function wireIntegrationHmrManagers(appConfig, hmrManager) {
27
- attachHmrToIntegrations(appConfig, hmrManager);
28
- }
29
- async function maybeInjectAdapterHmrHtmlResponse(response, options) {
30
- if (shouldInjectHmrHtmlResponse(options.watch, options.hmrManager, options.hostOwnsDevClient) && isHtmlResponse(response)) {
31
- return injectHmrRuntimeIntoHtmlResponse(response);
32
- }
33
- return response;
27
+ function startConfiguredIntegrationRuntimePrewarm(options) {
28
+ const { appConfig, runtimeOrigin } = options;
29
+ void Promise.all(
30
+ appConfig.integrations.map(
31
+ (integration) => ensureIntegrationRuntimeReady({
32
+ appConfig,
33
+ integrationName: integration.name,
34
+ runtimeOrigin
35
+ })
36
+ )
37
+ ).catch((error) => {
38
+ appLogger.error(
39
+ `Failed to prewarm integration runtimes: ${error instanceof Error ? error.message : String(error)}`
40
+ );
41
+ });
34
42
  }
35
43
  async function disposeDevResources(options) {
36
44
  await options.projectWatcher?.close();
@@ -44,7 +52,6 @@ async function disposeDevResources(options) {
44
52
  export {
45
53
  attachHmrToIntegrations,
46
54
  disposeDevResources,
47
- maybeInjectAdapterHmrHtmlResponse,
48
55
  prepareRuntimePublicDir,
49
- wireIntegrationHmrManagers
56
+ startConfiguredIntegrationRuntimePrewarm
50
57
  };
@@ -1,18 +1,20 @@
1
- import { AbstractServerAdapter } from '../abstract/server-adapter.js';
2
- import type { ServerAdapterOptions, ServerAdapterResult } from '../abstract/server-adapter.js';
3
- import { RouteRendererFactory } from '../../route-renderer/route-renderer.js';
4
- import { RouteRegistry } from '../../router/server/route-registry.js';
5
- import { SchemaValidationService } from '../../services/validation/schema-validation-service.js';
6
- import { StaticSiteGenerator } from '../../static-site-generator/static-site-generator.js';
1
+ import { AbstractServerAdapter } from '../../abstract/server-adapter.js';
2
+ import type { ServerAdapterOptions, ServerAdapterResult } from '../../abstract/server-adapter.js';
3
+ import { RouteRendererFactory } from '../../../route-renderer/route-renderer.js';
4
+ import { RouteRegistry } from '../../../router/server/route-registry.js';
5
+ import { SchemaValidationService } from '../../../services/validation/schema-validation-service.js';
6
+ import { StaticSiteGenerator } from '../../../static-site-generator/static-site-generator.js';
7
7
  import { ServerStaticBuilder } from './server-static-builder.js';
8
- import { FileSystemResponseMatcher } from './fs-server-response-matcher.js';
8
+ import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
9
9
  import { ServerRouteHandler } from './server-route-handler.js';
10
- import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext, StaticRoute } from '../../types/public-types.js';
11
- type SharedRequestContext = {
10
+ import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
11
+ import type { ApiHandler, CacheInvalidator, ErrorHandler, IHmrManager, RenderContext, StaticRoute } from '../../../types/public-types.js';
12
+ type SharedHmrAssetManager = IHmrManager;
13
+ type SharedRequestContext<TServer = unknown> = {
12
14
  apiHandlers: ApiHandler[];
13
- errorHandler?: ErrorHandler;
14
- serverInstance?: any;
15
- hmrManager?: any;
15
+ errorHandler?: ErrorHandler<Request, TServer>;
16
+ serverInstance?: TServer;
17
+ hmrManager?: SharedHmrAssetManager;
16
18
  };
17
19
  export declare abstract class SharedServerAdapter<TOptions extends ServerAdapterOptions, TResult extends ServerAdapterResult> extends AbstractServerAdapter<TOptions, TResult> {
18
20
  protected router: RouteRegistry;
@@ -22,15 +24,16 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
22
24
  protected staticSiteGenerator: StaticSiteGenerator;
23
25
  protected staticBuilder: ServerStaticBuilder;
24
26
  protected schemaValidator: SchemaValidationService;
27
+ protected readonly apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
25
28
  protected hostOwnsDevClient: boolean;
26
29
  protected initializeSharedRouteHandling(options: {
27
30
  staticRoutes: StaticRoute[];
28
- hmrManager?: any;
31
+ hmrManager?: SharedHmrAssetManager;
29
32
  }): Promise<void>;
30
33
  private ensureRouteRendererFactory;
31
34
  protected createSharedWatchRefreshCallback(options: {
32
35
  staticRoutes: StaticRoute[];
33
- hmrManager?: any;
36
+ hmrManager?: SharedHmrAssetManager;
34
37
  onRoutesReady?: () => Promise<void> | void;
35
38
  onError?: (error: Error) => Promise<void> | void;
36
39
  }): () => Promise<void>;
@@ -52,54 +55,23 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
52
55
  * 2. How to match logical routes to physical filesystem artifacts via `FileSystemResponseMatcher`
53
56
  * 3. Whether to serve the response from the embedded `PageCacheService` or generate it fresh on the fly.
54
57
  *
55
- * Because `HmrManager` implementations rely heavily on runtime-specific WebSocket APIs (e.g. Bun.serve Websockets vs Node WS),
56
- * we leave it untyped (`any`) here at the common denominator core.
57
- *
58
58
  * @param staticRoutes - A map of explicitly served static assets.
59
59
  * @param hmrManager - The runtime-specific Hot Module Replacement orchestrator (if watching).
60
60
  */
61
- protected configureSharedResponseHandlers(staticRoutes: StaticRoute[], hmrManager?: any): void;
61
+ protected configureSharedResponseHandlers(staticRoutes: StaticRoute[], hmrManager?: IHmrManager): void;
62
62
  private createSharedResponseHandlerDependencies;
63
63
  private createSharedPageCacheService;
64
64
  protected getCacheService(): CacheInvalidator | null;
65
65
  protected getRenderContext(): RenderContext;
66
- /**
67
- * Executes an Application Programming Interface (API) handler in an environment-agnostic manner.
68
- *
69
- * API routes in Ecopages are universally written using standard WinterCG `Request` and `Response` objects.
70
- * This execution pipeline takes the raw `Request`, extracts its dynamic segments, runs our high-speed JSON schema
71
- * validator against the body/query/headers, and triggers the developer's middleware chain sequentially.
72
- *
73
- * If the execution throws an error, it is gracefully caught, logged, and mutated into a standardized Http error payload,
74
- * ensuring the consuming client receives a parsable response even upon internal catastrophic failure.
75
- *
76
- * @param request - The incoming Web standard `Request`.
77
- * @param params - The extracted dynamic URL parameters (e.g., `{ id: '123' }`).
78
- * @param routeConfig - The user-defined API handler object containing their business logic (`handler`) and `middleware`.
79
- * @param serverInstance - Untyped reference to the underlying native server instance (BunServer/NodeServer) for potential escape hatches.
80
- * @param errorHandler - Optional global error trap defined in project configuration.
81
- * @returns The resulting Web standard `Response` constructed by the user's handler.
82
- */
83
- protected executeApiHandler(request: Request, params: Record<string, string | string[]>, routeConfig: ApiHandler, serverInstance: any, errorHandler?: ErrorHandler): Promise<Response>;
84
- private createApiHandlerContext;
85
- private normalizeApiParams;
86
- private applyApiRequestSchema;
87
- private runApiMiddlewareChain;
88
- private normalizePath;
89
- private matchApiPath;
90
- private getApiPathScore;
91
- protected matchApiHandler(request: Request, apiHandlers: ApiHandler[]): {
92
- routeConfig: ApiHandler;
93
- params: Record<string, string | string[]>;
94
- } | null;
95
66
  private tryHandleSharedHmrRequest;
67
+ private injectSharedHmrHtmlResponse;
96
68
  private tryHandleSharedApiRequest;
97
69
  /**
98
70
  * Universally processes an incoming WinterCG Web standard Request.
99
71
  *
100
72
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
101
73
  * 2. Checks if the incoming request matches any parsed API route schemas.
102
- * - Routes through `executeApiHandler` which performs strict validation.
74
+ * - Routes through `ApiRequestPipeline` which performs strict validation.
103
75
  * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
104
76
  *
105
77
  * Both Bun and Node bindings fall back to this exact function once they have mapped their
@@ -0,0 +1,226 @@
1
+ import path from "node:path";
2
+ import { AbstractServerAdapter } from "../../abstract/server-adapter.js";
3
+ import { RouteRendererFactory } from "../../../route-renderer/route-renderer.js";
4
+ import { RouteRegistry } from "../../../router/server/route-registry.js";
5
+ import { startupTrace } from "../../../diagnostics/startup-trace.js";
6
+ import { requestBuildDedupe } from "../../../diagnostics/request-build-dedupe.js";
7
+ import { MemoryCacheStore } from "../../../services/cache/memory-cache-store.js";
8
+ import { PageCacheService } from "../../../services/cache/page-cache-service.js";
9
+ import { SchemaValidationService } from "../../../services/validation/schema-validation-service.js";
10
+ import { StaticSiteGenerator } from "../../../static-site-generator/static-site-generator.js";
11
+ import { ServerStaticBuilder } from "./server-static-builder.js";
12
+ import { ExplicitStaticRouteMatcher } from "../http/explicit-static-route-matcher.js";
13
+ import { FileSystemServerResponseFactory } from "../http/fs-server-response-factory.js";
14
+ import { FileSystemResponseMatcher } from "../http/fs-server-response-matcher.js";
15
+ import { ServerRouteHandler } from "./server-route-handler.js";
16
+ import { createRenderContext } from "./render-context.js";
17
+ import { ApiRequestPipeline } from "../http/api-request-pipeline.js";
18
+ import {
19
+ injectHmrRuntimeIntoHtmlResponse,
20
+ isHtmlResponse,
21
+ shouldInjectHmrHtmlResponse
22
+ } from "../hmr/hmr-html-response.js";
23
+ import { getAppServerModuleTranspiler } from "../../../services/module-loading/app-server-module-transpiler.service.js";
24
+ import { resolveInternalExecutionDir } from "../../../utils/resolve-work-dir.js";
25
+ class SharedServerAdapter extends AbstractServerAdapter {
26
+ router;
27
+ fileSystemResponseMatcher;
28
+ routeRendererFactory;
29
+ routeHandler;
30
+ staticSiteGenerator;
31
+ staticBuilder;
32
+ schemaValidator = new SchemaValidationService();
33
+ apiRequestPipeline = new ApiRequestPipeline({
34
+ schemaValidator: this.schemaValidator,
35
+ getRenderContext: () => this.getRenderContext(),
36
+ getCacheService: () => this.getCacheService()
37
+ });
38
+ hostOwnsDevClient = false;
39
+ async initializeSharedRouteHandling(options) {
40
+ this.ensureRouteRendererFactory();
41
+ await this.initSharedRouter();
42
+ this.configureSharedResponseHandlers(options.staticRoutes, options.hmrManager);
43
+ }
44
+ ensureRouteRendererFactory() {
45
+ if (this.routeRendererFactory) {
46
+ return;
47
+ }
48
+ this.routeRendererFactory = new RouteRendererFactory({
49
+ appConfig: this.appConfig,
50
+ rendererModules: this.appConfig.runtime?.rendererModuleContext,
51
+ runtimeOrigin: this.runtimeOrigin
52
+ });
53
+ }
54
+ createSharedWatchRefreshCallback(options) {
55
+ return async () => {
56
+ try {
57
+ await this.initializeSharedRouteHandling({
58
+ staticRoutes: options.staticRoutes,
59
+ hmrManager: options.hmrManager
60
+ });
61
+ if (options.onRoutesReady) {
62
+ await options.onRoutesReady();
63
+ }
64
+ } catch (error) {
65
+ if (options.onError) {
66
+ await options.onError(error instanceof Error ? error : new Error(String(error)));
67
+ return;
68
+ }
69
+ throw error;
70
+ }
71
+ };
72
+ }
73
+ /**
74
+ * Scans the filesystem and dynamically constructs the Route Registry.
75
+ *
76
+ * This process runs identically across both Bun and Node wrappers. It analyzes the configured pages
77
+ * directory, building a map of all available UI routes and API endpoints.
78
+ * The resulting `RouteRegistry` instance becomes the central nervous system for mapping WinterCG incoming
79
+ * Web Requests (`Request`) to their corresponding internal execution paths.
80
+ */
81
+ async initSharedRouter() {
82
+ startupTrace.markPhaseStart("route-registry");
83
+ this.router = new RouteRegistry({
84
+ pagesDir: path.join(this.appConfig.rootDir, this.appConfig.srcDir, this.appConfig.pagesDir),
85
+ appConfig: this.appConfig,
86
+ origin: this.runtimeOrigin,
87
+ templatesExt: this.appConfig.templatesExt,
88
+ buildMode: !this.options?.watch,
89
+ pageModuleAdapter: this.createRouteRegistryPageModuleAdapter()
90
+ });
91
+ await this.router.init();
92
+ startupTrace.markPhaseEnd("route-registry");
93
+ }
94
+ createRouteRegistryPageModuleAdapter() {
95
+ this.ensureRouteRendererFactory();
96
+ return {
97
+ loadPageModule: async (filePath) => {
98
+ const module = await this.routeRendererFactory.getPageRenderer(filePath).loadPageModule(filePath);
99
+ const page = module.default;
100
+ return {
101
+ staticPaths: page?.staticPaths ?? module.getStaticPaths,
102
+ staticProps: page?.staticProps ?? module.getStaticProps
103
+ };
104
+ }
105
+ };
106
+ }
107
+ /**
108
+ * Sets up the unified rendering pipeline and response matching chain.
109
+ *
110
+ * It bridges several sub-systems together so that when an incoming request is received, the adapter knows:
111
+ * 1. How to render React/Lit pages via `RouteRendererFactory`
112
+ * 2. How to match logical routes to physical filesystem artifacts via `FileSystemResponseMatcher`
113
+ * 3. Whether to serve the response from the embedded `PageCacheService` or generate it fresh on the fly.
114
+ *
115
+ * @param staticRoutes - A map of explicitly served static assets.
116
+ * @param hmrManager - The runtime-specific Hot Module Replacement orchestrator (if watching).
117
+ */
118
+ configureSharedResponseHandlers(staticRoutes, hmrManager) {
119
+ this.ensureRouteRendererFactory();
120
+ const { fileSystemResponseMatcher, explicitStaticRouteMatcher } = this.createSharedResponseHandlerDependencies(staticRoutes);
121
+ this.fileSystemResponseMatcher = fileSystemResponseMatcher;
122
+ this.routeHandler = new ServerRouteHandler({
123
+ router: this.router,
124
+ fileSystemResponseMatcher: this.fileSystemResponseMatcher,
125
+ explicitStaticRouteMatcher,
126
+ hmrManager
127
+ });
128
+ }
129
+ createSharedResponseHandlerDependencies(staticRoutes) {
130
+ const fileSystemResponseFactory = new FileSystemServerResponseFactory({
131
+ options: {
132
+ watchMode: !!this.options?.watch
133
+ }
134
+ });
135
+ const cacheService = this.createSharedPageCacheService();
136
+ const fileSystemResponseMatcher = new FileSystemResponseMatcher({
137
+ appConfig: this.appConfig,
138
+ assetPrefix: path.join(this.appConfig.rootDir, this.appConfig.distDir),
139
+ router: this.router,
140
+ routeRendererFactory: this.routeRendererFactory,
141
+ fileSystemResponseFactory,
142
+ cacheService,
143
+ defaultCacheStrategy: this.appConfig.cache?.defaultStrategy ?? "static"
144
+ });
145
+ return {
146
+ cacheService,
147
+ fileSystemResponseMatcher,
148
+ explicitStaticRouteMatcher: staticRoutes.length > 0 ? new ExplicitStaticRouteMatcher({
149
+ appConfig: this.appConfig,
150
+ routeRendererFactory: this.routeRendererFactory,
151
+ staticRoutes
152
+ }) : void 0
153
+ };
154
+ }
155
+ createSharedPageCacheService() {
156
+ const cacheConfig = this.appConfig.cache;
157
+ const isCacheEnabled = cacheConfig?.enabled ?? !this.options?.watch;
158
+ if (!isCacheEnabled) {
159
+ return null;
160
+ }
161
+ const store = cacheConfig?.store === "memory" || !cacheConfig?.store ? new MemoryCacheStore({ maxEntries: cacheConfig?.maxEntries }) : cacheConfig.store;
162
+ return new PageCacheService({ store, enabled: true });
163
+ }
164
+ getCacheService() {
165
+ return this.fileSystemResponseMatcher?.getCacheService() ?? null;
166
+ }
167
+ getRenderContext() {
168
+ const serverModuleTranspiler = getAppServerModuleTranspiler(this.appConfig);
169
+ return createRenderContext({
170
+ integrations: this.appConfig.integrations,
171
+ rendererModules: this.appConfig.runtime?.rendererModuleContext,
172
+ importServerModule: async (filePath) => await serverModuleTranspiler.importModule({
173
+ filePath,
174
+ outdir: path.join(resolveInternalExecutionDir(this.appConfig), ".server-modules"),
175
+ externalPackages: true
176
+ })
177
+ });
178
+ }
179
+ tryHandleSharedHmrRequest(request, context) {
180
+ return context.hmrManager?.tryHandleAssetRequest(request) ?? null;
181
+ }
182
+ async injectSharedHmrHtmlResponse(response, context) {
183
+ if (shouldInjectHmrHtmlResponse(this.options?.watch ?? false, context.hmrManager, this.hostOwnsDevClient) && isHtmlResponse(response)) {
184
+ return injectHmrRuntimeIntoHtmlResponse(response);
185
+ }
186
+ return response;
187
+ }
188
+ async tryHandleSharedApiRequest(request, context) {
189
+ return await this.apiRequestPipeline.tryHandle(
190
+ request,
191
+ context.apiHandlers,
192
+ context.serverInstance,
193
+ context.errorHandler
194
+ );
195
+ }
196
+ /**
197
+ * Universally processes an incoming WinterCG Web standard Request.
198
+ *
199
+ * 1. Resolves static Hot Module Replacement runtime blobs if development.
200
+ * 2. Checks if the incoming request matches any parsed API route schemas.
201
+ * - Routes through `ApiRequestPipeline` which performs strict validation.
202
+ * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
203
+ *
204
+ * Both Bun and Node bindings fall back to this exact function once they have mapped their
205
+ * native HTTP objects into Web Standard Requests.
206
+ */
207
+ async handleSharedRequest(request, context) {
208
+ return requestBuildDedupe.run(
209
+ () => startupTrace.traceFirstRequest(request, async () => {
210
+ const hmrResponse = this.tryHandleSharedHmrRequest(request, context);
211
+ if (hmrResponse) {
212
+ return hmrResponse;
213
+ }
214
+ const apiResponse = await this.tryHandleSharedApiRequest(request, context);
215
+ if (apiResponse) {
216
+ return await this.injectSharedHmrHtmlResponse(apiResponse, context);
217
+ }
218
+ const routeResponse = await this.routeHandler.handleResponse(request);
219
+ return await this.injectSharedHmrHtmlResponse(routeResponse, context);
220
+ })
221
+ );
222
+ }
223
+ }
224
+ export {
225
+ SharedServerAdapter
226
+ };
@@ -1,7 +1,7 @@
1
- import type { IHmrManager } from '../../types/public-types.js';
2
- import type { RouteRegistry } from '../../router/server/route-registry.js';
3
- import type { ExplicitStaticRouteMatcher } from './explicit-static-route-matcher.js';
4
- import type { FileSystemResponseMatcher } from './fs-server-response-matcher.js';
1
+ import type { IHmrManager } from '../../../types/public-types.js';
2
+ import type { RouteRegistry } from '../../../router/server/route-registry.js';
3
+ import type { ExplicitStaticRouteMatcher } from '../http/explicit-static-route-matcher.js';
4
+ import type { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
5
5
  /**
6
6
  * Configuration parameters for ServerRouteHandler.
7
7
  */
@@ -12,12 +12,8 @@ export interface ServerRouteHandlerParams {
12
12
  fileSystemResponseMatcher: FileSystemResponseMatcher;
13
13
  /** Optional matcher for explicit static routes like processed images or sitemaps. */
14
14
  explicitStaticRouteMatcher?: ExplicitStaticRouteMatcher;
15
- /** Enable watch mode for development. */
16
- watch?: boolean;
17
15
  /** HMR manager for broadcasting hot module reload events in development. */
18
16
  hmrManager?: IHmrManager;
19
- /** When true, the host dev server owns browser dev-client bootstrap. */
20
- hostOwnsDevClient?: boolean;
21
17
  }
22
18
  /**
23
19
  * Handles HTTP requests and routing for the server.
@@ -27,34 +23,18 @@ export interface ServerRouteHandlerParams {
27
23
  * 2. File-based routes without extensions (application routes)
28
24
  * 3. Static file fallback (lowest priority - disk serving)
29
25
  *
30
- * In development mode, it also injects HMR scripts into HTML responses.
31
26
  */
32
27
  export declare class ServerRouteHandler {
33
28
  private readonly router;
34
29
  private readonly fileSystemResponseMatcher;
35
30
  private readonly explicitStaticRouteMatcher?;
36
- private readonly watch;
37
31
  private readonly hmrManager?;
38
- private readonly hostOwnsDevClient;
39
32
  /**
40
33
  * Creates a new ServerRouteHandler instance.
41
34
  *
42
35
  * @param params - Configuration parameters
43
36
  */
44
- constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher, watch, hmrManager, hostOwnsDevClient, }: ServerRouteHandlerParams);
45
- /**
46
- * Determines if HMR script should be injected.
47
- *
48
- * @returns true if in watch mode and HMR manager is enabled
49
- */
50
- shouldInjectHmrScript(): boolean;
51
- /**
52
- * Checks if a response contains HTML content.
53
- *
54
- * @param response - The HTTP response to check
55
- * @returns true if Content-Type header starts with 'text/html'
56
- */
57
- isHtmlResponse(response: Response): boolean;
37
+ constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher, hmrManager, }: ServerRouteHandlerParams);
58
38
  /**
59
39
  * Handles HTTP requests from the router adapter.
60
40
  *
@@ -64,19 +44,9 @@ export declare class ServerRouteHandler {
64
44
  * 3. Fall back to static file serving from disk
65
45
  *
66
46
  * @param request - The incoming HTTP request
67
- * @returns HTTP response, potentially with injected HMR script in dev mode
47
+ * @returns HTTP response for the matched route
68
48
  */
69
49
  handleResponse(request: Request): Promise<Response>;
70
- /**
71
- * Injects HMR script into HTML responses in development mode.
72
- *
73
- * The script is inserted before the closing </html> tag to enable
74
- * hot module reloading without full page refreshes.
75
- *
76
- * @param response - The HTTP response to potentially modify
77
- * @returns Original response or modified response with HMR script
78
- */
79
- private maybeInjectHmrScript;
80
50
  /**
81
51
  * Handles requests that do not match any routes.
82
52
  *