@ecopages/core 0.3.2 → 0.5.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 (79) hide show
  1. package/README.md +19 -3
  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/api-request-pipeline.js +2 -2
  9. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  10. package/src/adapters/shared/http/define-api-handler.js +15 -1
  11. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  12. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  13. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  14. package/src/adapters/shared/runtime/server-request-pipeline.js +46 -12
  15. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  16. package/src/adapters/shared/runtime/server-route-handler.js +16 -10
  17. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  18. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  19. package/src/assets/app-browser-client-build.js +8 -21
  20. package/src/assets/app-browser-client-manifest.d.ts +0 -1
  21. package/src/assets/app-browser-client-manifest.js +1 -20
  22. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  23. package/src/build/contracts/content-virtual-modules.js +11 -5
  24. package/src/build/contracts.d.ts +1 -1
  25. package/src/build/contracts.js +1 -1
  26. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  27. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  28. package/src/build/server-bundle-deploy-manifest.js +1 -1
  29. package/src/build.d.ts +1 -1
  30. package/src/build.js +1 -1
  31. package/src/config/assembly/finalize-config.js +5 -0
  32. package/src/dev/transform-server/dev-transform-server.js +1 -1
  33. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  34. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  35. package/src/errors/http-error.d.ts +9 -0
  36. package/src/errors/http-error.js +11 -0
  37. package/src/html/html-transformer.service.d.ts +0 -21
  38. package/src/html/html-transformer.service.js +0 -32
  39. package/src/html-pages/html-page-renderer.d.ts +2 -1
  40. package/src/html-pages/html-page-renderer.js +5 -3
  41. package/src/index.d.ts +1 -1
  42. package/src/index.js +1 -1
  43. package/src/integration.d.ts +1 -2
  44. package/src/integration.js +0 -1
  45. package/src/islands/island-host.d.ts +1 -2
  46. package/src/islands/island-host.js +1 -2
  47. package/src/plugins/integration-plugin.d.ts +1 -1
  48. package/src/plugins/processor.d.ts +1 -1
  49. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  50. package/src/plugins/tsconfig-import-resolver.js +4 -2
  51. package/src/processor.d.ts +1 -1
  52. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  53. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  54. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  55. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  56. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  57. package/src/route-renderer/orchestration/integration-renderer.d.ts +20 -44
  58. package/src/route-renderer/orchestration/integration-renderer.js +52 -115
  59. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  60. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  61. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  62. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  63. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  64. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  65. package/src/router/server/route-registry.d.ts +20 -9
  66. package/src/router/server/route-registry.js +52 -30
  67. package/src/router/server/segment-path-matcher.d.ts +8 -0
  68. package/src/router/server/segment-path-matcher.js +15 -0
  69. package/src/static-site-generator/production-page-browser-graph-prebuild.js +0 -4
  70. package/src/static-site-generator/static-site-generator.js +1 -1
  71. package/src/types/build-types.d.ts +6 -0
  72. package/src/types/contracts.d.ts +93 -65
  73. package/src/types/contracts.js +4 -1
  74. package/src/types/eco-api-types.d.ts +1 -1
  75. package/src/types/public-types.d.ts +1 -1
  76. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  77. package/src/utils/endpoint-file-extensions.js +13 -0
  78. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  79. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
package/README.md CHANGED
@@ -26,8 +26,8 @@ The important ownership rules are:
26
26
  - Component identity attribution is one build plugin, shared by server, browser, and HMR compilation paths: after a lexical `eco.` gate, it uses Oxc to wrap supported factory options with `bindComponentIdentity()`, which factories retain as `config.identity`.
27
27
  - Component ownership follows `config.integration`, then `config.identity.integration`, then the inherited owner through the exported `getComponentOwner()` helper. Integration plugins opt into page-owned asset bundling with `bundlesPageDependencies`; React and Ecopages JSX enable it. Bundling only combines consecutive eligible assets so custom-attribute files keep their declared order.
28
28
  - Direct local Eco Component imports (including named `export { X } from` barrels) and relative side-effect CSS imports supply Dependencies by default through the shared transform and existing collector; explicit asset declarations override inference, and inferred styles stay keyed by identity until collection. Eco owns the component render context used by its factories. See [eco](src/eco/README.md) and [Plugin Contracts](src/plugins/README.md).
