/
result.ts
274 lines (245 loc) · 7.55 KB
/
result.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import type { MarkdownRenderingOptions } from '@astrojs/markdown-remark';
import type {
AstroGlobal,
AstroGlobalPartial,
Params,
Props,
RuntimeMode,
SSRElement,
SSRLoadedRenderer,
SSRResult,
} from '../../@types/astro';
import {
renderSlotToString,
stringifyChunk,
type ComponentSlots,
} from '../../runtime/server/index.js';
import { renderJSX } from '../../runtime/server/jsx.js';
import { AstroCookies } from '../cookies/index.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
import { warn, type LogOptions } from '../logger/core.js';
import { isHTMLString } from '../../runtime/server/escape.js';
const clientAddressSymbol = Symbol.for('astro.clientAddress');
const responseSentSymbol = Symbol.for('astro.responseSent');
function onlyAvailableInSSR(name: 'Astro.redirect') {
return function _onlyAvailableInSSR() {
switch (name) {
case 'Astro.redirect':
throw new AstroError(AstroErrorData.StaticRedirectNotAvailable);
}
};
}
export interface CreateResultArgs {
adapterName: string | undefined;
ssr: boolean;
logging: LogOptions;
origin: string;
markdown: MarkdownRenderingOptions;
mode: RuntimeMode;
params: Params;
pathname: string;
props: Props;
renderers: SSRLoadedRenderer[];
clientDirectives: Map<string, string>;
resolve: (s: string) => Promise<string>;
site: string | undefined;
links?: Set<SSRElement>;
scripts?: Set<SSRElement>;
styles?: Set<SSRElement>;
componentMetadata?: SSRResult['componentMetadata'];
request: Request;
status: number;
locals: App.Locals;
}
function getFunctionExpression(slot: any) {
if (!slot) return;
if (slot.expressions?.length !== 1) return;
return slot.expressions[0] as (...args: any[]) => any;
}
class Slots {
#result: SSRResult;
#slots: ComponentSlots | null;
#loggingOpts: LogOptions;
constructor(result: SSRResult, slots: ComponentSlots | null, logging: LogOptions) {
this.#result = result;
this.#slots = slots;
this.#loggingOpts = logging;
if (slots) {
for (const key of Object.keys(slots)) {
if ((this as any)[key] !== undefined) {
throw new AstroError({
...AstroErrorData.ReservedSlotName,
message: AstroErrorData.ReservedSlotName.message(key),
});
}
Object.defineProperty(this, key, {
get() {
return true;
},
enumerable: true,
});
}
}
}
public has(name: string) {
if (!this.#slots) return false;
return Boolean(this.#slots[name]);
}
public async render(name: string, args: any[] = []) {
if (!this.#slots || !this.has(name)) return;
const result = this.#result;
if (!Array.isArray(args)) {
warn(
this.#loggingOpts,
'Astro.slots.render',
`Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])`
);
} else if (args.length > 0) {
const slotValue = this.#slots[name];
const component = typeof slotValue === 'function' ? await slotValue(result) : await slotValue;
// Astro
const expression = getFunctionExpression(component);
if (expression) {
const slot = async () => isHTMLString(await expression) ? expression : expression(...args)
return await renderSlotToString(result, slot).then((res) =>{
return res != null ? String(res) : res
}
);
}
// JSX
if (typeof component === 'function') {
return await renderJSX(result, (component as any)(...args)).then((res) =>
res != null ? String(res) : res
);
}
}
const content = await renderSlotToString(result, this.#slots[name]);
const outHTML = stringifyChunk(result, content);
return outHTML;
}
}
let renderMarkdown: any = null;
export function createResult(args: CreateResultArgs): SSRResult {
const { markdown, params, pathname, renderers, clientDirectives, request, resolve, locals } =
args;
const url = new URL(request.url);
const headers = new Headers();
headers.set('Content-Type', 'text/html');
const response: ResponseInit = {
status: args.status,
statusText: 'OK',
headers,
};
// Make headers be read-only
Object.defineProperty(response, 'headers', {
value: response.headers,
enumerable: true,
writable: false,
});
// Astro.cookies is defined lazily to avoid the cost on pages that do not use it.
let cookies: AstroCookies | undefined = undefined;
let componentMetadata = args.componentMetadata ?? new Map();
// Create the result object that will be passed into the render function.
// This object starts here as an empty shell (not yet the result) but then
// calling the render() function will populate the object with scripts, styles, etc.
const result: SSRResult = {
styles: args.styles ?? new Set<SSRElement>(),
scripts: args.scripts ?? new Set<SSRElement>(),
links: args.links ?? new Set<SSRElement>(),
componentMetadata,
propagators: new Map(),
extraHead: [],
scope: 0,
cookies,
/** This function returns the `Astro` faux-global */
createAstro(
astroGlobal: AstroGlobalPartial,
props: Record<string, any>,
slots: Record<string, any> | null
) {
const astroSlots = new Slots(result, slots, args.logging);
const Astro: AstroGlobal = {
// @ts-expect-error
__proto__: astroGlobal,
get clientAddress() {
if (!(clientAddressSymbol in request)) {
if (args.adapterName) {
throw new AstroError({
...AstroErrorData.ClientAddressNotAvailable,
message: AstroErrorData.ClientAddressNotAvailable.message(args.adapterName),
});
} else {
throw new AstroError(AstroErrorData.StaticClientAddressNotAvailable);
}
}
return Reflect.get(request, clientAddressSymbol) as string;
},
get cookies() {
if (cookies) {
return cookies;
}
cookies = new AstroCookies(request);
result.cookies = cookies;
return cookies;
},
params,
props,
locals,
request,
url,
redirect: args.ssr
? (path, status) => {
// If the response is already sent, error as we cannot proceed with the redirect.
if ((request as any)[responseSentSymbol]) {
throw new AstroError({
...AstroErrorData.ResponseSentError,
});
}
return new Response(null, {
status: status || 302,
headers: {
Location: path,
},
});
}
: onlyAvailableInSSR('Astro.redirect'),
response: response as AstroGlobal['response'],
slots: astroSlots as unknown as AstroGlobal['slots'],
};
Object.defineProperty(Astro, '__renderMarkdown', {
// Ensure this API is not exposed to users
enumerable: false,
writable: false,
// TODO: Remove this hole "Deno" logic once our plugin gets Deno support
value: async function (content: string, opts: MarkdownRenderingOptions) {
// @ts-expect-error
if (typeof Deno !== 'undefined') {
throw new Error('Markdown is not supported in Deno SSR');
}
if (!renderMarkdown) {
// The package is saved in this variable because Vite is too smart
// and will try to inline it in buildtime
let astroRemark = '@astrojs/';
astroRemark += 'markdown-remark';
renderMarkdown = (await import(astroRemark)).renderMarkdown;
}
const { code } = await renderMarkdown(content, { ...markdown, ...(opts ?? {}) });
return code;
},
});
return Astro;
},
resolve,
_metadata: {
renderers,
pathname,
hasHydrationScript: false,
hasRenderedHead: false,
hasDirectives: new Set(),
headInTree: false,
clientDirectives,
},
response,
};
return result;
}