@ecopages/core 0.3.2 → 0.4.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 (32) hide show
  1. package/README.md +17 -1
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +19 -19
  4. package/src/adapters/node/create-app.js +26 -40
  5. package/src/adapters/node/dev-session.d.ts +3 -1
  6. package/src/adapters/node/dev-session.js +4 -1
  7. package/src/adapters/node/server-adapter.js +5 -1
  8. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  9. package/src/adapters/shared/http/define-api-handler.js +15 -1
  10. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  11. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  12. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  13. package/src/adapters/shared/runtime/server-request-pipeline.js +45 -12
  14. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  15. package/src/adapters/shared/runtime/server-route-handler.js +12 -6
  16. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  17. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  18. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  19. package/src/build/server-bundle-deploy-manifest.js +1 -1
  20. package/src/config/assembly/finalize-config.js +5 -0
  21. package/src/index.d.ts +1 -1
  22. package/src/index.js +1 -1
  23. package/src/router/server/route-registry.d.ts +18 -9
  24. package/src/router/server/route-registry.js +49 -30
  25. package/src/router/server/segment-path-matcher.d.ts +8 -0
  26. package/src/router/server/segment-path-matcher.js +15 -0
  27. package/src/static-site-generator/static-site-generator.js +1 -1
  28. package/src/types/contracts.d.ts +87 -61
  29. package/src/types/contracts.js +4 -1
  30. package/src/types/public-types.d.ts +1 -1
  31. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  32. package/src/utils/endpoint-file-extensions.js +13 -0
@@ -6,6 +6,7 @@ import type { StaticGenerationRoute } from '../../../router/server/route-registr
6
6
  import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
7
7
  import { ServerRouteHandler } from './server-route-handler.js';
8
8
  import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
9
+ import { type EndpointRequestContext, type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
9
10
  import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext, StaticRoute, ErrorPageLoaders } from '../../../types/contracts.js';
