-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
render-context.ts
248 lines (239 loc) · 6.89 KB
/
render-context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import type {
APIContext,
ComponentInstance,
MiddlewareHandler,
RouteData,
} from '../@types/astro.js';
import { renderEndpoint } from '../runtime/server/endpoint.js';
import { attachCookiesToResponse } from './cookies/index.js';
import { callMiddleware } from './middleware/callMiddleware.js';
import { sequence } from './middleware/index.js';
import { AstroCookies } from './cookies/index.js';
import { createResult } from './render/index.js';
import { renderPage } from '../runtime/server/index.js';
import {
ASTRO_VERSION,
ROUTE_TYPE_HEADER,
clientAddressSymbol,
clientLocalsSymbol,
} from './constants.js';
import { getParams, getProps, type Pipeline } from './render/index.js';
import { AstroError, AstroErrorData } from './errors/index.js';
import {
computeCurrentLocale,
computePreferredLocale,
computePreferredLocaleList,
} from '../i18n/utils.js';
import { renderRedirect } from './redirects/render.js';
export class RenderContext {
private constructor(
readonly pipeline: Pipeline,
public locals: App.Locals,
readonly middleware: MiddlewareHandler,
readonly pathname: string,
readonly request: Request,
readonly routeData: RouteData,
public status: number,
readonly cookies = new AstroCookies(request),
readonly params = getParams(routeData, pathname)
) {}
static create({
locals = {},
middleware,
pathname,
pipeline,
request,
routeData,
status = 200,
}: Pick<RenderContext, 'pathname' | 'pipeline' | 'request' | 'routeData'> &
Partial<Pick<RenderContext, 'locals' | 'middleware' | 'status'>>) {
return new RenderContext(
pipeline,
locals,
sequence(...pipeline.internalMiddleware, middleware ?? pipeline.middleware),
pathname,
request,
routeData,
status
);
}
/**
* The main function of the RenderContext.
*
* Use this function to render any route known to Astro.
* It attempts to render a route. A route can be a:
*
* - page
* - redirect
* - endpoint
* - fallback
*/
async render(componentInstance: ComponentInstance | undefined): Promise<Response> {
const { cookies, middleware, pathname, pipeline, routeData } = this;
const { logger, routeCache, serverLike, streaming } = pipeline;
const props = await getProps({
mod: componentInstance,
routeData,
routeCache,
pathname,
logger,
serverLike,
});
const apiContext = this.createAPIContext(props);
const { type } = routeData;
const lastNext =
type === 'endpoint'
? () => renderEndpoint(componentInstance as any, apiContext, serverLike, logger)
: type === 'redirect'
? () => renderRedirect(this)
: type === 'page'
? async () => {
const result = await this.createResult(componentInstance!);
const response = await renderPage(
result,
componentInstance?.default as any,
props,
{},
streaming,
routeData
);
response.headers.set(ROUTE_TYPE_HEADER, 'page');
return response;
}
: type === 'fallback'
? () =>
new Response(null, { status: 500, headers: { [ROUTE_TYPE_HEADER]: 'fallback' } })
: () => {
throw new Error('Unknown type of route: ' + type);
};
const response = await callMiddleware(middleware, apiContext, lastNext);
if (response.headers.get(ROUTE_TYPE_HEADER)) {
response.headers.delete(ROUTE_TYPE_HEADER);
}
// LEGACY: we put cookies on the response object,
// where the adapter might be expecting to read it.
// New code should be using `app.render({ addCookieHeader: true })` instead.
attachCookiesToResponse(response, cookies);
return response;
}
createAPIContext(props: APIContext['props']): APIContext {
const renderContext = this;
const { cookies, i18nData, params, pipeline, request } = this;
const { currentLocale, preferredLocale, preferredLocaleList } = i18nData;
const generator = `Astro v${ASTRO_VERSION}`;
const redirect = (path: string, status = 302) =>
new Response(null, { status, headers: { Location: path } });
const site = pipeline.site ? new URL(pipeline.site) : undefined;
const url = new URL(request.url);
return {
cookies,
currentLocale,
generator,
params,
preferredLocale,
preferredLocaleList,
props,
redirect,
request,
site,
url,
get clientAddress() {
if (clientAddressSymbol in request) {
return Reflect.get(request, clientAddressSymbol) as string;
}
if (pipeline.adapterName) {
throw new AstroError({
...AstroErrorData.ClientAddressNotAvailable,
message: AstroErrorData.ClientAddressNotAvailable.message(pipeline.adapterName),
});
} else {
throw new AstroError(AstroErrorData.StaticClientAddressNotAvailable);
}
},
get locals() {
return renderContext.locals;
},
// TODO(breaking): disallow replacing the locals object
set locals(val) {
if (typeof val !== 'object') {
throw new AstroError(AstroErrorData.LocalsNotAnObject);
} else {
renderContext.locals = val;
// we also put it on the original Request object,
// where the adapter might be expecting to read it after the response.
Reflect.set(request, clientLocalsSymbol, val);
}
},
};
}
async createResult(mod: ComponentInstance) {
const { cookies, locals, params, pathname, pipeline, request, routeData, status } = this;
const {
adapterName,
clientDirectives,
compressHTML,
i18n,
manifest,
logger,
renderers,
resolve,
site,
serverLike,
} = pipeline;
const { links, scripts, styles } = await pipeline.headElements(routeData);
const componentMetadata =
(await pipeline.componentMetadata(routeData)) ?? manifest.componentMetadata;
const { defaultLocale, locales, strategy } = i18n ?? {};
const partial = Boolean(mod.partial);
return createResult({
adapterName,
clientDirectives,
componentMetadata,
compressHTML,
cookies,
defaultLocale,
locales,
locals,
logger,
links,
params,
partial,
pathname,
renderers,
resolve,
request,
route: routeData.route,
strategy,
site,
scripts,
ssr: serverLike,
status,
styles,
});
}
/**
* API Context may be created multiple times per request, i18n data needs to be computed only once.
* So, it is computed and saved here on creation of the first APIContext and reused for later ones.
*/
#i18nData?: Pick<APIContext, 'currentLocale' | 'preferredLocale' | 'preferredLocaleList'>;
get i18nData() {
if (this.#i18nData) return this.#i18nData;
const {
pipeline: { i18n },
request,
routeData,
} = this;
if (!i18n)
return {
currentLocale: undefined,
preferredLocale: undefined,
preferredLocaleList: undefined,
};
const { defaultLocale, locales, strategy } = i18n;
return (this.#i18nData = {
currentLocale: computeCurrentLocale(routeData.route, locales, strategy, defaultLocale),
preferredLocale: computePreferredLocale(request, locales),
preferredLocaleList: computePreferredLocaleList(request, locales),
});
}
}