-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathserver-runtime.ts
More file actions
240 lines (228 loc) · 6.06 KB
/
server-runtime.ts
File metadata and controls
240 lines (228 loc) · 6.06 KB
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
import { type Component } from "solid-js";
import {
pushRequest,
pushResponse,
} from "../shared/server-function-inspector/server-function-tracker";
import {
deserializeJSONStream,
deserializeJSStream,
// serializeToJSONStream,
serializeToJSONString,
} from "./serialization.ts";
import { BODY_FORMAL_FILE, BODY_FORMAT_KEY, BodyFormat } from "./server-functions-shared.ts";
let INSTANCE = 0;
async function createRequest(
base: string,
id: string,
instance: string,
options: RequestInit,
) {
const request = new Request(base, {
method: "POST",
...options,
headers: {
...options.headers,
"X-Server-Id": id,
"X-Server-Instance": instance,
},
});
if (import.meta.env.DEV) {
pushRequest(id, instance, request.clone());
}
const response = await fetch(request);
if (import.meta.env.DEV) {
pushResponse(id, instance, response.clone());
}
return response;
}
function getHeadersAndBody(body: any): {
headers?: HeadersInit;
body: BodyInit;
} | undefined {
switch (true) {
case typeof body === "string":
return {
headers: {
"Content-Type": "text/plain",
[BODY_FORMAT_KEY]: BodyFormat.String,
},
body,
};
case body instanceof FormData:
return {
headers: {
"Content-Type": "multipart/form-data",
[BODY_FORMAT_KEY]: BodyFormat.FormData,
},
body,
};
case body instanceof URLSearchParams:
return {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
[BODY_FORMAT_KEY]: BodyFormat.URLSearchParams,
},
body,
};
case body instanceof File: {
const formData = new FormData();
formData.append(BODY_FORMAL_FILE, body, body.name);
return {
headers: {
[BODY_FORMAT_KEY]: BodyFormat.File,
},
body: formData,
};
}
case body instanceof Blob:
return {
headers: {
[BODY_FORMAT_KEY]: BodyFormat.Blob,
},
body,
};
case body instanceof ArrayBuffer:
return {
headers: {
[BODY_FORMAT_KEY]: BodyFormat.ArrayBuffer,
},
body,
};
case body instanceof Uint8Array:
return {
headers: {
[BODY_FORMAT_KEY]: BodyFormat.Uint8Array,
},
body: new Uint8Array(body),
};
default:
return undefined;
}
}
async function initializeResponse(
base: string,
id: string,
instance: string,
options: RequestInit,
args: any[],
) {
// No args, skip serialization
if (args.length === 0) {
return createRequest(base, id, instance, options);
}
// For single arguments, we can directly encode as body
if (args.length === 1) {
const body = args[0];
const result = getHeadersAndBody(body);
if (result) {
return createRequest(base, id, instance, {
...options,
body: result.body,
headers: {
...options.headers,
...result.headers,
},
});
}
}
// Fallback to seroval
return createRequest(base, id, instance, {
...options,
// TODO(Alexis): move to serializeToJSONStream
body: await serializeToJSONString(args),
// duplex: 'half',
// body: serializeToJSONStream(args),
headers: {
...options.headers,
"Content-Type": "text/plain",
[BODY_FORMAT_KEY]: BodyFormat.Seroval,
},
});
}
async function fetchServerFunction(
base: string,
id: string,
options: Omit<RequestInit, "body">,
args: any[],
) {
const instance = `server-fn:${INSTANCE++}`;
const response = await initializeResponse(base, id, instance, options, args);
if (
response.headers.has("Location") ||
response.headers.has("X-Revalidate") ||
response.headers.has("X-Single-Flight")
) {
if (response.body) {
/* @ts-ignore-next-line */
response.customBody = () => {
if (import.meta.env.SEROVAL_MODE === "js") {
return deserializeJSStream(instance, response.clone());
}
return deserializeJSONStream(response.clone());
};
}
return response;
}
const contentType = response.headers.get("Content-Type");
const clone = response.clone();
let result;
if (contentType?.startsWith("text/plain")) {
result = await clone.text();
} else if (contentType?.startsWith("application/json")) {
result = await clone.json();
} else if (response.headers.get(BODY_FORMAT_KEY)) {
if (import.meta.env.SEROVAL_MODE === "js") {
result = await deserializeJSStream(instance, clone);
} else {
result = await deserializeJSONStream(clone);
}
}
if (response.headers.has("X-Error")) {
throw result;
}
return result;
}
export function createServerReference(id: string) {
let baseURL = import.meta.env.BASE_URL ?? "/";
if (!baseURL.endsWith("/")) baseURL += "/";
const fn = (...args: any[]) =>
fetchServerFunction(`${baseURL}_server`, id, {}, args);
return new Proxy(fn, {
get(target, prop, receiver) {
if (prop === "url") {
return `${baseURL}_server?id=${encodeURIComponent(id)}`;
}
if (prop === "GET") {
return receiver.withOptions({ method: "GET" });
}
if (prop === "withOptions") {
const url = `${baseURL}_server?id=${encodeURIComponent(id)}`;
return (options: RequestInit) => {
const fn = async (...args: any[]) => {
const encodeArgs =
options.method && options.method.toUpperCase() === "GET";
return fetchServerFunction(
encodeArgs
? url +
(args.length
? `&args=${encodeURIComponent(
await serializeToJSONString(args),
)}`
: "")
: `${baseURL}_server`,
id,
options,
encodeArgs ? [] : args,
);
};
fn.url = url;
return fn;
};
}
return (target as any)[prop];
},
});
}
export function createClientReference(Component: Component<any>, id: string) {
return Component;
}