10
11
  export type ServerRequestContext<TServer = unknown> = {
11
12
  apiHandlers: ApiHandler[];
@@ -27,17 +28,30 @@ export declare class ServerRequestPipeline {
27
28
  protected routeHandler: ServerRouteHandler;
28
29
  protected readonly apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
29
30
  private sharedPageCacheService;
31
+ /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
32
+ private readonly importEndpointModule;
33
+ private readonly endpointRouteHandler;
34
+ /** Warnings already logged, so a dev route refresh repeats none of them. */
35
+ private readonly loggedEndpointWarnings;
30
36
  constructor(options: ServerRequestPipelineOptions);
31
- /** Renders one declared path inside the request build scope for a DevSession prewarm. */
32
- renderDevPrewarmPath(pathname: string, runtimeOrigin: string): Promise<void>;
37
+ /**
38
+ * Renders one declared path inside the request build scope for a DevSession prewarm.
39
+ *
40
+ * @param requestContext - The `app.onError` handler and server, so a prewarmed endpoint's errors
41
+ * resolve as they would for a request
42
+ */
43
+ renderDevPrewarmPath(pathname: string, runtimeOrigin: string, requestContext: EndpointRequestContext): Promise<void>;
33
44
  initializeRouteHandling(options: {
34
45
  staticRoutes: StaticRoute[];
35
46
  errorPageLoaders?: ErrorPageLoaders;
47
+ apiHandlers: readonly ApiHandler[];
36
48
  }): Promise<void>;
49
+ private warnExplicitRoutesOnEndpoints;
37
50
  private ensureRouteRendererFactory;
38
51
  createWatchRefreshCallback(options: {
39
52
  staticRoutes: StaticRoute[];
40
53
  errorPageLoaders?: ErrorPageLoaders;
54
+ apiHandlers: readonly ApiHandler[];
41
55
  onRoutesReady?: () => Promise<void> | void;
42
56
  onError?: (error: Error) => Promise<void> | void;
43
57
  }): () => Promise<void>;
@@ -68,6 +82,7 @@ export declare class ServerRequestPipeline {
68
82
  private getOrCreateSharedPageCacheService;
69
83
  protected getCacheService(): CacheInvalidator | null;
70
84
  protected getRenderContext(): RenderContext;
85
+ private importServerModule;
71
86
  private tryHandleSharedDevClientRequest;
72
87
  private tryHandleSharedHmrRequest;
73
88
  private injectSharedHmrHtmlResponse;
@@ -80,6 +95,7 @@ export declare class ServerRequestPipeline {
80
95
  getStaticBuildContext(): {
81
96
  router: RouteRegistry;
82
97
  routeRendererFactory: RouteRendererFactory;
98
+ importServerModule: EndpointRouteHandlerOptions['importServerModule'];
83
99
  };
84
100
  listStaticGenerationRoutes(input: {
85
101
  runtimeOrigin: string;
@@ -90,7 +106,8 @@ export declare class ServerRequestPipeline {
90
106
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
91
107
  * 2. Checks if the incoming request matches any parsed API route schemas.
92
108
  * - Routes through `ApiRequestPipeline` which performs strict validation.
93
- * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
109
+ * 3. Falls through to standard `ServerRouteHandler` for explicit static routes, then filesystem
110
+ * Pages and endpoint files.
94
111
  *
95
112
  * The Node host maps its native HTTP request into a Web Request before calling this method.
96
113
  */
@@ -13,6 +13,8 @@ import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js
13
13
  import { ServerRouteHandler } from './server-route-handler.js';
14
14
  import { createRenderContext } from './render-context.js';
15
15
  import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
16
+ import { EndpointRouteHandler, findExplicitRoutesOnEndpoints, } from '../http/endpoint-route-handler.js';
17
+ import { appLogger } from '../../../global/app-logger.js';
16
18
  import { parseSegmentPath } from '../../../router/server/segment-path-matcher.js';
17
19
  import { isHtmlResponse, withUncachedDevHtml } from '../hmr/hmr-html-response.js';
18
20
  import { resolveInternalExecutionDir } from '../../../utils/resolve-work-dir.js';
@@ -30,23 +32,45 @@ export class ServerRequestPipeline {
30
32
  getCacheService: () => this.getCacheService(),
31
33
  });
32
34
  sharedPageCacheService;
35
+ /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
36
+ importEndpointModule = (filePath) => this.importServerModule(filePath);
37
+ endpointRouteHandler = new EndpointRouteHandler({
38
+ apiRequestPipeline: this.apiRequestPipeline,
39
+ importServerModule: this.importEndpointModule,
40
+ });
41
+ /** Warnings already logged, so a dev route refresh repeats none of them. */
42
+ loggedEndpointWarnings = new Set();
33
43
  constructor(options) {
34
44
  this.appConfig = options.appConfig;
35
45
  this.runtime = options.runtime;
36
46
  this.watchMode = options.watch ?? false;
37
47
  }
38
- /** Renders one declared path inside the request build scope for a DevSession prewarm. */
39
- async renderDevPrewarmPath(pathname, runtimeOrigin) {
48
+ /**
49
+ * Renders one declared path inside the request build scope for a DevSession prewarm.
50
+ *
51
+ * @param requestContext - The `app.onError` handler and server, so a prewarmed endpoint's errors
52
+ * resolve as they would for a request
53
+ */
54
+ async renderDevPrewarmPath(pathname, runtimeOrigin, requestContext) {
40
55
  await requireBuildQueue(this.appConfig).withRequestScope(() => runWithBuildInputIndex(requireAppRuntime(this.appConfig).buildInputIndex, async () => {
41
- const response = await this.routeHandler.handleResponse(new Request(new URL(pathname, runtimeOrigin).toString(), { method: 'GET' }));
56
+ const response = await this.routeHandler.handleResponse(new Request(new URL(pathname, runtimeOrigin).toString(), { method: 'GET' }), requestContext);
42
57
  await response.arrayBuffer();
43
58
  }));
44
59
  }
45
60
  async initializeRouteHandling(options) {
46
61
  this.ensureRouteRendererFactory();
47
62
  await this.initSharedRouter();
63
+ this.warnExplicitRoutesOnEndpoints(options.apiHandlers);
48
64
  this.configureResponseHandlers(options);
49
65
  }
66
+ warnExplicitRoutesOnEndpoints(apiHandlers) {
67
+ for (const warning of findExplicitRoutesOnEndpoints(apiHandlers, this.router.templateRoutes)) {
68
+ if (!this.loggedEndpointWarnings.has(warning)) {
69
+ this.loggedEndpointWarnings.add(warning);
70
+ appLogger.warn(warning);
71
+ }
72
+ }
73
+ }
50
74
  ensureRouteRendererFactory() {
51
75
  if (this.routeRendererFactory) {
52
76
  return;
@@ -61,6 +85,7 @@ export class ServerRequestPipeline {
61
85
  await this.initializeRouteHandling({
62
86
  staticRoutes: options.staticRoutes,
63
87
  errorPageLoaders: options.errorPageLoaders,
88
+ apiHandlers: options.apiHandlers,
64
89
  });
65
90
  if (options.onRoutesReady) {
66
91
  await options.onRoutesReady();
@@ -127,6 +152,7 @@ export class ServerRequestPipeline {
127
152
  this.routeHandler = new ServerRouteHandler({
128
153
  router: this.router,
129
154
  fileSystemResponseMatcher: this.fileSystemResponseMatcher,
155
+ endpointRouteHandler: this.endpointRouteHandler,
130
156
  explicitStaticRouteMatcher,
131
157
  });
132
158
  }
@@ -185,15 +211,17 @@ export class ServerRequestPipeline {
185
211
  return this.fileSystemResponseMatcher?.getCacheService() ?? null;
186
212
  }
187
213
  getRenderContext() {
188
- const moduleLoader = requireAppRuntime(this.appConfig).moduleLoader;
189
214
  return createRenderContext({
190
215
  integrations: this.appConfig.integrations,
191
216
  ensureIntegrationReady: (integrationName) => ensureIntegrationRuntimeReady({ appConfig: this.appConfig, integrationName }),
192
- importServerModule: async (filePath) => await moduleLoader.importModule({
193
- filePath,
194
- outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
195
- externalPackages: true,
196
- }),
217
+ importServerModule: (filePath) => this.importServerModule(filePath),
218
+ });
219
+ }
220
+ async importServerModule(filePath) {
221
+ return await requireAppRuntime(this.appConfig).moduleLoader.importModule({
222
+ filePath,
223
+ outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
224
+ externalPackages: true,
197
225
  });
198
226
  }
199
227
  async tryHandleSharedDevClientRequest(request) {
@@ -225,7 +253,11 @@ export class ServerRequestPipeline {
225
253
  return this.watchMode && isHtmlResponse(response) ? withUncachedDevHtml(response) : response;
226
254
  }
227
255
  getStaticBuildContext() {
228
- return { router: this.router, routeRendererFactory: this.routeRendererFactory };
256
+ return {
257
+ router: this.router,
258
+ routeRendererFactory: this.routeRendererFactory,
259
+ importServerModule: this.importEndpointModule,
260
+ };
229
261
  }
230
262
  async listStaticGenerationRoutes(input) {
231
263
  return await this.router.listStaticGenerationRoutes(input);
@@ -236,7 +268,8 @@ export class ServerRequestPipeline {
236
268
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
237
269
  * 2. Checks if the incoming request matches any parsed API route schemas.
238
270
  * - Routes through `ApiRequestPipeline` which performs strict validation.
239
- * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
271
+ * 3. Falls through to standard `ServerRouteHandler` for explicit static routes, then filesystem
272
+ * Pages and endpoint files.
240
273
  *
241
274
  * The Node host maps its native HTTP request into a Web Request before calling this method.
242
275
  */
@@ -265,7 +298,7 @@ export class ServerRequestPipeline {
265
298
  if (apiResponse) {
266
299
  return await this.injectSharedHmrHtmlResponse(apiResponse);
267
300
  }
268
- const routeResponse = await this.routeHandler.handleResponse(request, parsedPathSegments);
301
+ const routeResponse = await this.routeHandler.handleResponse(request, context, parsedPathSegments);
269
302
  return await this.injectSharedHmrHtmlResponse(routeResponse);
270
303
  })));
271
304
  }
@@ -1,6 +1,7 @@
1
1
  import type { RouteRegistry } from '../../../router/server/route-registry.js';
2
2
  import type { ExplicitStaticRouteMatcher } from '../http/explicit-static-route-matcher.js';
3
3
  import type { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
4
+ import type { EndpointRequestContext, EndpointRouteHandler } from '../http/endpoint-route-handler.js';
4
5
  import { type ParsedSegmentPath } from '../../../router/server/segment-path-matcher.js';
5
6
  /**
6
7
  * Configuration parameters for ServerRouteHandler.
@@ -10,6 +11,8 @@ export interface ServerRouteHandlerParams {
10
11
  router: RouteRegistry;
11
12
  /** Matcher for handling file system route responses. */
12
13
  fileSystemResponseMatcher: FileSystemResponseMatcher;
14
+ /** Answers file system routes whose role is `endpoint`. */
15
+ endpointRouteHandler: EndpointRouteHandler;
13
16
  /** Optional matcher for explicit static routes like processed images or sitemaps. */
14
17
  explicitStaticRouteMatcher?: ExplicitStaticRouteMatcher;
15
18
  }
@@ -25,26 +28,28 @@ export interface ServerRouteHandlerParams {
25
28
  export declare class ServerRouteHandler {
26
29
  private readonly router;
27
30
  private readonly fileSystemResponseMatcher;
31
+ private readonly endpointRouteHandler;
28
32
  private readonly explicitStaticRouteMatcher?;
29
33
  /**
30
34
  * Creates a new ServerRouteHandler instance.
31
35
  *
32
36
  * @param params - Configuration parameters
33
37
  */
34
- constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher }: ServerRouteHandlerParams);
38
+ constructor({ router, fileSystemResponseMatcher, endpointRouteHandler, explicitStaticRouteMatcher, }: ServerRouteHandlerParams);
35
39
  /**
36
40
  * Handles HTTP requests from the router adapter.
37
41
  *
38
42
  * Priority-based routing flow:
39
43
  * 1. Check explicit static routes first (e.g., /sitemap.xml, /image.webp from plugins)
40
44
  * 2. Match file-based routes, unless the path ends in a known static file extension, so a
41
- * dotted route such as `/v1.2` still matches its Page
45
+ * dotted route such as `/v1.2` still matches its Page or endpoint
42
46
  * 3. Fall back to static file serving from disk
43
47
  *
44
48
  * @param request - The incoming HTTP request
49
+ * @param requestContext - The `app.onError` handler and server an endpoint's errors resolve with
45
50
  * @returns HTTP response for the matched route
46
51
  */
47
- handleResponse(request: Request, parsedPathSegments?: ParsedSegmentPath): Promise<Response>;
52
+ handleResponse(request: Request, requestContext: EndpointRequestContext, parsedPathSegments?: ParsedSegmentPath): Promise<Response>;
48
53
  /**
49
54
  * Handles requests that do not match any routes.
50
55
  *
@@ -14,15 +14,17 @@ import { parseSegmentPath } from '../../../router/server/segment-path-matcher.js
14
14
  export class ServerRouteHandler {
15
15
  router;
16
16
  fileSystemResponseMatcher;
17
+ endpointRouteHandler;
17
18
  explicitStaticRouteMatcher;
18
19
  /**
19
20
  * Creates a new ServerRouteHandler instance.
20
21
  *
21
22
  * @param params - Configuration parameters
22
23
  */
23
- constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher }) {
24
+ constructor({ router, fileSystemResponseMatcher, endpointRouteHandler, explicitStaticRouteMatcher, }) {
24
25
  this.router = router;
25
26
  this.fileSystemResponseMatcher = fileSystemResponseMatcher;
27
+ this.endpointRouteHandler = endpointRouteHandler;
26
28
  this.explicitStaticRouteMatcher = explicitStaticRouteMatcher;
27
29
  }
28
30
  /**
@@ -31,13 +33,14 @@ export class ServerRouteHandler {
31
33
  * Priority-based routing flow:
32
34
  * 1. Check explicit static routes first (e.g., /sitemap.xml, /image.webp from plugins)
33
35
  * 2. Match file-based routes, unless the path ends in a known static file extension, so a
34
- * dotted route such as `/v1.2` still matches its Page
36
+ * dotted route such as `/v1.2` still matches its Page or endpoint
35
37
  * 3. Fall back to static file serving from disk
36
38
  *
37
39
  * @param request - The incoming HTTP request
40
+ * @param requestContext - The `app.onError` handler and server an endpoint's errors resolve with
38
41
  * @returns HTTP response for the matched route
39
42
  */
40
- async handleResponse(request, parsedPathSegments) {
43
+ async handleResponse(request, requestContext, parsedPathSegments) {
41
44
  const pathname = new URL(request.url).pathname;
42
45
  try {
43
46
  const pathSegments = parsedPathSegments ?? parseSegmentPath(pathname);
@@ -54,9 +57,12 @@ export class ServerRouteHandler {
54
57
  }
55
58
  }
56
59
  const fsMatch = !ServerUtils.hasKnownStaticExtension(pathname) && this.router.matchRequest(request.url, pathSegments);
57
- return await (fsMatch
58
- ? this.fileSystemResponseMatcher.handleMatch(fsMatch, request)
59
- : this.handleNoMatch(request));
60
+ if (!fsMatch) {
61
+ return await this.handleNoMatch(request);
62
+ }
63
+ return await (fsMatch.templateRoute.role === 'endpoint'
64
+ ? this.endpointRouteHandler.handleMatch(fsMatch, request, requestContext)
65
+ : this.fileSystemResponseMatcher.handleMatch(fsMatch, request));
60
66
  }
61
67
  catch (error) {
62
68
  if (error instanceof HttpError) {
@@ -4,6 +4,7 @@ import type { ErrorPageLoaders, StaticRoute } from '../../../types/contracts.js'
4
4
  import type { RouteRegistry } from '../../../router/server/route-registry.js';
5
5
  import type { StaticSiteGenerator } from '../../../static-site-generator/static-site-generator.js';
6
6
  import type { StaticGenerationRendererResolver } from '../../../route-renderer/route-renderer.js';
7
+ import { type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
7
8
  export interface StaticBuildOptions {
8
9
  baseUrl?: string;
9
10
  force?: boolean;
@@ -22,6 +23,11 @@ export interface ServerStaticBuilderParams {
22
23
  * Whether the app requires a server entry bundle for production use.
23
24
  * When `true`, the build step bundles the server entry file for `ecopages start`.
24
25
  * Defaults to `false` (static-only build, no server needed).
26
+ *
27
+ * @remarks
28
+ * Covers what the app registers: Explicit Routes and WebSocket handlers. An endpoint file under the pages
29
+ * directory is known only once the Route Registry has scanned it, so {@link ServerStaticBuilder.build} adds
30
+ * it to this decision.
25
31
  */
26
32
  needsServerBundle?: boolean;
27
33
  logger?: ServerStaticBuilderLogger;
@@ -76,7 +82,7 @@ export declare class ServerStaticBuilder {
76
82
  *
77
83
  * @remarks
78
84
  * Only invoked when the app requires a runtime server (API handlers,
79
- * websocket handlers, etc.). Static-only apps skip this step entirely.
85
+ * websocket handlers or endpoint files). Static-only apps skip this step entirely.
80
86
  * Every process bundles the entry from source.
81
87
  *
82
88
  * Source code is bundled: the app entry graph, workspace packages and
@@ -97,11 +103,18 @@ export declare class ServerStaticBuilder {
97
103
  * @param dependencies.router - The initialized router
98
104
  * @param dependencies.routeRendererFactory - The route renderer factory
99
105
  * @param dependencies.staticRoutes - Explicit static routes registered via app.static()
106
+ * @param dependencies.importServerModule - The server-module loader endpoint requests use
107
+ *
108
+ * @remarks
109
+ * Every endpoint file is imported and its exports checked as its first request would, before the
110
+ * server bundle and static generation, so a broken one fails the build with the request's error.
111
+ * The import is cached in this process only; `ecopages start` compiles the file again.
100
112
  */
101
113
  build(options: StaticBuildOptions | undefined, dependencies: {
102
114
  router: RouteRegistry;
103
115
  routeRendererFactory: StaticGenerationRendererResolver;
104
116
  staticRoutes?: StaticRoute[];
105
117
  errorPageLoaders?: ErrorPageLoaders;
118
+ importServerModule: EndpointRouteHandlerOptions['importServerModule'];
106
119
  }): Promise<void>;
107
120
  }
@@ -12,6 +12,7 @@ import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '..
12
12
  import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
13
13
  import { resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
14
14
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
15
+ import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
15
16
  /**
16
17
  * Handles static site generation.
17
18
  */
@@ -85,7 +86,7 @@ export class ServerStaticBuilder {
85
86
  *
86
87
  * @remarks
87
88
  * Only invoked when the app requires a runtime server (API handlers,
88
- * websocket handlers, etc.). Static-only apps skip this step entirely.
89
+ * websocket handlers or endpoint files). Static-only apps skip this step entirely.
89
90
  * Every process bundles the entry from source.
90
91
  *
91
92
  * Source code is bundled: the app entry graph, workspace packages and
@@ -141,6 +142,12 @@ export class ServerStaticBuilder {
141
142
  * @param dependencies.router - The initialized router
142
143
  * @param dependencies.routeRendererFactory - The route renderer factory
143
144
  * @param dependencies.staticRoutes - Explicit static routes registered via app.static()
145
+ * @param dependencies.importServerModule - The server-module loader endpoint requests use
146
+ *
147
+ * @remarks
148
+ * Every endpoint file is imported and its exports checked as its first request would, before the
149
+ * server bundle and static generation, so a broken one fails the build with the request's error.
150
+ * The import is cached in this process only; `ecopages start` compiles the file again.
144
151
  */
145
152
  async build(options, dependencies) {
146
153
  const { baseUrl: explicitBaseUrl, force = false } = options ?? {};
@@ -150,7 +157,11 @@ export class ServerStaticBuilder {
150
157
  await this.prepareExport();
151
158
  }
152
159
  this.exportPrepared = false;
153
- if (this.needsServerBundle) {
160
+ const endpointRoutes = dependencies.router.templateRoutes.filter((route) => route.role === 'endpoint');
161
+ for (const route of endpointRoutes) {
162
+ readEndpointHandlers(await dependencies.importServerModule(route.filePath), route);
163
+ }
164
+ if (this.needsServerBundle || endpointRoutes.length > 0) {
154
165
  await this.bundleServerEntry();
155
166
  }
156
167
  await this.staticSiteGenerator.run({
@@ -42,7 +42,7 @@ export declare function writeServerBundleDeployManifest(appConfig: EcoPagesAppCo
42
42
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
43
43
  * that used another `distDir`.
44
44
  *
45
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
45
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
46
46
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
47
47
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
48
48
  * recognised.
@@ -72,7 +72,7 @@ function readServerBundleDeployManifest(serverDir) {
72
72
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
73
73
  * that used another `distDir`.
74
74
  *
75
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
75
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
76
76
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
77
77
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
78
78
  * recognised.
@@ -7,6 +7,7 @@ import { appLogger } from '../../global/app-logger.js';
7
7
  import { HTML_PAGES_INTEGRATION_NAME } from '../../html-pages/html-page-module.js';
8
8
  import { HtmlPagesPlugin } from '../../html-pages/html-pages.plugin.js';
9
9
  import { invariant } from '../../utils/invariant.js';
10
+ import { ENDPOINT_FILE_EXTENSIONS, findEndpointFileExtension } from '../../utils/endpoint-file-extensions.js';
10
11
  import { DEFAULT_ECOPAGES_DIST_DIR, DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT, DEFAULT_ECOPAGES_WORK_DIR, } from '../../constants.js';
11
12
  import { collectConfigModuleFiles } from '../config-module-files.js';
12
13
  import { DEFAULT_ECO_CONFIG_FILENAME, resolveUserConfigRootDir } from '../resolve-eco-config-path.js';
@@ -84,6 +85,10 @@ function collectTemplateExtensions(integrations) {
84
85
  if (names.has('kitajs') && names.has('react')) {
85
86
  appLogger.debug('Both kitajs and react integrations are enabled. Use per-file JSX import source/pragma consistently (e.g. `/** @jsxImportSource react */` for React files and `/** @jsxImportSource @kitajs/html */` for Kita files).');
86
87
  }
88
+ for (const integration of integrations) {
89
+ const reserved = integration.extensions.find((extension) => findEndpointFileExtension(extension));
90
+ invariant(reserved === undefined, `Integration "${integration.name}" registers "${reserved}", which is reserved for endpoint files: ${ENDPOINT_FILE_EXTENSIONS.join(', ')}.`);
91
+ }
87
92
  const extensions = integrations.flatMap((integration) => integration.extensions);
88
93
  const duplicateExtension = findDuplicate(extensions);
89
94
  invariant(duplicateExtension === undefined, `Integration extensions must be unique: "${duplicateExtension}" is registered by more than one Integration.`);
package/src/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type * from './types/public-types.js';
2
2
  export { eco } from './eco/eco.js';
3
- export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, json, html, redirect, type GroupHandler, } from './adapters/shared/http/define-api-handler.js';
3
+ export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, type GroupHandler, } from './adapters/shared/http/define-api-handler.js';
4
4
  export { attributeMdxComponentIdentity } from './plugins/eco-component-meta-plugin.js';
5
5
  export { bindComponentIdentity, getComponentIdentity, getComponentOwner, type ComponentIdentity, } from './eco/component-identity.js';
6
6
  export { attachDiscoveredDependencies } from './eco/discovered-dependencies.js';
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { eco } from './eco/eco.js';
2
- export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, json, html, redirect, } from './adapters/shared/http/define-api-handler.js';
2
+ export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, } from './adapters/shared/http/define-api-handler.js';
3
3
  export { attributeMdxComponentIdentity } from './plugins/eco-component-meta-plugin.js';
4
4
  export { bindComponentIdentity, getComponentIdentity, getComponentOwner, } from './eco/component-identity.js';
5
5
  export { attachDiscoveredDependencies } from './eco/discovered-dependencies.js';
@@ -2,17 +2,23 @@ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
2
  import type { PageParams, PageQuery } from '../../types/contracts.js';
3
3
  import { type ParsedSegmentPath } from './segment-path-matcher.js';
4
4
  export type RouteKind = 'exact' | 'catch-all' | 'dynamic';
5
+ /**
6
+ * What a Template Route file declares: a Page rendered to HTML, or an endpoint file whose method
7
+ * handler exports answer its requests. Only `page` routes take part in static generation.
8
+ */
9
+ export type RouteRole = 'page' | 'endpoint';
5
10
  export type RouteParams = PageParams;
6
11
  export type RouteQuery = PageQuery;
7
12
  export type TemplateRoute = {
8
13
  readonly pathname: string;
9
14
  readonly kind: RouteKind;
15
+ readonly role: RouteRole;
10
16
  readonly filePath: string;
11
17
  readonly paramNames: readonly string[];
12
18
  };
13
19
  export type RouteMatch = {
14
20
  readonly requestedPathname: string;
15
- readonly templateRoute: Pick<TemplateRoute, 'pathname' | 'kind' | 'filePath'> & Partial<Pick<TemplateRoute, 'paramNames'>>;
21
+ readonly templateRoute: Pick<TemplateRoute, 'pathname' | 'kind' | 'role' | 'filePath'> & Partial<Pick<TemplateRoute, 'paramNames'>>;
16
22
  readonly params: RouteParams;
17
23
  readonly query: RouteQuery;
18
24
  };
@@ -62,22 +68,23 @@ export declare class RouteRegistry {
62
68
  constructor(options: RouteRegistryOptions);
63
69
  get origin(): string;
64
70
  get templateRoutes(): readonly TemplateRoute[];
71
+ private get pageRoutes();
65
72
  init(): Promise<void>;
66
73
  reload(): Promise<void>;
67
74
  onReload(listener: () => void): () => void;
68
75
  matchRequest(requestUrl: string, parsedPathSegments?: ParsedSegmentPath): RouteMatch | null;
69
76
  /**
70
- * Orders overlapping catch-all routes by the specificity of their prefix.
77
+ * Orders two dynamic or two catch-all routes by the specificity of their
78
+ * pattern segments, the catch-all segment itself left out.
71
79
  *
72
80
  * @remarks
73
- * Prefix segments are compared from left to right because an earlier static
81
+ * Segments are compared from left to right because an earlier literal
74
82
  * segment constrains a request more strongly than a later one. A longer
75
- * prefix wins only after the shared segment pattern ties. The pathname tie
76
- * breaker keeps equal patterns deterministic without depending on discovery
77
- * order.
83
+ * pattern wins only after the shared segments tie. The pathname tie breaker
84
+ * keeps equal patterns deterministic without depending on discovery order.
78
85
  */
79
- private compareCatchAllSpecificity;
80
- private getCatchAllPrefix;
86
+ private compareSpecificity;
87
+ private getSpecificitySegments;
81
88
  private isDynamicRouteSegment;
82
89
  listStaticPathExpansions(input: {
83
90
  runtimeOrigin: string;
@@ -89,7 +96,9 @@ export declare class RouteRegistry {
89
96
  /**
90
97
  * @remarks
91
98
  * Strips the longest template extension the file ends with, so `about.kita.tsx` keeps no
92
- * `.kita` part when `.tsx` is also registered, and `my.html-tips.html` keeps its name.
99
+ * `.kita` part when `.tsx` is also registered, and `my.html-tips.html` keeps its name. An
100
+ * endpoint strips its whole marker, so `users.api.tsx` is `/users` even when `.tsx` is a
101
+ * template extension.
93
102
  */
94
103
  private getRoutePath;
95
104
  /**