29
- - Every Integration shares one renderer and the app-owned `AssetProcessingService` across route renders, explicit views, and foreign-child handoffs. Integration-owned asset processing calls pass their owning Integration so its optional dependency-preparation hook can run; one service cache covers grouped and ungrouped processor results. Route preparation records one component graph for ownership validation, dependencies, client assets, and dev cache paths. Dependency collection uses the service to turn declared assets into runtime-ready output instead of treating a missing service as an empty asset set. Route renders keep assets and foreign-renderer caches in per-render sessions, with async context storage isolating concurrent renders. See [Route Renderer](src/route-renderer/README.md).
30
- - Custom Integrations can create a renderer with `createIntegrationRenderer()` and opt into component, page-graph, document-shell props and composition, foreign-child, route lifecycle, grouped island assets, and finalization hooks without rebuilding the route pipeline. Hook factories receive app-owned renderer options plus helpers for Integration-wide dependencies, component-owned dependencies, dependency paths, and pending lazy triggers. Core handles queued-child resolution and island-host finalization around component hooks. See [Custom Integration](../../apps/docs/src/content/docs/plugins/custom-integration.mdx).
29
+ - Every Integration shares one renderer and the app-owned `AssetProcessingService` across route renders, explicit views, and foreign-child handoffs. Integration-owned asset processing calls pass their owning Integration so its optional dependency-preparation hook can run; one service cache covers grouped and ungrouped processor results. Route preparation records one component graph for ownership validation, dependencies, client assets, and dev cache paths; a development render fails on a component outside it. Dependency collection uses the service to turn declared assets into runtime-ready output instead of treating a missing service as an empty asset set. Route preparation builds each Page Package once; component renders return HTML and attributes only and add no assets. Route renders keep Integration dependencies and foreign-renderer caches in per-render sessions, with async context storage isolating concurrent renders. See [Route Renderer](src/route-renderer/README.md).
30
+ - Custom Integrations can create a renderer with `createIntegrationRenderer()` and opt into component, page-graph, document-shell props and composition, foreign-child, route lifecycle, grouped island assets, and finalization hooks without rebuilding the route pipeline. Hook factories receive app-owned renderer options plus helpers for Integration-wide dependencies, dependency paths, and pending lazy triggers. Core handles queued-child resolution and island-host finalization around component hooks. See [Custom Integration](../../apps/docs/src/content/docs/plugins/custom-integration.mdx).
31
31
  - Browser bundling and server module loading are separate paths. SSR-enabled lazy scripts execute on the server before rendering and in the browser only on their configured trigger.
32
32
  - The Project Watcher batches file and directory events, sends matching Processors one `onChanges` notification for each non-restart file batch, and dispatches every HMR-eligible path once per debounce window. Directory-only Pages batches refresh routes without Processor or HMR notifications. Sustained edits are scheduled no later than one second after the first; processing is serialized and startup fails if the filesystem subscription is not ready within 30 seconds. See [Project Watcher](src/watchers/README.md).
33
33
  - Development Page prewarm renders run in the background without delaying server readiness. App configuration declares `devPrewarmPaths`; Processors append the pathnames they own to that list from `setup()`, which finishes before the server reports that it is listening. A path that fails to render is skipped and logged at debug level. See [Runtime Adapters](src/adapters/README.md) and [Plugin Contracts](src/plugins/README.md).
@@ -134,7 +134,7 @@ Use this package README as the top-level map, then drill into the focused subsys
134
134
  - `src/dev/invalidation/README.md`: file-change classification and dirty-marking for bounded watcher batches
135
135
  - `src/hmr/README.md`: HMR strategy, update-layer ownership, and build error presentation
136
136
  - `src/dev-toolbar/README.md`: toolbar enablement, custom clients, and build error event contract
137
- - `src/router/README.md`: route discovery, matching, browser navigation coordination, persistence-aware body morphing, and the shared client navigation pipeline
137
+ - `src/router/README.md`: route discovery (Pages and `*.api.{ts,tsx,js,jsx}` endpoint files), matching, browser navigation coordination, persistence-aware body morphing, and the shared client navigation pipeline
138
138
  - `src/route-renderer/README.md`: rendering orchestration, semantic error pages, dependency resolution, and HTML cache source paths
139
139
  - `src/static-site-generator/README.md`: static build execution, collected Page render failures, and sitemap eligibility from successful route-render metadata
140
140
  - `src/eco/README.md`: `eco` authoring APIs for pages, layouts, and components, including the `LayoutOptions` type contract
@@ -257,6 +257,8 @@ export const helloWorldAlt = defineApiHandler({
257
257
  });
258
258
  ```
259
259
 
260
+ `defineQuery`, `app.query()` and `api.query` handle the HTTP QUERY method (RFC 10008): a safe, idempotent read whose request body carries the query. It takes a `schema.body` like `definePost`, and Ecopages adds no caching, `Accept-Query` or `Vary`; set them on the response if you want them. QUERY here is the method, not the handler context's `query` field (the URL's search parameters).
261
+
260
262
  Group related routes with `defineGroupHandler`. Prefer `api.get` / `api.post` helpers inside the `routes` callback:
261
263
 
262
264
  ```typescript
@@ -281,6 +283,20 @@ Standalone response helpers (`json`, `html`, `redirect`) share the same body emi
281
283
 
282
284
  Register a prebuilt handler with `app.add()`. Use `app.get(path, handler)` only when defining the route inline in `app.ts`.
283
285
 
286
+ The method helpers also accept a handler without `path`, for an export of an endpoint file (`*.api.ts`, `.api.tsx`, `.api.js` or `.api.jsx`), whose path under the pages directory gives the URL. The `api.get` / `api.post` group helpers still require `path`, and `app.add()` and `app.group()` throw for a handler without one.
287
+
288
+ The filesystem form of the same handler is an endpoint file. `src/pages/api/hello.api.ts` answers `/api/hello` with no `app.add()` call:
289
+
290
+ ```typescript
291
+ import { defineGet } from '@ecopages/core';
292
+
293
+ export const GET = defineGet({
294
+ handler: async ({ response }) => response.json({ message: 'Hello World' }),
295
+ });
296
+ ```
297
+
298
+ The file's rules (405 and `Allow`, load errors, `app.ts` routes on the same URL) are in the [Endpoint Files docs](https://ecopages.app/docs/server/endpoint-files); the contracts are in `src/router/README.md` and `src/adapters/README.md`. A build of an app with an endpoint file checks each file's exports, then emits the server bundle (`dist/.server/`) even when nothing else registers a handler, so `ecopages start` serves it.
299
+
284
300
  ### 6. Error pages
