@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.
- package/README.md +19 -3
- package/package.json +3 -3
- package/src/adapters/node/create-app.d.ts +19 -19
- package/src/adapters/node/create-app.js +26 -40
- package/src/adapters/node/dev-session.d.ts +3 -1
- package/src/adapters/node/dev-session.js +4 -1
- package/src/adapters/node/server-adapter.js +5 -1
- package/src/adapters/shared/http/api-request-pipeline.js +2 -2
- package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
- package/src/adapters/shared/http/define-api-handler.js +15 -1
- package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
- package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
- package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
- package/src/adapters/shared/runtime/server-request-pipeline.js +46 -12
- package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
- package/src/adapters/shared/runtime/server-route-handler.js +16 -10
- package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
- package/src/adapters/shared/runtime/server-static-builder.js +13 -2
- package/src/assets/app-browser-client-build.js +8 -21
- package/src/assets/app-browser-client-manifest.d.ts +0 -1
- package/src/assets/app-browser-client-manifest.js +1 -20
- package/src/build/contracts/content-virtual-modules.d.ts +9 -3
- package/src/build/contracts/content-virtual-modules.js +11 -5
- package/src/build/contracts.d.ts +1 -1
- package/src/build/contracts.js +1 -1
- package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
- package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
- package/src/build/server-bundle-deploy-manifest.js +1 -1
- package/src/build.d.ts +1 -1
- package/src/build.js +1 -1
- package/src/config/assembly/finalize-config.js +5 -0
- package/src/dev/transform-server/dev-transform-server.js +1 -1
- package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
- package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
- package/src/errors/http-error.d.ts +9 -0
- package/src/errors/http-error.js +11 -0
- package/src/html/html-transformer.service.d.ts +0 -21
- package/src/html/html-transformer.service.js +0 -32
- package/src/html-pages/html-page-renderer.d.ts +2 -1
- package/src/html-pages/html-page-renderer.js +5 -3
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/integration.d.ts +1 -2
- package/src/integration.js +0 -1
- package/src/islands/island-host.d.ts +1 -2
- package/src/islands/island-host.js +1 -2
- package/src/plugins/integration-plugin.d.ts +1 -1
- package/src/plugins/processor.d.ts +1 -1
- package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
- package/src/plugins/tsconfig-import-resolver.js +4 -2
- package/src/processor.d.ts +1 -1
- package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
- package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
- package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
- package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
- package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
- package/src/route-renderer/orchestration/integration-renderer.d.ts +20 -44
- package/src/route-renderer/orchestration/integration-renderer.js +52 -115
- package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
- package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
- package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
- package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
- package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
- package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
- package/src/router/server/route-registry.d.ts +20 -9
- package/src/router/server/route-registry.js +52 -30
- package/src/router/server/segment-path-matcher.d.ts +8 -0
- package/src/router/server/segment-path-matcher.js +15 -0
- package/src/static-site-generator/production-page-browser-graph-prebuild.js +0 -4
- package/src/static-site-generator/static-site-generator.js +1 -1
- package/src/types/build-types.d.ts +6 -0
- package/src/types/contracts.d.ts +93 -65
- package/src/types/contracts.js +4 -1
- package/src/types/eco-api-types.d.ts +1 -1
- package/src/types/public-types.d.ts +1 -1
- package/src/utils/endpoint-file-extensions.d.ts +11 -0
- package/src/utils/endpoint-file-extensions.js +13 -0
- package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
- 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
|
|
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,
|
|
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
|
+
"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.
|
|
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.
|
|
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,
|
|
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?:
|
|
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
|
|
72
|
-
get
|
|
73
|
-
post
|
|
74
|
-
put
|
|
75
|
-
delete
|
|
76
|
-
patch
|
|
77
|
-
options
|
|
78
|
-
head
|
|
79
|
-
|
|
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
|
-
*
|
|
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
|
|
86
|
-
middleware?:
|
|
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
|
-
|
|
74
|
-
return this.addRouteHandler(path, method, handler, options?.middleware, options?.schema);
|
|
75
|
-
}
|
|
76
|
-
get
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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.
|
|
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
|
-
*
|
|
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
|
|
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 =
|
|
124
|
-
const createHandler = (method) => {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
|
89
|
-
return
|
|
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,
|
|
1
|
+
import type { ApiHandler, ApiHandlerContext, MiddlewareContext, MiddlewareList, RenderOptions, RouteHandlerContext, RouteSchema } from '../../../types/contracts.js';
|
|
2
2
|
type UniversalContext = ApiHandlerContext<Request, unknown>;
|
|
3
|
-
type
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
export declare const
|
|
16
|
-
export declare const
|
|
17
|
-
export declare const
|
|
18
|
-
export declare const
|
|
19
|
-
export declare const
|
|
20
|
-
export declare const
|
|
21
|
-
|
|
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?:
|
|
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
|
|
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
|
-
|
|
36
|
-
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|