285
301
 
286
302
  Filesystem `src/pages/404.*` and `500.*` take precedence. For explicit-route apps, register views on the app:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@clack/prompts": "^1.7.0",
24
- "@ecopages/file-system": "0.3.2",
24
+ "@ecopages/file-system": "0.5.0",
25
25
  "@ecopages/logger": "^0.2.3",
26
26
  "@ecopages/scripts-injector": "^0.1.5",
27
27
  "@jridgewell/remapping": "^2.3.5",
@@ -35,7 +35,7 @@
35
35
  "ws": "^8.20.1"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/dev-toolbar": "0.3.2"
38
+ "@ecopages/dev-toolbar": "0.5.0"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@ecopages/dev-toolbar": {
@@ -1,5 +1,5 @@
1
1
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
- import type { ApiHandler, ApiHandlerContext, ErrorHandler, Middleware, RouteGroupBuilder, RouteOptions, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
2
+ import type { ApiHandler, ApiHandlerContext, ErrorHandler, MiddlewareContext, MiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
3
3
  import { type HttpErrorPageStatus } from '../../errors/http-error-page-contract.js';
4
4
  import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
5
5
  import { type RuntimeHost } from './runtime-host.js';
@@ -30,13 +30,9 @@ export type EcopagesAppDependencies = {
30
30
  runtimeHost: RuntimeHost;
31
31
  createServerAdapter?: (params: NodeServerAdapterParams) => Promise<NodeServerAdapter>;
32
32
  };
33
- /**
34
- * Handler function type for route handlers
35
- */
36
- export type RouteHandler<TRequest extends Request = Request, TServer = unknown, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = (context: TContext) => Promise<Response> | Response;
37
- export type RouteGroupDefinition<TRequest extends Request = Request, TServer = unknown, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = {
33
+ export type RouteGroupDefinition<TRequest extends Request = Request, TServer = unknown> = {
38
34
  prefix: string;
39
- middleware?: readonly Middleware<TRequest, TServer, TContext>[];
35
+ middleware?: MiddlewareList<TRequest, TServer>;
40
36
  routes: readonly ApiHandler<string, TRequest, TServer>[];
41
37
  };
42
38
  export declare class EcopagesApp implements AsyncDisposable {
@@ -68,22 +64,26 @@ export declare class EcopagesApp implements AsyncDisposable {
68
64
  */
69
65
  private stopCount;
70
66
  constructor(options: EcopagesAppRuntimeOptions, dependencies: EcopagesAppDependencies);
71
- private register;
72
- get<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
73
- post<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
74
- put<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
75
- delete<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
76
- patch<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
77
- options<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
78
- head<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
79
- route<P extends string>(path: P, method: ApiHandler['method'], handler: RouteHandler<Request, unknown>, options?: RouteOptions<Request, unknown>): this;
67
+ private method;
68
+ readonly get: RouteMethod<this, Request, unknown>;
69
+ readonly post: RouteMethod<this, Request, unknown>;
70
+ readonly put: RouteMethod<this, Request, unknown>;
71
+ readonly delete: RouteMethod<this, Request, unknown>;
72
+ readonly patch: RouteMethod<this, Request, unknown>;
73
+ readonly options: RouteMethod<this, Request, unknown>;
74
+ readonly head: RouteMethod<this, Request, unknown>;
75
+ /** Registers a handler for the QUERY method, not for `ctx.query`. */
76
+ readonly query: RouteMethod<this, Request, unknown>;
77
+ route<TSchema extends RouteSchema = RouteSchema, TRouteContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(path: string, method: ApiHandler['method'], handler: (context: RouteHandlerContext<TSchema, TRouteContext & MiddlewareContext<TMiddleware>>) => Promise<Response> | Response, options?: RouteOptions<Request, unknown, TSchema, TMiddleware>): this;
80
78
  add(handler: ApiHandler<string, Request, unknown>): this;
81
79
  /**
82
- * Internal method to add route handlers to the API handlers array
80
+ * @remarks
81
+ * The typed handler signature is erased here: the request pipeline builds one context per request
82
+ * and fills its schema fields before the handler runs.
83
83
  */
84
84
  private addRouteHandler;
85
- group<TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(prefixOrGroup: string | RouteGroupDefinition<Request, unknown, TContext>, callback?: (builder: RouteGroupBuilder<Request, unknown, TContext>) => void, options?: {
86
- middleware?: readonly Middleware<Request, unknown, TContext>[];
85
+ group<TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(prefixOrGroup: string | RouteGroupDefinition<Request, unknown>, callback?: (builder: RouteGroupBuilder<Request, unknown, TContext & MiddlewareContext<TMiddleware>>) => void, options?: {
86
+ middleware?: TMiddleware;
87
87
  }): this;
88
88
  private registerGroup;
89
89
  /**
@@ -70,38 +70,29 @@ export class EcopagesApp {
70
70
  dependencies.createServerAdapter ?? (async (params) => new NodeServerAdapter(params));
71
71
  startupTrace.markConfigReady();
72
72
  }
73
- register(path, method, handler, options) {
74
- return this.addRouteHandler(path, method, handler, options?.middleware, options?.schema);
75
- }
76
- get(path, handler, options) {
77
- return this.register(path, 'GET', handler, options);
78
- }
79
- post(path, handler, options) {
80
- return this.register(path, 'POST', handler, options);
81
- }
82
- put(path, handler, options) {
83
- return this.register(path, 'PUT', handler, options);
84
- }
85
- delete(path, handler, options) {
86
- return this.register(path, 'DELETE', handler, options);
87
- }
88
- patch(path, handler, options) {
89
- return this.register(path, 'PATCH', handler, options);
90
- }
91
- options(path, handler, options) {
92
- return this.register(path, 'OPTIONS', handler, options);
93
- }
94
- head(path, handler, options) {
95
- return this.register(path, 'HEAD', handler, options);
96
- }
73
+ method(method) {
74
+ return (path, handler, options) => this.addRouteHandler(path, method, handler, options?.middleware, options?.schema);
75
+ }
76
+ get = this.method('GET');
77
+ post = this.method('POST');
78
+ put = this.method('PUT');
79
+ delete = this.method('DELETE');
80
+ patch = this.method('PATCH');
81
+ options = this.method('OPTIONS');
82
+ head = this.method('HEAD');
83
+ /** Registers a handler for the QUERY method, not for `ctx.query`. */
84
+ query = this.method('QUERY');
97
85
  route(path, method, handler, options) {
98
- return this.register(path, method, handler, options);
86
+ return this.method(method)(path, handler, options);
99
87
  }
100
88
  add(handler) {
89
+ invariant(handler.path !== '', `The ${handler.method} handler has no path. Export it from an endpoint file (\`*.api.ts\`, \`.api.tsx\`, \`.api.js\` or \`.api.jsx\`) under the pages directory, or give it a \`path\` to register it with app.add().`);
101
90
  return this.addRouteHandler(handler.path, handler.method, handler.handler, handler.middleware, handler.schema);
102
91
  }
103
92
  /**
104
- * Internal method to add route handlers to the API handlers array
93
+ * @remarks
94
+ * The typed handler signature is erased here: the request pipeline builds one context per request
95
+ * and fills its schema fields before the handler runs.
105
96
  */
106
97
  addRouteHandler(path, method, handler, middleware, schema) {
107
98
  invariant(typeof path === 'string', `Invalid route path for ${method}: expected a string path starting with "/" but received ${Object.prototype.toString.call(path)}. If you're passing a prebuilt ApiHandler, use app.add(handler).`);
@@ -110,7 +101,7 @@ export class EcopagesApp {
110
101
  path,
111
102
  method,
112
103
  handler: handler,
113
- middleware: middleware,
104
+ middleware,
114
105
  schema,
115
106
  });
116
107
  return this;
@@ -120,19 +111,12 @@ export class EcopagesApp {
120
111
  return this.registerGroup(prefixOrGroup);
121
112
  }
122
113
  const normalizedPrefix = prefixOrGroup.endsWith('/') ? prefixOrGroup.slice(0, -1) : prefixOrGroup;
123
- const groupMiddleware = (options?.middleware ?? []);
124
- const createHandler = (method) => {
125
- return ((path, handler, routeOptions) => {
126
- const combinedMiddleware = [
127
- ...groupMiddleware,
128
- ...(routeOptions?.middleware ?? []),
129
- ];
130
- const fullPath = path === '/' ? normalizedPrefix : `${normalizedPrefix}${path}`;
131
- this.addRouteHandler(fullPath, method, handler, combinedMiddleware.length > 0
132
- ? combinedMiddleware
133
- : undefined, routeOptions?.schema);
134
- return builder;
135
- });
114
+ const groupMiddleware = options?.middleware ?? [];
115
+ const createHandler = (method) => (path, handler, routeOptions) => {
116
+ const combinedMiddleware = [...groupMiddleware, ...(routeOptions?.middleware ?? [])];
117
+ const fullPath = path === '/' ? normalizedPrefix : `${normalizedPrefix}${path}`;
118
+ this.addRouteHandler(fullPath, method, handler, combinedMiddleware.length > 0 ? combinedMiddleware : undefined, routeOptions?.schema);
119
+ return builder;
136
120
  };
137
121
  const builder = {
138
122
  get: createHandler('GET'),
@@ -142,6 +126,7 @@ export class EcopagesApp {
142
126
  patch: createHandler('PATCH'),
143
127
  options: createHandler('OPTIONS'),
144
128
  head: createHandler('HEAD'),
129
+ query: createHandler('QUERY'),
145
130
  };
146
131
  callback?.(builder);
147
132
  return this;
@@ -150,6 +135,7 @@ export class EcopagesApp {
150
135
  const normalizedPrefix = group.prefix.endsWith('/') ? group.prefix.slice(0, -1) : group.prefix;
151
136
  const groupMiddleware = group.middleware ?? [];
152
137
  for (const route of group.routes) {
138
+ invariant(route.path !== '', `The ${route.method} handler in group "${group.prefix}" has no path. Export it from an endpoint file (\`*.api.ts\`, \`.api.tsx\`, \`.api.js\` or \`.api.jsx\`) under the pages directory, or give it a \`path\` ("/" for the group root) to register it with app.group().`);
153
139
  const normalizedPath = route.path.startsWith('/') ? route.path : `/${route.path}`;
154
140
  const fullPath = route.path === '/' ? normalizedPrefix : `${normalizedPrefix}${normalizedPath}`;
155
141
  const combinedMiddleware = [...groupMiddleware, ...(route.middleware ?? [])];
@@ -1,7 +1,7 @@
1
1
  import { WebSocketServer } from 'ws';
2
2
  import type { AppRuntime } from '../../config/assembly/app-runtime.js';
3
3
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
4
- import type { EcopagesWebSocketHandler } from '../../types/contracts.js';
4
+ import type { EcopagesWebSocketHandler, ErrorHandler } from '../../types/contracts.js';
5
5
  import type { ServerRequestPipeline } from '../shared/runtime/server-request-pipeline.js';
6
6
  import type { NodeServerInstance } from './server-adapter.js';
7
7
  export type DevSessionOptions = {
@@ -9,6 +9,8 @@ export type DevSessionOptions = {
9
9
  runtime: AppRuntime;
10
10
  server: NodeServerInstance;
11
11
  requestPipeline: ServerRequestPipeline;
12
+ /** The `app.onError` handler a prewarmed endpoint's errors resolve with. */
13
+ errorHandler?: ErrorHandler;
12
14
  websocketHandlers: Map<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>;
13
15
  onDevelopmentRestart?: (changedFile: string) => Promise<void>;
14
16
  configureResponseHandlers: () => void;
@@ -62,7 +62,10 @@ export class DevSession {
62
62
  this.prewarm = startDevStaticRoutePrewarm({
63
63
  pathnames: [...new Set(appConfig.devPrewarmPaths)],
64
64
  signal: this.prewarmAbort.signal,
65
- renderPath: (pathname) => this.options.requestPipeline.renderDevPrewarmPath(pathname, runtime.origin),
65
+ renderPath: (pathname) => this.options.requestPipeline.renderDevPrewarmPath(pathname, runtime.origin, {
66
+ errorHandler: this.options.errorHandler,
67
+ serverInstance: this.options.server,
68
+ }),
66
69
  });
67
70
  }
68
71
  dispose() {
@@ -149,6 +149,7 @@ export class NodeServerAdapter {
149
149
  await this.requestPipeline.initializeRouteHandling({
150
150
  staticRoutes: this.staticRoutes,
151
151
  errorPageLoaders: this.errorPageLoaders,
152
+ apiHandlers: this.apiHandlers,
152
153
  });
153
154
  }
154
155
  getServerOptions() {
@@ -167,10 +168,11 @@ export class NodeServerAdapter {
167
168
  async buildStatic(options) {
168
169
  await this.initialize();
169
170
  const baseUrl = resolveServeRuntimeOrigin(this.serveOptions);
170
- const { router, routeRendererFactory } = this.requestPipeline.getStaticBuildContext();
171
+ const { router, routeRendererFactory, importServerModule } = this.requestPipeline.getStaticBuildContext();
171
172
  await this.staticBuilder.build({ baseUrl, force: options?.force, keepGoing: options?.keepGoing }, {
172
173
  router,
173
174
  routeRendererFactory,
175
+ importServerModule,
174
176
  staticRoutes: this.staticRoutes,
175
177
  errorPageLoaders: this.errorPageLoaders,
176
178
  });
@@ -350,6 +352,7 @@ export class NodeServerAdapter {
350
352
  runtime: this.runtime,
351
353
  server,
352
354
  requestPipeline: this.requestPipeline,
355
+ errorHandler: this.errorHandler,
353
356
  websocketHandlers: this.websocketHandlers,
354
357
  onDevelopmentRestart: this.onDevelopmentRestart,
355
358
  configureResponseHandlers: () => this.requestPipeline.configureResponseHandlers({
@@ -359,6 +362,7 @@ export class NodeServerAdapter {
359
362
  createWatchRefreshCallback: () => this.requestPipeline.createWatchRefreshCallback({
360
363
  staticRoutes: this.staticRoutes,
361
364
  errorPageLoaders: this.errorPageLoaders,
365
+ apiHandlers: this.apiHandlers,
362
366
  }),
363
367
  });
364
368
  await this.devSession.start();
@@ -85,8 +85,8 @@ export class ApiRequestPipeline {
85
85
  appLogger.error('[ecopages] Error in custom error handler', handlerError);
86
86
  }
87
87
  }
88
- if (error instanceof HttpError)
89
- return error.toResponse();
88
+ if (HttpError.isHttpError(error))
89
+ return HttpError.responseFor(error);
90
90
  appLogger.error('[ecopages] Error handling request', error);
91
91
  return new Response('Internal Server Error', { status: 500 });
92
92
  }
@@ -1,46 +1,61 @@
1
- import type { ApiHandler, ApiHandlerContext, Middleware, RenderOptions, RouteSchema, TypedGroupHandlerContext } from '../../../types/contracts.js';
1
+ import type { ApiHandler, ApiHandlerContext, MiddlewareContext, MiddlewareList, RenderOptions, RouteHandlerContext, RouteSchema } from '../../../types/contracts.js';
2
2
  type UniversalContext = ApiHandlerContext<Request, unknown>;
3
- type SchemaHandlerContext<TSchema extends RouteSchema | undefined, TContext extends UniversalContext> = TSchema extends RouteSchema ? TypedGroupHandlerContext<TSchema, TContext> : TContext;
4
- type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema | undefined, TContext extends UniversalContext> = Omit<ApiHandler<TPath, Request, unknown>, 'handler' | 'middleware' | 'schema' | 'method'> & {
5
- handler: (context: SchemaHandlerContext<TSchema, TContext>) => Promise<Response> | Response;
6
- middleware?: Middleware<Request, unknown, TContext>[];
3
+ type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema, TContext extends UniversalContext, TMiddleware extends MiddlewareList<Request, unknown>> = Omit<ApiHandler<TPath, Request, unknown>, 'handler' | 'middleware' | 'schema' | 'method' | 'path'> & {
4
+ handler: (context: RouteHandlerContext<TSchema, TContext & MiddlewareContext<TMiddleware>>) => Promise<Response> | Response;
5
+ middleware?: TMiddleware;
7
6
  schema?: TSchema;
8
7
  };
9
- export declare function defineApiHandler<TPath extends string, TSchema extends RouteSchema | undefined = undefined, TContext extends UniversalContext = UniversalContext>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
8
+ /**
9
+ * A define helper bound to one HTTP method.
10
+ *
11
+ * @typeParam TContext - The context the handler starts from: the base context, or the group's
12
+ * @typeParam TPathOptional - Whether `path` may be omitted, as an endpoint file export omits it
13
+ *
14
+ * @remarks
15
+ * Without `path` the returned `path` is `''`, which `app.add` and `app.group` reject.
16
+ */
17
+ type DefineApiMethod<TContext extends UniversalContext, TPathOptional extends boolean = false> = <const TPath extends string = '', TSchema extends RouteSchema = RouteSchema, THandlerContext extends TContext = TContext, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, THandlerContext, TMiddleware> & (TPathOptional extends true ? {
18
+ path?: TPath;
19
+ } : {
20
+ path: TPath;
21
+ })) => ApiHandler<TPath, Request, unknown>;
22
+ /**
23
+ * @remarks
24
+ * The returned handler's context is the base context: the typed one, narrowed by the schema and the
25
+ * middleware, is erased by the cast, as `app.add` would erase it. The middleware list needs no cast.
26
+ */
27
+ export declare function defineApiHandler<TPath extends string, TSchema extends RouteSchema = RouteSchema, TContext extends UniversalContext = UniversalContext, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
28
+ path: TPath;
10
29
  method: ApiHandler<TPath, Request, unknown>['method'];
11
30
  }): ApiHandler<TPath, Request, unknown>;
12
- declare const defineApiMethod: <M extends ApiHandler["method"]>(method: M) => <const TPath extends string, TSchema extends RouteSchema | undefined = undefined, TContext extends UniversalContext = UniversalContext>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
13
- path: TPath;
14
- }) => ApiHandler<TPath, Request, unknown>;
15
- export declare const defineGet: ReturnType<typeof defineApiMethod<'GET'>>;
16
- export declare const definePost: ReturnType<typeof defineApiMethod<'POST'>>;
17
- export declare const definePut: ReturnType<typeof defineApiMethod<'PUT'>>;
18
- export declare const defineDelete: ReturnType<typeof defineApiMethod<'DELETE'>>;
19
- export declare const definePatch: ReturnType<typeof defineApiMethod<'PATCH'>>;
20
- export declare const defineOptions: ReturnType<typeof defineApiMethod<'OPTIONS'>>;
21
- export declare const defineHead: ReturnType<typeof defineApiMethod<'HEAD'>>;
31
+ /** The method helper an endpoint file exports from: `path` may be omitted. */
32
+ type EndpointMethod = DefineApiMethod<UniversalContext, true>;
33
+ export declare const defineGet: EndpointMethod;
34
+ export declare const definePost: EndpointMethod;
35
+ export declare const definePut: EndpointMethod;
36
+ export declare const defineDelete: EndpointMethod;
37
+ export declare const definePatch: EndpointMethod;
38
+ export declare const defineOptions: EndpointMethod;
39
+ export declare const defineHead: EndpointMethod;
40
+ /** Defines a handler for the QUERY method, a safe, idempotent read whose request body carries the query. */
41
+ export declare const defineQuery: EndpointMethod;
22
42
  export declare function json(data: unknown, options?: RenderOptions): Response;
23
43
  export declare function html(content: string, options?: RenderOptions): Response;
24
44
  export declare function redirect(url: string, status?: number): Response;
25
45
  export interface GroupHandler<TPrefix extends string = string> {
26
46
  prefix: TPrefix;
27
- middleware?: readonly Middleware<Request, unknown, any>[];
47
+ middleware?: MiddlewareList<Request, unknown>;
28
48
  routes: readonly ApiHandler<string, Request, unknown>[];
29
49
  }
30
50
  type GroupDefineHandler<TContext extends UniversalContext> = {
31
- <const TPath extends string, TSchema extends RouteSchema | undefined = undefined>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
51
+ <const TPath extends string, TSchema extends RouteSchema = RouteSchema, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
32
52
  path: TPath;
33
53
  method: ApiHandler<TPath, Request, unknown>['method'];
34
54
  }): ApiHandler<TPath, Request, unknown>;
35
- get: ReturnType<typeof defineApiMethod<'GET'>>;
36
- post: ReturnType<typeof defineApiMethod<'POST'>>;
37
- put: ReturnType<typeof defineApiMethod<'PUT'>>;
38
- delete: ReturnType<typeof defineApiMethod<'DELETE'>>;
39
- patch: ReturnType<typeof defineApiMethod<'PATCH'>>;
40
- options: ReturnType<typeof defineApiMethod<'OPTIONS'>>;
41
- head: ReturnType<typeof defineApiMethod<'HEAD'>>;
55
+ } & {
56
+ [M in ApiHandler['method'] as Lowercase<M>]: DefineApiMethod<TContext>;
42
57
  };
43
- export declare function defineGroupHandler<TPrefix extends string, TMiddleware extends readonly Middleware<Request, unknown, any>[] = [], TContext extends UniversalContext = TMiddleware extends readonly Middleware<Request, unknown, infer TGroupContext>[] ? TGroupContext : UniversalContext>(config: {
58
+ export declare function defineGroupHandler<TPrefix extends string, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>, TContext extends UniversalContext = UniversalContext & MiddlewareContext<TMiddleware>>(config: {
44
59
  prefix: TPrefix;
45
60
  middleware?: TMiddleware;
46
61
  routes: (api: GroupDefineHandler<TContext>) => readonly ApiHandler<string, Request, unknown>[];
@@ -1,8 +1,19 @@
1
1
  import { createBodyResponse } from './create-body-response.js';
2
+ /**
3
+ * @remarks
4
+ * The returned handler's context is the base context: the typed one, narrowed by the schema and the
5
+ * middleware, is erased by the cast, as `app.add` would erase it. The middleware list needs no cast.
6
+ */
2
7
  export function defineApiHandler(handler) {
3
8
  return handler;
4
9
  }
5
- const defineApiMethod = (method) => (handler) => defineApiHandler({ ...handler, method });
10
+ function defineApiMethod(method) {
11
+ return ((handler) => ({
12
+ ...handler,
13
+ path: handler.path ?? '',
14
+ method,
15
+ }));
16
+ }
6
17
  export const defineGet = defineApiMethod('GET');
7
18
  export const definePost = defineApiMethod('POST');
8
19
  export const definePut = defineApiMethod('PUT');
@@ -10,6 +21,8 @@ export const defineDelete = defineApiMethod('DELETE');
10
21
  export const definePatch = defineApiMethod('PATCH');
11
22
  export const defineOptions = defineApiMethod('OPTIONS');
12
23
  export const defineHead = defineApiMethod('HEAD');
24
+ /** Defines a handler for the QUERY method, a safe, idempotent read whose request body carries the query. */
25
+ export const defineQuery = defineApiMethod('QUERY');
13
26
  export function json(data, options) {
14
27
  return createBodyResponse('json', data, {
15
28
  status: options?.status,
@@ -38,6 +51,7 @@ function createGroupApi() {
38
51
  patch: defineApiMethod('PATCH'),
39
52
  options: defineApiMethod('OPTIONS'),
40
53
  head: defineApiMethod('HEAD'),
54
+ query: defineApiMethod('QUERY'),
41
55
  });
42
56
  }
43
57
  export function defineGroupHandler(config) {
@@ -0,0 +1,46 @@
1
+ import type { RouteMatch, TemplateRoute } from '../../../router/server/route-registry.js';
2
+ import { type ApiHandler, type ApiHandlerMethod, type ErrorHandler } from '../../../types/contracts.js';
3
+ import type { ApiRequestPipeline } from './api-request-pipeline.js';
4
+ type EndpointHandler = ApiHandler<string, Request, unknown>;
5
+ /** The per-request values an endpoint needs so its errors reach `app.onError`. */
6
+ export type EndpointRequestContext = {
7
+ errorHandler?: ErrorHandler<Request, unknown>;
8
+ serverInstance?: unknown;
9
+ };
10
+ export type EndpointRouteHandlerOptions = {
11
+ apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
12
+ /** The server-module loader Pages use, so a dev save drops the cached endpoint module. */
13
+ importServerModule: (filePath: string) => Promise<Record<string, unknown>>;
14
+ };
15
+ type EndpointFile = Pick<TemplateRoute, 'pathname' | 'filePath'>;
16
+ /**
17
+ * Reads the method handlers an endpoint module exports, keyed in `Allow` header order.
18
+ *
19
+ * @remarks
20
+ * Exports other than the method names are ignored. A method export that is not a method-helper
21
+ * result, is built for another method, or sets `path` fails the load: the file is the one owner of
22
+ * the URL.
23
+ */
24
+ export declare function readEndpointHandlers(module: Record<string, unknown>, { filePath, pathname }: EndpointFile): ReadonlyMap<ApiHandlerMethod, EndpointHandler>;
25
+ /**
26
+ * Lists one warning per Explicit Route registered on the same pathname as an endpoint file.
27
+ *
28
+ * @remarks
29
+ * Explicit Routes match first, so each one keeps its method and the file answers the rest.
30
+ * `:slug` and `[slug]` are the same slot, as are `*` and `[...slug]`.
31
+ */
32
+ export declare function findExplicitRoutesOnEndpoints(apiHandlers: readonly Pick<ApiHandler, 'method' | 'path'>[], templateRoutes: readonly Pick<TemplateRoute, 'pathname' | 'filePath' | 'role'>[]): string[];
33
+ /**
34
+ * Answers a request matched to an endpoint Template Route through the API pipeline.
35
+ *
36
+ * @remarks
37
+ * The module is imported on every request; the server-module loader caches it until a dev save
38
+ * invalidates it. A load error resolves like a handler error, through `app.onError`.
39
+ */
40
+ export declare class EndpointRouteHandler {
41
+ private readonly apiRequestPipeline;
42
+ private readonly importServerModule;
43
+ constructor({ apiRequestPipeline, importServerModule }: EndpointRouteHandlerOptions);
44
+ handleMatch(match: RouteMatch, request: Request, context: EndpointRequestContext): Promise<Response>;
45
+ }
46
+ export {};
@@ -0,0 +1,96 @@
1
+ import { segmentPathPatternKey } from '../../../router/server/segment-path-matcher.js';
2
+ import { API_HANDLER_METHODS, } from '../../../types/contracts.js';
3
+ import { invariant } from '../../../utils/invariant.js';
4
+ function isApiHandler(value) {
5
+ return (typeof value === 'object' &&
6
+ value !== null &&
7
+ 'handler' in value &&
8
+ typeof value.handler === 'function' &&
9
+ 'method' in value &&
10
+ typeof value.method === 'string');
11
+ }
12
+ function methodHelperName(method) {
13
+ return `define${method[0]}${method.slice(1).toLowerCase()}`;
14
+ }
15
+ /**
16
+ * Reads the method handlers an endpoint module exports, keyed in `Allow` header order.
17
+ *
18
+ * @remarks
19
+ * Exports other than the method names are ignored. A method export that is not a method-helper
20
+ * result, is built for another method, or sets `path` fails the load: the file is the one owner of
21
+ * the URL.
22
+ */
23
+ export function readEndpointHandlers(module, { filePath, pathname }) {
24
+ const handlers = new Map();
25
+ for (const method of API_HANDLER_METHODS) {
26
+ const value = module[method];
27
+ if (value === undefined) {
28
+ continue;
29
+ }
30
+ const exportName = `${filePath}: the ${method} export of the endpoint "${pathname}"`;
31
+ invariant(isApiHandler(value), `${exportName} is not a request handler. Build it with ${methodHelperName(method)}().`);
32
+ invariant(value.method === method, `${exportName} is a ${value.method} handler. Build it with ${methodHelperName(method)}().`);
33
+ invariant(!value.path, `${exportName} sets path "${value.path}". The file gives the endpoint its path; remove path.`);
34
+ handlers.set(method, value);
35
+ }
36
+ invariant(handlers.size > 0, `${filePath} defines the endpoint "${pathname}" but exports no request handler. Export at least one of ${API_HANDLER_METHODS.join(', ')}, built with defineGet() or another method helper.`);
37
+ return handlers;
38
+ }
39
+ /**
40
+ * Lists one warning per Explicit Route registered on the same pathname as an endpoint file.
41
+ *
42
+ * @remarks
43
+ * Explicit Routes match first, so each one keeps its method and the file answers the rest.
44
+ * `:slug` and `[slug]` are the same slot, as are `*` and `[...slug]`.
45
+ */
46
+ export function findExplicitRoutesOnEndpoints(apiHandlers, templateRoutes) {
47
+ const endpointsByKey = new Map(templateRoutes
48
+ .filter((route) => route.role === 'endpoint')
49
+ .map((route) => [segmentPathPatternKey(route.pathname, 'filesystem'), route]));
50
+ return apiHandlers.flatMap(({ method, path }) => {
51
+ const endpoint = endpointsByKey.get(segmentPathPatternKey(path, 'api'));
52
+ return endpoint
53
+ ? [
54
+ `The app route ${method} ${path} and the endpoint file ${endpoint.filePath} both answer "${endpoint.pathname}". The app route answers ${method}; the file answers its other methods.`,
55
+ ]
56
+ : [];
57
+ });
58
+ }
59
+ /**
60
+ * Answers a request matched to an endpoint Template Route through the API pipeline.
61
+ *
62
+ * @remarks
63
+ * The module is imported on every request; the server-module loader caches it until a dev save
64
+ * invalidates it. A load error resolves like a handler error, through `app.onError`.
65
+ */
66
+ export class EndpointRouteHandler {
67
+ apiRequestPipeline;
68
+ importServerModule;
69
+ constructor({ apiRequestPipeline, importServerModule }) {
70
+ this.apiRequestPipeline = apiRequestPipeline;
71
+ this.importServerModule = importServerModule;
72
+ }
73
+ async handleMatch(match, request, context) {
74
+ const { errorHandler, serverInstance } = context;
75
+ let handlers;
76
+ try {
77
+ const module = await this.importServerModule(match.templateRoute.filePath);
78
+ handlers = readEndpointHandlers(module, match.templateRoute);
79
+ }
80
+ catch (error) {
81
+ return await this.apiRequestPipeline.handleError(error, {
82
+ request,
83
+ params: match.params,
84
+ serverInstance,
85
+ errorHandler,
86
+ });
87
+ }
88
+ const requestMethod = request.method.toUpperCase();
89
+ const method = API_HANDLER_METHODS.find((candidate) => candidate === requestMethod);
90
+ const handler = method && handlers.get(method);
91
+ if (!handler) {
92
+ return new Response(null, { status: 405, headers: { Allow: [...handlers.keys()].join(', ') } });
93
+ }
94
+ return await this.apiRequestPipeline.execute(request, match.params, handler, serverInstance, errorHandler);
95
+ }
96
+ }