@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.20
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 +1 -1
- package/dist/server.dev.js +5065 -0
- package/dist/server.js +1757 -355
- package/dist/{server.cjs → server.observe.js} +1951 -558
- package/dist/{dev.cjs → web.dev.js} +945 -550
- package/dist/web.js +635 -332
- package/dist/{dev.js → web.observe.js} +688 -403
- package/frames/dist/assets.js +92 -0
- package/frames/dist/client.dev.js +1296 -1198
- package/frames/dist/client.js +1128 -1191
- package/frames/dist/client.observe.js +2041 -0
- package/frames/dist/regions.js +171 -0
- package/frames/dist/server.dev.js +2549 -0
- package/frames/dist/server.js +1688 -3005
- package/frames/dist/server.observe.js +2548 -0
- package/frames/dist/trace.js +45 -0
- package/frames/dist/wire.js +594 -0
- package/frames/package.json +2 -25
- package/package.json +244 -256
- package/performance-tracks/dist/performance-tracks.dev.js +679 -0
- package/performance-tracks/dist/performance-tracks.js +6 -0
- package/performance-tracks/dist/performance-tracks.observe.js +667 -0
- package/performance-tracks/package.json +7 -0
- package/performance-tracks/types/index.d.ts +69 -0
- package/serialization/decode/package.json +2 -15
- package/serialization/dist/decode.js +121 -25
- package/serialization/dist/serialization.js +242 -88
- package/serialization/package.json +2 -15
- package/serialization/types/index.d.ts +85 -158
- package/serialization/types/serializer-decode.d.ts +173 -114
- package/serialization/types/serializer.d.ts +109 -0
- package/server-functions/dist/client.dev.js +1462 -0
- package/server-functions/dist/client.js +667 -165
- package/server-functions/dist/client.observe.js +1441 -0
- package/server-functions/dist/rich-args.js +84 -1
- package/server-functions/dist/server.dev.js +2714 -297
- package/server-functions/dist/server.js +2595 -271
- package/server-functions/dist/server.observe.js +3594 -0
- package/server-functions/package.json +2 -35
- package/server-functions/rich-args/package.json +2 -15
- package/skills/server-components/SKILL.md +117 -0
- package/storage/package.json +2 -15
- package/types/client.d.ts +342 -288
- package/types/constants.d.ts +22 -0
- package/types/cookies.d.ts +32 -84
- package/types/diagnostics.d.ts +80 -0
- package/types/frames/assets-tier.d.ts +78 -0
- package/types/frames/client.d.ts +40 -1
- package/types/frames/frame-client.d.ts +443 -280
- package/types/frames/frame-container-plugin.d.ts +64 -0
- package/types/frames/frame-morph.d.ts +29 -0
- package/types/frames/frame-sink.d.ts +141 -161
- package/types/frames/frame-transport.d.ts +263 -184
- package/types/frames/regions-tier.d.ts +60 -0
- package/types/frames/serializer-decode.d.ts +241 -0
- package/types/frames/serializer.d.ts +85 -158
- package/types/frames/server.d.ts +2 -2
- package/types/frames/trace-tier.d.ts +2 -0
- package/types/frames/tree-rewrite.d.ts +39 -0
- package/types/frames/wire-tier.d.ts +169 -0
- package/types/head.d.ts +20 -0
- package/types/index.d.ts +98 -81
- package/types/index.server.d.ts +159 -0
- package/types/jsx.d.ts +49 -44
- package/types/observe.d.ts +535 -0
- package/types/reconcile.d.ts +1 -0
- package/types/render.d.ts +11 -0
- package/types/request-error-hook.d.ts +5 -0
- package/types/response.d.ts +95 -147
- package/types/serializer-decode.d.ts +173 -114
- package/types/serializer.d.ts +85 -158
- package/types/server-functions/argument-codec.d.ts +30 -0
- package/types/server-functions/client.d.ts +238 -223
- package/types/server-functions/flash.d.ts +28 -30
- package/types/server-functions/registry.d.ts +105 -0
- package/types/server-functions/rich-args.d.ts +1 -10
- package/types/server-functions/server.d.ts +539 -531
- package/types/server-functions/shared.d.ts +398 -425
- package/types/server-functions/uploads.d.ts +50 -0
- package/types/server-mock.d.ts +120 -13
- package/types/server-observe.d.ts +86 -0
- package/types/server.d.ts +571 -422
- package/types/trace.d.ts +127 -0
- package/LICENSE +0 -21
- package/dist/web.cjs +0 -2033
- package/frames/dist/client.cjs +0 -2002
- package/frames/dist/client.dev.cjs +0 -2022
- package/frames/dist/server.cjs +0 -3877
- package/serialization/dist/decode.cjs +0 -139
- package/serialization/dist/serialization.cjs +0 -261
- package/serialization/types-cjs/index.d.cts +0 -182
- package/serialization/types-cjs/package.json +0 -3
- package/serialization/types-cjs/serializer-decode.d.cts +0 -182
- package/server-functions/dist/client.cjs +0 -834
- package/server-functions/dist/rich-args.cjs +0 -11
- package/server-functions/dist/server.cjs +0 -1242
- package/server-functions/dist/server.dev.cjs +0 -1242
- package/storage/dist/storage.cjs +0 -12
- package/storage/types-cjs/index.d.cts +0 -28
- package/storage/types-cjs/package.json +0 -3
- package/types/core.d.ts +0 -9
- package/types-cjs/client.d.cts +0 -337
- package/types-cjs/cookies.d.cts +0 -93
- package/types-cjs/core.d.cts +0 -9
- package/types-cjs/frames/client.d.cts +0 -36
- package/types-cjs/frames/frame-client.d.cts +0 -356
- package/types-cjs/frames/frame-sink.d.cts +0 -194
- package/types-cjs/frames/frame-transport.d.cts +0 -222
- package/types-cjs/frames/serializer.d.cts +0 -182
- package/types-cjs/frames/server.d.cts +0 -52
- package/types-cjs/index.d.cts +0 -244
- package/types-cjs/jsx-properties.d.cts +0 -93
- package/types-cjs/jsx.d.cts +0 -4159
- package/types-cjs/package.json +0 -3
- package/types-cjs/response.d.cts +0 -174
- package/types-cjs/serializer-decode.d.cts +0 -182
- package/types-cjs/serializer.d.cts +0 -182
- package/types-cjs/server-functions/client.d.cts +0 -262
- package/types-cjs/server-functions/flash.d.cts +0 -38
- package/types-cjs/server-functions/rich-args.d.cts +0 -10
- package/types-cjs/server-functions/server.d.cts +0 -681
- package/types-cjs/server-functions/shared.d.cts +0 -523
- package/types-cjs/server-mock.d.cts +0 -286
- package/types-cjs/server.d.cts +0 -544
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getOwner } from 'solid-js';
|
|
2
|
+
import { sharedConfig, reportServerError } from 'solid-js/internal';
|
|
3
|
+
|
|
4
|
+
const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
|
|
5
|
+
function isHttpNavigationTarget(target) {
|
|
6
|
+
try {
|
|
7
|
+
const protocol = new URL(target, "http://base.invalid").protocol;
|
|
8
|
+
return protocol === "http:" || protocol === "https:";
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
2
13
|
|
|
3
14
|
const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
|
|
4
15
|
function isResponseEnvelope(value) {
|
|
@@ -9,6 +20,239 @@ function isSafeError(value) {
|
|
|
9
20
|
return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
|
|
10
21
|
}
|
|
11
22
|
const REVALIDATE_HEADER = "X-Revalidate";
|
|
23
|
+
const RESPONSE_HEADER_VALUE_LIMIT = 4096;
|
|
24
|
+
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
|
|
25
|
+
|
|
26
|
+
const REQUEST_ERROR_HOOK = Symbol.for("solid-js/server/request-error-hook");
|
|
27
|
+
function hooks() {
|
|
28
|
+
const g = globalThis;
|
|
29
|
+
return g[REQUEST_ERROR_HOOK] || (g[REQUEST_ERROR_HOOK] = new WeakMap());
|
|
30
|
+
}
|
|
31
|
+
function requestErrorHook(event) {
|
|
32
|
+
return event === undefined ? undefined : hooks().get(event);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
|
|
36
|
+
const ZERO_TRACE = "00000000000000000000000000000000";
|
|
37
|
+
const ZERO_SPAN = "0000000000000000";
|
|
38
|
+
function parseTraceparent(value) {
|
|
39
|
+
if (!value) return undefined;
|
|
40
|
+
const m = TRACEPARENT.exec(value.trim());
|
|
41
|
+
if (!m) return undefined;
|
|
42
|
+
const [, version, traceId, parentId, flags, rest] = m;
|
|
43
|
+
if (version === "ff") return undefined;
|
|
44
|
+
if (version === "00" && rest !== undefined) return undefined;
|
|
45
|
+
if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
|
|
46
|
+
return {
|
|
47
|
+
traceId,
|
|
48
|
+
parentId,
|
|
49
|
+
sampled: (parseInt(flags, 16) & 1) === 1
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function randomHex(bytes) {
|
|
53
|
+
let out = "";
|
|
54
|
+
for (let i = 0; i < bytes; i += 4) out += (Math.random() * 0x100000000 >>> 0).toString(16).padStart(8, "0");
|
|
55
|
+
return out.length === bytes * 2 ? out : out.slice(0, bytes * 2);
|
|
56
|
+
}
|
|
57
|
+
function randomTraceId() {
|
|
58
|
+
let id = randomHex(16);
|
|
59
|
+
while (id === ZERO_TRACE) id = randomHex(16);
|
|
60
|
+
return id;
|
|
61
|
+
}
|
|
62
|
+
function randomSpanId() {
|
|
63
|
+
let id = randomHex(8);
|
|
64
|
+
while (id === ZERO_SPAN) id = randomHex(8);
|
|
65
|
+
return id;
|
|
66
|
+
}
|
|
67
|
+
function formatTraceparent(context) {
|
|
68
|
+
return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
|
|
69
|
+
}
|
|
70
|
+
const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
|
|
71
|
+
function records$1() {
|
|
72
|
+
const g = globalThis;
|
|
73
|
+
return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
|
|
74
|
+
}
|
|
75
|
+
function traceFor(key, request) {
|
|
76
|
+
const store = records$1();
|
|
77
|
+
let record = store.get(key);
|
|
78
|
+
if (record) return record;
|
|
79
|
+
const headers = request ? request.headers : undefined;
|
|
80
|
+
const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
|
|
81
|
+
const context = {
|
|
82
|
+
traceId: incoming ? incoming.traceId : randomTraceId(),
|
|
83
|
+
spanId: randomSpanId(),
|
|
84
|
+
entries: {}
|
|
85
|
+
};
|
|
86
|
+
if (incoming) {
|
|
87
|
+
context.parentId = incoming.parentId;
|
|
88
|
+
context.sampled = incoming.sampled;
|
|
89
|
+
}
|
|
90
|
+
if (headers) {
|
|
91
|
+
const state = headers.get("tracestate");
|
|
92
|
+
if (state) context.state = state;
|
|
93
|
+
const baggage = headers.get("baggage");
|
|
94
|
+
if (baggage) context.baggage = baggage;
|
|
95
|
+
}
|
|
96
|
+
let answered = false;
|
|
97
|
+
context.entries.traceparent = formatTraceparent(context);
|
|
98
|
+
record = {
|
|
99
|
+
context,
|
|
100
|
+
emit: incoming !== undefined && incoming.sampled || answered,
|
|
101
|
+
timing: []
|
|
102
|
+
};
|
|
103
|
+
store.set(key, record);
|
|
104
|
+
return record;
|
|
105
|
+
}
|
|
106
|
+
function traceForEvent(event) {
|
|
107
|
+
return traceFor(event.request || event, event.request);
|
|
108
|
+
}
|
|
109
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
110
|
+
function splitServerTiming(value) {
|
|
111
|
+
const entries = [];
|
|
112
|
+
let start = 0;
|
|
113
|
+
let quoted = false;
|
|
114
|
+
for (let i = 0; i < value.length; i++) {
|
|
115
|
+
const c = value[i];
|
|
116
|
+
if (quoted) {
|
|
117
|
+
if (c === "\\") i++;else if (c === '"') quoted = false;
|
|
118
|
+
} else if (c === '"') quoted = true;else if (c === ",") {
|
|
119
|
+
entries.push(value.slice(start, i));
|
|
120
|
+
start = i + 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
entries.push(value.slice(start));
|
|
124
|
+
return entries;
|
|
125
|
+
}
|
|
126
|
+
function metricName(entry) {
|
|
127
|
+
return entry.split(";")[0].trim().toLowerCase();
|
|
128
|
+
}
|
|
129
|
+
function namesOnServerTiming(headers) {
|
|
130
|
+
const names = new Set();
|
|
131
|
+
const existing = headers.get("server-timing");
|
|
132
|
+
if (existing) {
|
|
133
|
+
for (const entry of splitServerTiming(existing)) {
|
|
134
|
+
const name = metricName(entry);
|
|
135
|
+
if (name) names.add(name);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return names;
|
|
139
|
+
}
|
|
140
|
+
function quoteDesc(value) {
|
|
141
|
+
return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
|
|
142
|
+
}
|
|
143
|
+
function shellMs(record) {
|
|
144
|
+
return record.render !== undefined ? record.render.shellMs : undefined;
|
|
145
|
+
}
|
|
146
|
+
function hasServerTiming(record) {
|
|
147
|
+
return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
|
|
148
|
+
}
|
|
149
|
+
function appendTraceServerTiming(headers, record) {
|
|
150
|
+
if (record.emit) {
|
|
151
|
+
const entries = record.context.entries;
|
|
152
|
+
let present;
|
|
153
|
+
for (const name in entries) {
|
|
154
|
+
if (!TOKEN.test(name)) continue;
|
|
155
|
+
if (!present) present = namesOnServerTiming(headers);
|
|
156
|
+
if (present.has(name.toLowerCase())) continue;
|
|
157
|
+
headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
|
|
158
|
+
present.add(name.toLowerCase());
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const shell = shellMs(record);
|
|
162
|
+
if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
|
|
163
|
+
for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
|
|
164
|
+
}
|
|
165
|
+
function metricOf(work) {
|
|
166
|
+
if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
|
|
167
|
+
const boundary = work.event;
|
|
168
|
+
return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
|
|
169
|
+
}
|
|
170
|
+
function formatMetric(name, dur, desc) {
|
|
171
|
+
let out = `${name};dur=${Math.round(dur * 10) / 10}`;
|
|
172
|
+
if (desc) out += `;desc="${quoteDesc(desc)}"`;
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
function mergeServerTiming(target, value) {
|
|
176
|
+
const present = namesOnServerTiming(target);
|
|
177
|
+
for (const entry of splitServerTiming(value)) {
|
|
178
|
+
const trimmed = entry.trim();
|
|
179
|
+
const name = metricName(trimmed);
|
|
180
|
+
if (!name || present.has(name)) continue;
|
|
181
|
+
target.append("Server-Timing", trimmed);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function records() {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
function settledPromise(value) {
|
|
189
|
+
if (value instanceof Promise) return value;
|
|
190
|
+
try {
|
|
191
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
|
|
192
|
+
} catch {}
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
function isDeferredBody(value) {
|
|
196
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
197
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
|
|
198
|
+
const v = value;
|
|
199
|
+
if (typeof v[Symbol.asyncIterator] === "function") return true;
|
|
200
|
+
return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function timesServerWork(type) {
|
|
204
|
+
const channel = records();
|
|
205
|
+
if (channel === undefined) return false;
|
|
206
|
+
return channel.observed(type);
|
|
207
|
+
}
|
|
208
|
+
function deliver(context, at, boundary, outcome, value) {
|
|
209
|
+
const record = {
|
|
210
|
+
id: context.id,
|
|
211
|
+
direct: context.direct,
|
|
212
|
+
at,
|
|
213
|
+
durationMs: performance.now() - at,
|
|
214
|
+
outcome
|
|
215
|
+
};
|
|
216
|
+
if (boundary !== undefined) record.boundary = boundary;
|
|
217
|
+
if (outcome === "ok" && isDeferredBody(value)) record.deferred = true;
|
|
218
|
+
traceForEvent(context.event).timing.push({
|
|
219
|
+
type: "invocation",
|
|
220
|
+
event: record
|
|
221
|
+
});
|
|
222
|
+
const channel = records();
|
|
223
|
+
if (!channel.observed("invocation")) return;
|
|
224
|
+
const live = {
|
|
225
|
+
event: context.event,
|
|
226
|
+
args: context.args
|
|
227
|
+
};
|
|
228
|
+
if (context.request !== undefined) live.request = context.request;
|
|
229
|
+
if (outcome === "ok") live.result = value;else live.error = value;
|
|
230
|
+
channel.emit("invocation", record, live);
|
|
231
|
+
}
|
|
232
|
+
function observeInvocation(context, execute) {
|
|
233
|
+
if (!timesServerWork("invocation")) return execute();
|
|
234
|
+
const at = performance.now();
|
|
235
|
+
const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
|
|
236
|
+
let result;
|
|
237
|
+
try {
|
|
238
|
+
result = execute();
|
|
239
|
+
} catch (error) {
|
|
240
|
+
deliver(context, at, boundary, "error", error);
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
const promised = settledPromise(result);
|
|
244
|
+
if (promised !== undefined) {
|
|
245
|
+
return promised.then(value => {
|
|
246
|
+
deliver(context, at, boundary, "ok", value);
|
|
247
|
+
return value;
|
|
248
|
+
}, error => {
|
|
249
|
+
deliver(context, at, boundary, "error", error);
|
|
250
|
+
throw error;
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
deliver(context, at, boundary, "ok", result);
|
|
254
|
+
return result;
|
|
255
|
+
}
|
|
12
256
|
|
|
13
257
|
const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
|
|
14
258
|
function getServerFunctionMetadata(fn) {
|
|
@@ -26,6 +270,32 @@ function withMeta(fn, meta) {
|
|
|
26
270
|
Object.assign(metadata, meta);
|
|
27
271
|
return fn;
|
|
28
272
|
}
|
|
273
|
+
const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
|
|
274
|
+
const INVOKE_OPTION_REDIRECTS = {
|
|
275
|
+
headers: "Session-dynamic headers belong to the prepareRequest hook, declaration metadata to " + "withMeta(fn, meta), and data belongs in the arguments, where it is serialized, typed, " + "and part of the cache key.",
|
|
276
|
+
method: "The method is declaration-scoped: declare the function with GET(fn).",
|
|
277
|
+
body: "The arguments are the body: pass them in the args array.",
|
|
278
|
+
timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
|
|
279
|
+
};
|
|
280
|
+
function invoke(fn, options, ...args) {
|
|
281
|
+
const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
|
|
282
|
+
if (!channel) {
|
|
283
|
+
throw new Error(isServerFunction(fn) ? "invoke: this wrapper does not forward the invocation channel " + "(SERVER_FUNCTION_INVOKE). Wrappers that share calls (caches, channels) opt in " + "deliberately — a caller's signal cannot own a wire other callers share. Invoke " + "the underlying reference directly, or use the wrapper's own per-call idioms." : "invoke expects a server function reference (or a wrapper that forwards its " + "invocation channel). Per-call options apply at the transport; for a data " + "layer's calls, use its per-call options instead.");
|
|
284
|
+
}
|
|
285
|
+
if (options === null || typeof options !== "object") {
|
|
286
|
+
throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
|
|
287
|
+
}
|
|
288
|
+
const picked = {};
|
|
289
|
+
for (const key in options) {
|
|
290
|
+
if (key !== "signal" && key !== "keepalive" && key !== "priority") {
|
|
291
|
+
throw new Error(`\`${key}\` is not an invocation option. ` + (INVOKE_OPTION_REDIRECTS[key] || "Options here are strictly invocation-scoped (they vary between calls of the " + "same function): signal, keepalive, priority."));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (options.signal !== undefined) picked.signal = options.signal;
|
|
295
|
+
if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
|
|
296
|
+
if (options.priority !== undefined) picked.priority = options.priority;
|
|
297
|
+
return channel(args, picked);
|
|
298
|
+
}
|
|
29
299
|
const LIVE_SOURCE = Symbol.for("solid.LiveSource");
|
|
30
300
|
const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
|
|
31
301
|
function provideServerFunctionRPC(rpc) {
|
|
@@ -62,6 +332,7 @@ function serializeCookie(name, value, options = {}) {
|
|
|
62
332
|
if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
63
333
|
if (options.httpOnly) cookie += "; HttpOnly";
|
|
64
334
|
if (options.secure) cookie += "; Secure";
|
|
335
|
+
if (options.partitioned) cookie += "; Partitioned";
|
|
65
336
|
if (options.sameSite) {
|
|
66
337
|
const sameSite = options.sameSite.toLowerCase();
|
|
67
338
|
cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
|
|
@@ -69,7 +340,7 @@ function serializeCookie(name, value, options = {}) {
|
|
|
69
340
|
return cookie;
|
|
70
341
|
}
|
|
71
342
|
const FLASH_COOKIE = "flash";
|
|
72
|
-
const FLASH_MATCHER =
|
|
343
|
+
const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
|
|
73
344
|
function hasFlashCookie(cookieHeader) {
|
|
74
345
|
return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
|
|
75
346
|
}
|
|
@@ -86,11 +357,141 @@ function configureServerFunctionsCodec(codec) {
|
|
|
86
357
|
function getServerFunctionsCodec() {
|
|
87
358
|
return codecConfig.codec;
|
|
88
359
|
}
|
|
89
|
-
|
|
360
|
+
const UNNAMED_FLIGHT_SOURCE = "true";
|
|
361
|
+
const flightConfig = {
|
|
362
|
+
consumers: new Map()
|
|
363
|
+
};
|
|
364
|
+
function assertFlightSource(source) {
|
|
365
|
+
if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
|
|
366
|
+
throw new TypeError(`Invalid flight data source id "${source}": ids ride the ` + `${SINGLE_FLIGHT_HEADER} header as a comma-separated list, and "true" is ` + `reserved for the unnamed registration (the bare consumer/hook signatures).`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
|
|
370
|
+
const named = typeof sourceOrConsumer === "string";
|
|
371
|
+
if (named) assertFlightSource(sourceOrConsumer);
|
|
372
|
+
const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
|
|
373
|
+
const consumer = named ? maybeConsumer : sourceOrConsumer;
|
|
374
|
+
flightConfig.consumers.set(source, consumer);
|
|
90
375
|
return () => {
|
|
376
|
+
if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
|
|
91
377
|
};
|
|
92
378
|
}
|
|
93
|
-
|
|
379
|
+
function frameAddress(id, args) {
|
|
380
|
+
return args && args.length ? id + ":" + hashArguments(args) : id;
|
|
381
|
+
}
|
|
382
|
+
function hashArguments(args) {
|
|
383
|
+
let hash = 0;
|
|
384
|
+
const text = stableString(args);
|
|
385
|
+
for (let i = 0; i < text.length; i++) {
|
|
386
|
+
hash = (hash << 5) - hash + text.charCodeAt(i);
|
|
387
|
+
hash |= 0;
|
|
388
|
+
}
|
|
389
|
+
return (hash >>> 0).toString(36);
|
|
390
|
+
}
|
|
391
|
+
function stableString(value, seen) {
|
|
392
|
+
if (value === null || typeof value !== "object") {
|
|
393
|
+
return typeof value === "bigint" ? value + "n" : String(value);
|
|
394
|
+
}
|
|
395
|
+
if (value instanceof Date) return "Date:" + value.getTime();
|
|
396
|
+
seen || (seen = new Set());
|
|
397
|
+
if (seen.has(value)) return "~";
|
|
398
|
+
seen.add(value);
|
|
399
|
+
if (value instanceof Map) {
|
|
400
|
+
const entries = [];
|
|
401
|
+
for (const [k, v] of value) {
|
|
402
|
+
entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
|
|
403
|
+
}
|
|
404
|
+
return "Map{" + entries.sort().join(",") + "}";
|
|
405
|
+
}
|
|
406
|
+
if (value instanceof Set) {
|
|
407
|
+
const members = [];
|
|
408
|
+
for (const v of value) members.push(stableString(v, seen));
|
|
409
|
+
return "Set{" + members.sort().join(",") + "}";
|
|
410
|
+
}
|
|
411
|
+
if (Array.isArray(value)) {
|
|
412
|
+
let out = "[";
|
|
413
|
+
for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
|
|
414
|
+
return out + "]";
|
|
415
|
+
}
|
|
416
|
+
const keys = Object.keys(value).sort();
|
|
417
|
+
let out = "{";
|
|
418
|
+
for (let i = 0; i < keys.length; i++) {
|
|
419
|
+
out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
|
|
420
|
+
}
|
|
421
|
+
return out + "}";
|
|
422
|
+
}
|
|
423
|
+
function serverFunctionAddress(endpoint, id) {
|
|
424
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
425
|
+
return `${mount}/${encodeURIComponent(id)}`;
|
|
426
|
+
}
|
|
427
|
+
function serverFunctionDataAddress(endpoint, id) {
|
|
428
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
429
|
+
return `${mount}/data/${encodeURIComponent(id)}`;
|
|
430
|
+
}
|
|
431
|
+
function serverFunctionLiveAddress(endpoint, id) {
|
|
432
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
433
|
+
return `${mount}/live/${encodeURIComponent(id)}`;
|
|
434
|
+
}
|
|
435
|
+
function parseServerFunctionAddress(pathname, endpoint) {
|
|
436
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
437
|
+
if (!pathname.startsWith(mount)) return null;
|
|
438
|
+
const rest = pathname.slice(mount.length);
|
|
439
|
+
if (!rest.startsWith("/")) return null;
|
|
440
|
+
let segment = rest.slice(1);
|
|
441
|
+
let data = false;
|
|
442
|
+
let live = false;
|
|
443
|
+
if (segment.startsWith("data/")) {
|
|
444
|
+
segment = segment.slice(5);
|
|
445
|
+
data = true;
|
|
446
|
+
} else if (segment.startsWith("live/")) {
|
|
447
|
+
segment = segment.slice(5);
|
|
448
|
+
live = true;
|
|
449
|
+
}
|
|
450
|
+
if (!segment || segment.includes("/")) return null;
|
|
451
|
+
try {
|
|
452
|
+
return {
|
|
453
|
+
id: decodeURIComponent(segment),
|
|
454
|
+
data,
|
|
455
|
+
live
|
|
456
|
+
};
|
|
457
|
+
} catch {
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const MAX_GET_URL_LENGTH = 2000;
|
|
462
|
+
function urlTargetId(target, helper) {
|
|
463
|
+
if (typeof target === "string") return target;
|
|
464
|
+
if (isServerFunction(target) && typeof target.id === "string") return target.id;
|
|
465
|
+
throw new Error(`${helper} expects a server function reference (or its id).`);
|
|
466
|
+
}
|
|
467
|
+
function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
|
|
468
|
+
const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
|
|
469
|
+
if (!boundArgs.length) return address;
|
|
470
|
+
if (!isJSONSafe(boundArgs)) {
|
|
471
|
+
throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
|
|
472
|
+
}
|
|
473
|
+
return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
|
|
474
|
+
}
|
|
475
|
+
function serverFunctionUrlFor(endpoint, fn, args) {
|
|
476
|
+
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
477
|
+
throw new Error("serverFunctionUrl expects a server function reference.");
|
|
478
|
+
}
|
|
479
|
+
const metadata = getServerFunctionMetadata(fn);
|
|
480
|
+
if (!metadata || metadata.method !== "GET") {
|
|
481
|
+
throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
|
|
482
|
+
}
|
|
483
|
+
const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
|
|
484
|
+
if (!args.length) return address;
|
|
485
|
+
if (!isJSONSafe(args)) {
|
|
486
|
+
throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
|
|
487
|
+
}
|
|
488
|
+
const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
|
|
489
|
+
const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
|
|
490
|
+
if (length > MAX_GET_URL_LENGTH) {
|
|
491
|
+
throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
|
|
492
|
+
}
|
|
493
|
+
return url;
|
|
494
|
+
}
|
|
94
495
|
const ERROR_HEADER = "X-Server-Function-Error";
|
|
95
496
|
const ERROR_HEADER_MARKER = "=?1?";
|
|
96
497
|
const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
|
|
@@ -116,8 +517,31 @@ function decodeErrorHeaderValue(value) {
|
|
|
116
517
|
return value;
|
|
117
518
|
}
|
|
118
519
|
}
|
|
119
|
-
const INSTANCE_HEADER = "X-Server-Function-Instance";
|
|
120
520
|
const BODY_FORMAT_HEADER = "X-Server-Function-Format";
|
|
521
|
+
const LAST_EVENT_ID_HEADER = "Last-Event-ID";
|
|
522
|
+
const UNKNOWN_HEADER = "X-Server-Function-Unknown";
|
|
523
|
+
const BUILD_HEADER = "X-Server-Function-Build";
|
|
524
|
+
const REDIRECT_HEADER = "X-Server-Function-Redirect";
|
|
525
|
+
function decodeRedirectHeaderValue(value) {
|
|
526
|
+
if (typeof value !== "string") return undefined;
|
|
527
|
+
const at = value.indexOf(" ");
|
|
528
|
+
if (at < 0) return undefined;
|
|
529
|
+
const status = Number(value.slice(0, at));
|
|
530
|
+
const url = value.slice(at + 1);
|
|
531
|
+
if (!Number.isInteger(status) || !url) return undefined;
|
|
532
|
+
if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
|
|
533
|
+
let parsed;
|
|
534
|
+
try {
|
|
535
|
+
parsed = new URL(url);
|
|
536
|
+
} catch {
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
|
|
540
|
+
return {
|
|
541
|
+
status,
|
|
542
|
+
url
|
|
543
|
+
};
|
|
544
|
+
}
|
|
121
545
|
const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
|
|
122
546
|
const FILE_FORM_KEY = "__server_function_file__";
|
|
123
547
|
const BodyFormat = {
|
|
@@ -129,7 +553,8 @@ const BodyFormat = {
|
|
|
129
553
|
File: "5",
|
|
130
554
|
ArrayBuffer: "6",
|
|
131
555
|
Uint8Array: "7",
|
|
132
|
-
Json: "8"
|
|
556
|
+
Json: "8",
|
|
557
|
+
Void: "9"
|
|
133
558
|
};
|
|
134
559
|
const JSON_SAFE_DEPTH_LIMIT = 4096;
|
|
135
560
|
const EXIT = {};
|
|
@@ -146,7 +571,7 @@ function isJSONSafe(value) {
|
|
|
146
571
|
const t = typeof v;
|
|
147
572
|
if (t === "string" || t === "boolean") continue;
|
|
148
573
|
if (t === "number") {
|
|
149
|
-
if (!Number.isFinite(v)) return false;
|
|
574
|
+
if (!Number.isFinite(v) || Object.is(v, -0)) return false;
|
|
150
575
|
continue;
|
|
151
576
|
}
|
|
152
577
|
if (t !== "object") return false;
|
|
@@ -159,7 +584,11 @@ function isJSONSafe(value) {
|
|
|
159
584
|
const proto = Object.getPrototypeOf(v);
|
|
160
585
|
if (proto !== Object.prototype && proto !== null) return false;
|
|
161
586
|
if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
|
|
162
|
-
for (const k in v)
|
|
587
|
+
for (const k in v) {
|
|
588
|
+
const descriptor = Object.getOwnPropertyDescriptor(v, k);
|
|
589
|
+
if (descriptor === undefined || !("value" in descriptor)) return false;
|
|
590
|
+
stack.push(descriptor.value);
|
|
591
|
+
}
|
|
163
592
|
}
|
|
164
593
|
}
|
|
165
594
|
return true;
|
|
@@ -225,127 +654,262 @@ function getHeadersAndBody(body) {
|
|
|
225
654
|
return undefined;
|
|
226
655
|
}
|
|
227
656
|
}
|
|
228
|
-
async function extractBody(source, codecOptions) {
|
|
657
|
+
async function extractBody(source, codecOptions, wire) {
|
|
229
658
|
const contentType = source.headers.get("content-type");
|
|
230
659
|
const format = source.headers.get(BODY_FORMAT_HEADER);
|
|
231
|
-
const clone = source.clone();
|
|
232
660
|
switch (true) {
|
|
233
661
|
case format === BodyFormat.Serialized:
|
|
234
|
-
return await deserializeStream(
|
|
662
|
+
return await deserializeStream(source, codecOptions, wire);
|
|
235
663
|
case format === BodyFormat.Json:
|
|
236
|
-
return JSON.parse(await
|
|
664
|
+
return JSON.parse(await source.text());
|
|
237
665
|
case format === BodyFormat.String:
|
|
238
|
-
return await
|
|
666
|
+
return await source.text();
|
|
239
667
|
case format === BodyFormat.File:
|
|
240
668
|
{
|
|
241
|
-
const formData = await
|
|
669
|
+
const formData = await source.formData();
|
|
242
670
|
return formData.get(FILE_FORM_KEY);
|
|
243
671
|
}
|
|
244
672
|
case format === BodyFormat.FormData:
|
|
245
673
|
case contentType && contentType.startsWith("multipart/form-data"):
|
|
246
|
-
return await
|
|
674
|
+
return await source.formData();
|
|
247
675
|
case format === BodyFormat.URLSearchParams:
|
|
248
676
|
case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
|
|
249
|
-
return new URLSearchParams(await
|
|
677
|
+
return new URLSearchParams(await source.text());
|
|
250
678
|
case format === BodyFormat.Blob:
|
|
251
|
-
return await
|
|
679
|
+
return await source.blob();
|
|
252
680
|
case format === BodyFormat.ArrayBuffer:
|
|
253
|
-
return await
|
|
681
|
+
return await source.arrayBuffer();
|
|
254
682
|
case format === BodyFormat.Uint8Array:
|
|
255
|
-
return new Uint8Array(await
|
|
683
|
+
return new Uint8Array(await source.arrayBuffer());
|
|
256
684
|
}
|
|
257
685
|
return undefined;
|
|
258
686
|
}
|
|
259
687
|
function createChunk(data) {
|
|
260
|
-
const
|
|
261
|
-
const encodeData = encoder.encode(data);
|
|
688
|
+
const encodeData = CHUNK_ENCODER.encode(data);
|
|
262
689
|
const bytes = encodeData.length;
|
|
690
|
+
if (bytes > MAX_CHUNK_BYTES) {
|
|
691
|
+
throw new RangeError("Server function chunk is too large to frame.");
|
|
692
|
+
}
|
|
263
693
|
const chunk = new Uint8Array(12 + bytes);
|
|
264
|
-
chunk.set(
|
|
694
|
+
chunk.set(CHUNK_ENCODER.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
|
|
265
695
|
chunk.set(encodeData, 12);
|
|
266
696
|
return chunk;
|
|
267
697
|
}
|
|
698
|
+
const CHUNK_ENCODER = /* @__PURE__ */new TextEncoder();
|
|
699
|
+
const CHUNK_DECODER = /* @__PURE__ */new TextDecoder("utf-8", {
|
|
700
|
+
fatal: true
|
|
701
|
+
});
|
|
702
|
+
const MAX_CHUNK_BYTES = 0xffffffff;
|
|
703
|
+
const RETAINED_STORE_BYTES = 64 * 1024;
|
|
704
|
+
const DONE = {
|
|
705
|
+
done: true,
|
|
706
|
+
value: undefined
|
|
707
|
+
};
|
|
708
|
+
function malformedStream() {
|
|
709
|
+
return new Error("Malformed server function stream.");
|
|
710
|
+
}
|
|
268
711
|
class ChunkReader {
|
|
269
712
|
constructor(stream) {
|
|
270
713
|
this.reader = stream.getReader();
|
|
271
|
-
this.
|
|
714
|
+
this.store = new Uint8Array(0);
|
|
715
|
+
this.buffer = this.store;
|
|
272
716
|
this.done = false;
|
|
717
|
+
this.cancelled = false;
|
|
273
718
|
}
|
|
274
719
|
async readChunk() {
|
|
275
720
|
const chunk = await this.reader.read();
|
|
276
|
-
if (
|
|
277
|
-
const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
|
|
278
|
-
newBuffer.set(this.buffer);
|
|
279
|
-
newBuffer.set(chunk.value, this.buffer.length);
|
|
280
|
-
this.buffer = newBuffer;
|
|
281
|
-
} else {
|
|
721
|
+
if (chunk.done) {
|
|
282
722
|
this.done = true;
|
|
723
|
+
return this.cancelled;
|
|
283
724
|
}
|
|
725
|
+
const incoming = chunk.value;
|
|
726
|
+
const store = this.store;
|
|
727
|
+
const start = this.buffer.byteOffset;
|
|
728
|
+
const end = start + this.buffer.length;
|
|
729
|
+
const needed = this.buffer.length + incoming.length;
|
|
730
|
+
if (end + incoming.length <= store.length) {
|
|
731
|
+
store.set(incoming, end);
|
|
732
|
+
this.buffer = store.subarray(start, end + incoming.length);
|
|
733
|
+
} else if (needed <= store.length) {
|
|
734
|
+
store.copyWithin(0, start, end);
|
|
735
|
+
store.set(incoming, this.buffer.length);
|
|
736
|
+
this.buffer = store.subarray(0, needed);
|
|
737
|
+
} else {
|
|
738
|
+
const grown = new Uint8Array(Math.max(needed, store.length * 2));
|
|
739
|
+
grown.set(this.buffer);
|
|
740
|
+
grown.set(incoming, this.buffer.length);
|
|
741
|
+
this.store = grown;
|
|
742
|
+
this.buffer = grown.subarray(0, needed);
|
|
743
|
+
}
|
|
744
|
+
return this.cancelled;
|
|
284
745
|
}
|
|
285
746
|
async next() {
|
|
747
|
+
if (this.cancelled) return DONE;
|
|
286
748
|
while (this.buffer.length < 12) {
|
|
287
749
|
if (this.done) {
|
|
288
|
-
if (this.buffer.length === 0) return
|
|
289
|
-
|
|
290
|
-
value: undefined
|
|
291
|
-
};
|
|
292
|
-
throw new Error("Malformed server function stream.");
|
|
750
|
+
if (this.buffer.length === 0) return DONE;
|
|
751
|
+
throw malformedStream();
|
|
293
752
|
}
|
|
294
|
-
await this.readChunk();
|
|
295
|
-
}
|
|
296
|
-
const decoder = new TextDecoder();
|
|
297
|
-
const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
|
|
298
|
-
if (Number.isNaN(bytes)) {
|
|
299
|
-
throw new Error("Malformed server function stream.");
|
|
753
|
+
if (await this.readChunk()) return DONE;
|
|
300
754
|
}
|
|
755
|
+
const header = String.fromCharCode(...this.buffer.subarray(0, 12));
|
|
756
|
+
if (!/^;0x[\dA-Fa-f]{8};$/.test(header)) throw malformedStream();
|
|
757
|
+
const bytes = parseInt(header.slice(3, 11), 16);
|
|
301
758
|
while (bytes > this.buffer.length - 12) {
|
|
302
759
|
if (this.done) {
|
|
303
|
-
throw
|
|
760
|
+
throw malformedStream();
|
|
304
761
|
}
|
|
305
|
-
await this.readChunk();
|
|
762
|
+
if (await this.readChunk()) return DONE;
|
|
763
|
+
}
|
|
764
|
+
let partial;
|
|
765
|
+
try {
|
|
766
|
+
partial = CHUNK_DECODER.decode(this.buffer.subarray(12, 12 + bytes));
|
|
767
|
+
} catch {
|
|
768
|
+
throw malformedStream();
|
|
306
769
|
}
|
|
307
|
-
const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
|
|
308
770
|
this.buffer = this.buffer.subarray(12 + bytes);
|
|
771
|
+
if (this.store.length > RETAINED_STORE_BYTES && this.buffer.length <= RETAINED_STORE_BYTES) {
|
|
772
|
+
this.store = this.buffer = this.buffer.slice();
|
|
773
|
+
}
|
|
309
774
|
return {
|
|
310
775
|
done: false,
|
|
311
776
|
value: partial
|
|
312
777
|
};
|
|
313
778
|
}
|
|
314
779
|
async drain(interpret) {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
780
|
+
try {
|
|
781
|
+
while (true) {
|
|
782
|
+
const result = await this.next();
|
|
783
|
+
if (result.done) {
|
|
784
|
+
break;
|
|
785
|
+
}
|
|
786
|
+
interpret(result.value);
|
|
319
787
|
}
|
|
320
|
-
|
|
788
|
+
} catch (error) {
|
|
789
|
+
this.cancel(error).catch(() => {});
|
|
790
|
+
throw error;
|
|
321
791
|
}
|
|
322
792
|
}
|
|
793
|
+
cancel(reason) {
|
|
794
|
+
this.cancelled = true;
|
|
795
|
+
return this.reader.cancel(reason);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
function createEventChunk(data, id) {
|
|
799
|
+
let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
|
|
800
|
+
for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
|
|
801
|
+
return CHUNK_ENCODER.encode(event + "\n");
|
|
802
|
+
}
|
|
803
|
+
const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
|
|
804
|
+
function isEventStream(source) {
|
|
805
|
+
const contentType = source.headers.get("content-type");
|
|
806
|
+
return !!contentType && contentType.startsWith("text/event-stream");
|
|
807
|
+
}
|
|
808
|
+
function positionDigest(value) {
|
|
809
|
+
if (value === undefined || !isJSONSafe(value)) return undefined;
|
|
810
|
+
const text = JSON.stringify(value);
|
|
811
|
+
if (typeof text !== "string") return undefined;
|
|
812
|
+
return textDigest(text);
|
|
813
|
+
}
|
|
814
|
+
function textDigest(text) {
|
|
815
|
+
let a = 0x811c9dc5;
|
|
816
|
+
let b = 0x050c5d1f;
|
|
817
|
+
for (let i = 0; i < text.length; i++) {
|
|
818
|
+
const code = text.charCodeAt(i);
|
|
819
|
+
a = Math.imul(a ^ code, 0x01000193);
|
|
820
|
+
b = Math.imul(b ^ code, 0x01000193);
|
|
821
|
+
}
|
|
822
|
+
return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
|
|
823
|
+
}
|
|
824
|
+
const ERROR_TRAILER_PREFIX = "!";
|
|
825
|
+
function encodeErrorTrailer(error) {
|
|
826
|
+
const shaped = error instanceof Error ? error : new Error(String(error));
|
|
827
|
+
return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
|
|
828
|
+
name: shaped.name,
|
|
829
|
+
message: shaped.message
|
|
830
|
+
} : {
|
|
831
|
+
message: shaped.message
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
function errorFromTrailer(payload) {
|
|
835
|
+
let shape;
|
|
836
|
+
try {
|
|
837
|
+
shape = JSON.parse(payload.slice(1));
|
|
838
|
+
} catch {
|
|
839
|
+
shape = null;
|
|
840
|
+
}
|
|
841
|
+
const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
|
|
842
|
+
if (shape && typeof shape.name === "string") error.name = shape.name;
|
|
843
|
+
return error;
|
|
844
|
+
}
|
|
845
|
+
function serializeStream(value, codecOptions) {
|
|
846
|
+
return new ReadableStream({
|
|
847
|
+
async start(controller) {
|
|
848
|
+
const {
|
|
849
|
+
serializeJSON
|
|
850
|
+
} = await import('@solidjs/web/serialization');
|
|
851
|
+
serializeJSON(value, {
|
|
852
|
+
...codecOptions,
|
|
853
|
+
onParse(node) {
|
|
854
|
+
controller.enqueue(createChunk(JSON.stringify(node)));
|
|
855
|
+
},
|
|
856
|
+
onDone() {
|
|
857
|
+
controller.close();
|
|
858
|
+
},
|
|
859
|
+
onError(error) {
|
|
860
|
+
controller.error(error);
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
});
|
|
323
865
|
}
|
|
324
|
-
async function deserializeStream(source, codecOptions) {
|
|
866
|
+
async function deserializeStream(source, codecOptions, wire) {
|
|
325
867
|
if (!source.body) {
|
|
326
868
|
throw new Error("missing body");
|
|
327
869
|
}
|
|
328
|
-
const reader = new ChunkReader(source.body);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
870
|
+
const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
|
|
871
|
+
try {
|
|
872
|
+
const result = await reader.next();
|
|
873
|
+
if (!result.done) {
|
|
874
|
+
if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
875
|
+
throw errorFromTrailer(result.value);
|
|
876
|
+
}
|
|
877
|
+
const {
|
|
878
|
+
createJSONDeserializer
|
|
879
|
+
} = await import('@solidjs/web/serialization/decode');
|
|
880
|
+
const deserializeChunk = createJSONDeserializer(codecOptions);
|
|
881
|
+
function interpretChunk(chunk) {
|
|
882
|
+
if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
883
|
+
throw errorFromTrailer(chunk);
|
|
884
|
+
}
|
|
885
|
+
return deserializeChunk(JSON.parse(chunk));
|
|
886
|
+
}
|
|
887
|
+
const connection = wire && wire.connection;
|
|
888
|
+
let endConnection;
|
|
889
|
+
if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
|
|
890
|
+
const end = error => {
|
|
891
|
+
const sweep = () => deserializeChunk.abort(error);
|
|
892
|
+
if (connection) {
|
|
893
|
+
const close = () => deserializeChunk.close();
|
|
894
|
+
endConnection({
|
|
895
|
+
open: deserializeChunk.open(),
|
|
896
|
+
error,
|
|
897
|
+
sweep,
|
|
898
|
+
close
|
|
899
|
+
});
|
|
900
|
+
} else sweep();
|
|
901
|
+
};
|
|
902
|
+
reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
|
|
903
|
+
return interpretChunk(result.value);
|
|
337
904
|
}
|
|
338
|
-
|
|
339
|
-
|
|
905
|
+
} catch (error) {
|
|
906
|
+
reader.cancel(error).catch(() => {});
|
|
907
|
+
throw error;
|
|
340
908
|
}
|
|
341
|
-
return undefined;
|
|
342
|
-
}
|
|
343
|
-
async function deserializeString(text, codecOptions) {
|
|
344
|
-
return await deserializeStream(new Response(text), codecOptions);
|
|
345
909
|
}
|
|
346
910
|
async function decodeResponse(response, codecOptions) {
|
|
347
911
|
if (!response.body) return undefined;
|
|
348
|
-
return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
912
|
+
return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
349
913
|
}
|
|
350
914
|
async function decodeResponsePayload(response, codecOptions) {
|
|
351
915
|
const decoded = await decodeResponse(response, codecOptions);
|
|
@@ -363,18 +927,48 @@ async function decodeResponsePayload(response, codecOptions) {
|
|
|
363
927
|
typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
|
|
364
928
|
const RequestContext = Symbol.for("solid.RequestContext");
|
|
365
929
|
function getRequestEvent() {
|
|
366
|
-
|
|
930
|
+
const store = globalThis[RequestContext];
|
|
931
|
+
if (!store) return undefined;
|
|
932
|
+
const event = store.getStore();
|
|
933
|
+
if (event) return event;
|
|
934
|
+
const ctx = renderContextOf(getOwner());
|
|
935
|
+
return ctx && ctx.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.");
|
|
936
|
+
}
|
|
937
|
+
const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
|
|
938
|
+
function renderContextOf(owner) {
|
|
939
|
+
const roots = globalThis[RENDER_ROOTS];
|
|
940
|
+
if (!roots) return undefined;
|
|
941
|
+
for (; owner; owner = owner._parent) {
|
|
942
|
+
const context = roots.get(owner);
|
|
943
|
+
if (context) return context;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function peekRequestEvent() {
|
|
947
|
+
const store = globalThis[RequestContext];
|
|
948
|
+
return store ? store.getStore() : undefined;
|
|
949
|
+
}
|
|
950
|
+
function traceForStub(stub, event) {
|
|
951
|
+
if (!event) {
|
|
952
|
+
event = peekRequestEvent();
|
|
953
|
+
if (!event || event.response !== stub) return undefined;
|
|
954
|
+
}
|
|
955
|
+
return traceForEvent(event);
|
|
367
956
|
}
|
|
368
957
|
function reportLostHeaderWrite(method, name) {
|
|
369
|
-
const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
|
|
958
|
+
const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
|
|
370
959
|
console.error(message);
|
|
371
960
|
}
|
|
372
961
|
function commitResponseStub(stub, {
|
|
373
|
-
allowLateLocation = false
|
|
962
|
+
allowLateLocation = false,
|
|
963
|
+
event
|
|
374
964
|
} = {}) {
|
|
375
965
|
if (!stub || stub.committed) return stub;
|
|
376
|
-
stub.committed = true;
|
|
377
966
|
const headers = stub.headers;
|
|
967
|
+
if (headers && typeof headers.append === "function") {
|
|
968
|
+
const trace = traceForStub(stub, event);
|
|
969
|
+
if (trace) appendTraceServerTiming(headers, trace);
|
|
970
|
+
}
|
|
971
|
+
stub.committed = true;
|
|
378
972
|
if (!headers || typeof headers.set !== "function") return stub;
|
|
379
973
|
for (const method of ["set", "append", "delete"]) {
|
|
380
974
|
const original = headers[method].bind(headers);
|
|
@@ -396,42 +990,118 @@ function copyInitHeaders(init) {
|
|
|
396
990
|
for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
|
|
397
991
|
return headers;
|
|
398
992
|
}
|
|
399
|
-
|
|
993
|
+
let stubGapFillExcluded;
|
|
994
|
+
function isStubGapFillExcluded(key) {
|
|
995
|
+
return (stubGapFillExcluded ||= new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
|
|
996
|
+
...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()))).has(key);
|
|
997
|
+
}
|
|
400
998
|
function fillsStubGap(key, headers, response) {
|
|
401
|
-
if (key === "set-cookie" ||
|
|
999
|
+
if (key === "set-cookie" || isStubGapFillExcluded(key)) return false;
|
|
402
1000
|
if (response.body === null && (key === "content-type" || key === "content-length")) return false;
|
|
403
1001
|
return !headers.has(key);
|
|
404
1002
|
}
|
|
405
1003
|
function commitEventResponse(response, event = getRequestEvent()) {
|
|
406
1004
|
const stub = event && event.response;
|
|
407
|
-
if (!stub || !stub.headers || stub.committed)
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
stub.headers.forEach((value, key) => {
|
|
412
|
-
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
413
|
-
});
|
|
414
|
-
if (!cookies.length && !hasGaps) return response;
|
|
415
|
-
try {
|
|
416
|
-
for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
|
|
417
|
-
stub.headers.forEach((value, key) => {
|
|
418
|
-
if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
|
|
419
|
-
});
|
|
420
|
-
return response;
|
|
421
|
-
} catch {
|
|
1005
|
+
if (!stub || !stub.headers || stub.committed) {
|
|
1006
|
+
if (!event || stub) return response;
|
|
1007
|
+
const trace = traceForEvent(event);
|
|
1008
|
+
if (!hasServerTiming(trace)) return response;
|
|
422
1009
|
const headers = copyInitHeaders(response.headers);
|
|
423
|
-
|
|
424
|
-
stub.headers.forEach((value, key) => {
|
|
425
|
-
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
426
|
-
});
|
|
1010
|
+
appendTraceServerTiming(headers, trace);
|
|
427
1011
|
return new Response(response.body, {
|
|
428
1012
|
status: response.status,
|
|
429
1013
|
statusText: response.statusText,
|
|
430
1014
|
headers
|
|
431
1015
|
});
|
|
432
1016
|
}
|
|
1017
|
+
const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
|
|
1018
|
+
commitResponseStub(stub, {
|
|
1019
|
+
event
|
|
1020
|
+
});
|
|
1021
|
+
let hasGaps = false;
|
|
1022
|
+
stub.headers.forEach((value, key) => {
|
|
1023
|
+
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
1024
|
+
});
|
|
1025
|
+
const timing = stub.headers.get("server-timing");
|
|
1026
|
+
const mergesTiming = timing !== null && response.headers.has("server-timing");
|
|
1027
|
+
if (!cookies.length && !hasGaps && !mergesTiming) return response;
|
|
1028
|
+
const headers = copyInitHeaders(response.headers);
|
|
1029
|
+
for (const cookie of cookies) headers.append("Set-Cookie", cookie);
|
|
1030
|
+
stub.headers.forEach((value, key) => {
|
|
1031
|
+
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
1032
|
+
});
|
|
1033
|
+
if (mergesTiming) mergeServerTiming(headers, timing);
|
|
1034
|
+
return new Response(response.body, {
|
|
1035
|
+
status: response.status,
|
|
1036
|
+
statusText: response.statusText,
|
|
1037
|
+
headers
|
|
1038
|
+
});
|
|
433
1039
|
}
|
|
434
1040
|
|
|
1041
|
+
let configuredSecret;
|
|
1042
|
+
function setFlashSecret(secret) {
|
|
1043
|
+
configuredSecret = secret;
|
|
1044
|
+
}
|
|
1045
|
+
function resolveSecret() {
|
|
1046
|
+
return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
|
|
1047
|
+
}
|
|
1048
|
+
const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
|
|
1049
|
+
const FLASH_KEY_ITERATIONS = 100_000;
|
|
1050
|
+
let cachedSecret;
|
|
1051
|
+
let cachedKey;
|
|
1052
|
+
function resolveFlashKey() {
|
|
1053
|
+
const secret = resolveSecret();
|
|
1054
|
+
if (typeof secret !== "string" || secret.length === 0) return null;
|
|
1055
|
+
if (secret !== cachedSecret) {
|
|
1056
|
+
cachedSecret = secret;
|
|
1057
|
+
const encoder = new TextEncoder();
|
|
1058
|
+
cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
|
|
1059
|
+
name: "PBKDF2",
|
|
1060
|
+
salt: encoder.encode(FLASH_KEY_DOMAIN),
|
|
1061
|
+
iterations: FLASH_KEY_ITERATIONS,
|
|
1062
|
+
hash: "SHA-256"
|
|
1063
|
+
}, material, {
|
|
1064
|
+
name: "AES-GCM",
|
|
1065
|
+
length: 256
|
|
1066
|
+
}, false, ["encrypt", "decrypt"]));
|
|
1067
|
+
}
|
|
1068
|
+
return cachedKey;
|
|
1069
|
+
}
|
|
1070
|
+
const FLASH_FORMAT_VERSION = "1.";
|
|
1071
|
+
const IV_BYTES = 12;
|
|
1072
|
+
const GCM_TAG_BYTES = 16;
|
|
1073
|
+
function toBase64url(bytes) {
|
|
1074
|
+
let binary = "";
|
|
1075
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
1076
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1077
|
+
}
|
|
1078
|
+
function fromBase64url(text) {
|
|
1079
|
+
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
|
|
1080
|
+
const bytes = new Uint8Array(binary.length);
|
|
1081
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1082
|
+
return bytes;
|
|
1083
|
+
}
|
|
1084
|
+
async function encryptFlashValue(key, json) {
|
|
1085
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
1086
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
1087
|
+
name: "AES-GCM",
|
|
1088
|
+
iv
|
|
1089
|
+
}, key, new TextEncoder().encode(json)));
|
|
1090
|
+
const packed = new Uint8Array(IV_BYTES + ciphertext.length);
|
|
1091
|
+
packed.set(iv);
|
|
1092
|
+
packed.set(ciphertext, IV_BYTES);
|
|
1093
|
+
return FLASH_FORMAT_VERSION + toBase64url(packed);
|
|
1094
|
+
}
|
|
1095
|
+
async function decryptFlashValue(key, value) {
|
|
1096
|
+
if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
|
|
1097
|
+
const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
|
|
1098
|
+
if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
|
|
1099
|
+
const plain = await crypto.subtle.decrypt({
|
|
1100
|
+
name: "AES-GCM",
|
|
1101
|
+
iv: packed.subarray(0, IV_BYTES)
|
|
1102
|
+
}, key, packed.subarray(IV_BYTES));
|
|
1103
|
+
return new TextDecoder().decode(plain);
|
|
1104
|
+
}
|
|
435
1105
|
function encodeInputValue(value) {
|
|
436
1106
|
if (value instanceof FormData) return {
|
|
437
1107
|
$f: [...value.entries()].filter(([, v]) => typeof v === "string")
|
|
@@ -452,7 +1122,11 @@ function decodeInputValue(value) {
|
|
|
452
1122
|
}
|
|
453
1123
|
return value;
|
|
454
1124
|
}
|
|
455
|
-
function encodeFlashCookie(url, result, input, thrown) {
|
|
1125
|
+
async function encodeFlashCookie(url, result, input, thrown) {
|
|
1126
|
+
const key = resolveFlashKey();
|
|
1127
|
+
if (!key) {
|
|
1128
|
+
return null;
|
|
1129
|
+
}
|
|
456
1130
|
const isError = result instanceof Error;
|
|
457
1131
|
const payload = {
|
|
458
1132
|
url,
|
|
@@ -461,29 +1135,155 @@ function encodeFlashCookie(url, result, input, thrown) {
|
|
|
461
1135
|
thrown: !!thrown,
|
|
462
1136
|
input: input.map(encodeInputValue)
|
|
463
1137
|
};
|
|
464
|
-
|
|
1138
|
+
if (fitsCookie(payload)) return flashCookie(payload, await key);
|
|
1139
|
+
payload.truncated = true;
|
|
1140
|
+
payload.input = [];
|
|
1141
|
+
if (!fitsCookie(payload)) {
|
|
1142
|
+
if (typeof payload.result === "string") {
|
|
1143
|
+
let prefix = payload.result;
|
|
1144
|
+
while (prefix.length > 0 && !fitsCookie({
|
|
1145
|
+
...payload,
|
|
1146
|
+
result: prefix
|
|
1147
|
+
})) {
|
|
1148
|
+
prefix = prefix.slice(0, prefix.length >> 1);
|
|
1149
|
+
}
|
|
1150
|
+
payload.result = prefix.length > 0 ? prefix : true;
|
|
1151
|
+
} else {
|
|
1152
|
+
payload.result = true;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (!fitsCookie(payload)) return null;
|
|
1156
|
+
return flashCookie(payload, await key);
|
|
1157
|
+
}
|
|
1158
|
+
const FLASH_MAX_AGE_SECONDS = 60;
|
|
1159
|
+
async function flashCookie(payload, key) {
|
|
1160
|
+
return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
|
|
465
1161
|
secure: true,
|
|
466
|
-
httpOnly: true
|
|
1162
|
+
httpOnly: true,
|
|
1163
|
+
sameSite: "lax",
|
|
1164
|
+
maxAge: FLASH_MAX_AGE_SECONDS
|
|
467
1165
|
});
|
|
468
1166
|
}
|
|
469
|
-
|
|
1167
|
+
const COOKIE_PAIR_BUDGET = 4000;
|
|
1168
|
+
function fitsCookie(payload) {
|
|
1169
|
+
const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
|
|
1170
|
+
const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
|
|
1171
|
+
const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
|
|
1172
|
+
return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
|
|
1173
|
+
}
|
|
1174
|
+
async function decodeFlashCookie(cookieHeader) {
|
|
470
1175
|
const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
|
|
471
1176
|
if (!match) return;
|
|
472
1177
|
try {
|
|
473
|
-
const
|
|
474
|
-
if (!
|
|
1178
|
+
const key = resolveFlashKey();
|
|
1179
|
+
if (!key) return;
|
|
1180
|
+
const json = await decryptFlashValue(await key, match);
|
|
1181
|
+
if (json === undefined) return;
|
|
1182
|
+
const payload = JSON.parse(json);
|
|
1183
|
+
if (!payload || typeof payload !== "object" || !("result" in payload)) return;
|
|
475
1184
|
const result = payload.error ? new Error(payload.result) : payload.result;
|
|
476
|
-
|
|
1185
|
+
const submission = {
|
|
477
1186
|
input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
|
|
478
1187
|
url: payload.url,
|
|
479
1188
|
result: payload.thrown ? undefined : result,
|
|
480
1189
|
error: payload.thrown ? result : undefined
|
|
481
1190
|
};
|
|
1191
|
+
if (payload.truncated) submission.truncated = true;
|
|
1192
|
+
return submission;
|
|
482
1193
|
} catch (error) {
|
|
483
|
-
console.error(error);
|
|
484
1194
|
}
|
|
485
1195
|
}
|
|
486
1196
|
|
|
1197
|
+
const RESPONSE_TAG = "seroval-plugins/web/Response";
|
|
1198
|
+
const REQUEST_TAG = "seroval-plugins/web/Request";
|
|
1199
|
+
const REFUSED_TAGS = [RESPONSE_TAG, REQUEST_TAG];
|
|
1200
|
+
const RESOLVED_PLUGINS = Symbol.for("solid.codec.resolvedPlugins");
|
|
1201
|
+
const REFUSED_ARGUMENT = Symbol("solid.serverFunction.refusedArgument");
|
|
1202
|
+
function refusedArgumentError(name = "Response or Request") {
|
|
1203
|
+
const error = new TypeError(`Server function arguments cannot carry Response or Request values (got a ${name}). ` + "Pass the data it holds — its body, headers or url — instead.");
|
|
1204
|
+
error[REFUSED_ARGUMENT] = true;
|
|
1205
|
+
return error;
|
|
1206
|
+
}
|
|
1207
|
+
function refusedArgument(error) {
|
|
1208
|
+
for (let depth = 0; depth < 4 && error !== null && typeof error === "object"; depth++) {
|
|
1209
|
+
if (error[REFUSED_ARGUMENT] === true) return error;
|
|
1210
|
+
error = error.cause;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const refused = plugin => REFUSED_TAGS.includes(plugin.tag);
|
|
1214
|
+
const reachesRefused = plugin => refused(plugin) || !!plugin.extends && plugin.extends.some(reachesRefused);
|
|
1215
|
+
function filterPlugins(plugins, out, seen) {
|
|
1216
|
+
for (const plugin of plugins) {
|
|
1217
|
+
if (seen.has(plugin)) continue;
|
|
1218
|
+
seen.add(plugin);
|
|
1219
|
+
if (refused(plugin)) continue;
|
|
1220
|
+
const severs = !!plugin.extends && plugin.extends.some(reachesRefused);
|
|
1221
|
+
out.push(severs ? {
|
|
1222
|
+
...plugin,
|
|
1223
|
+
extends: undefined
|
|
1224
|
+
} : plugin);
|
|
1225
|
+
if (plugin.extends) filterPlugins(plugin.extends, out, seen);
|
|
1226
|
+
}
|
|
1227
|
+
return out;
|
|
1228
|
+
}
|
|
1229
|
+
let defaultArgumentPlugins;
|
|
1230
|
+
const customArgumentPlugins = new WeakMap();
|
|
1231
|
+
function argumentDecodeCodec(codec, defaults) {
|
|
1232
|
+
const custom = codec && codec.plugins;
|
|
1233
|
+
let plugins = custom ? customArgumentPlugins.get(custom) : defaultArgumentPlugins;
|
|
1234
|
+
if (!plugins) {
|
|
1235
|
+
plugins = filterPlugins(custom ? [...custom, ...defaults] : defaults, [], new Set());
|
|
1236
|
+
if (custom) customArgumentPlugins.set(custom, plugins);else defaultArgumentPlugins = plugins;
|
|
1237
|
+
}
|
|
1238
|
+
return {
|
|
1239
|
+
...codec,
|
|
1240
|
+
[RESOLVED_PLUGINS]: plugins
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
function namesRefusedType(payload) {
|
|
1244
|
+
for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
|
|
1245
|
+
return false;
|
|
1246
|
+
}
|
|
1247
|
+
function withArgumentPlugins(argumentCodec, extra) {
|
|
1248
|
+
return {
|
|
1249
|
+
...argumentCodec,
|
|
1250
|
+
[RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
const UPLOAD_ARGS_PART = "args";
|
|
1255
|
+
const UPLOAD_FILE_PART = "file";
|
|
1256
|
+
const UPLOAD_TAG = "solid/server-function-upload";
|
|
1257
|
+
function isBlob(value) {
|
|
1258
|
+
if (typeof Blob !== "undefined" && value instanceof Blob) return true;
|
|
1259
|
+
return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
|
|
1260
|
+
}
|
|
1261
|
+
function malformed() {
|
|
1262
|
+
return new TypeError("Malformed server function upload");
|
|
1263
|
+
}
|
|
1264
|
+
function createUploadDeserializer(form) {
|
|
1265
|
+
const refuse = () => {
|
|
1266
|
+
throw malformed();
|
|
1267
|
+
};
|
|
1268
|
+
return {
|
|
1269
|
+
tag: UPLOAD_TAG,
|
|
1270
|
+
test: () => false,
|
|
1271
|
+
parse: {
|
|
1272
|
+
sync: refuse,
|
|
1273
|
+
async: refuse,
|
|
1274
|
+
stream: refuse
|
|
1275
|
+
},
|
|
1276
|
+
serialize: refuse,
|
|
1277
|
+
deserialize: (node, ctx) => {
|
|
1278
|
+
const index = ctx.deserialize(node.i);
|
|
1279
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
|
|
1280
|
+
const part = form.get(UPLOAD_FILE_PART + index);
|
|
1281
|
+
if (!isBlob(part)) refuse();
|
|
1282
|
+
return part;
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
|
|
487
1287
|
const config = {
|
|
488
1288
|
provideEvent: undefined,
|
|
489
1289
|
wrapInvocation: undefined,
|
|
@@ -493,7 +1293,11 @@ const config = {
|
|
|
493
1293
|
transformDirectResult: undefined,
|
|
494
1294
|
handleNoJS: undefined,
|
|
495
1295
|
endpoint: "/_server",
|
|
496
|
-
csrf: true
|
|
1296
|
+
csrf: true,
|
|
1297
|
+
bodySizeLimit: 1_048_576,
|
|
1298
|
+
maxArguments: 1000,
|
|
1299
|
+
chaosReconnectEvery: 0,
|
|
1300
|
+
buildId: undefined
|
|
497
1301
|
};
|
|
498
1302
|
function configureServerFunctionsServer({
|
|
499
1303
|
provideEvent,
|
|
@@ -505,7 +1309,12 @@ function configureServerFunctionsServer({
|
|
|
505
1309
|
handleNoJS,
|
|
506
1310
|
endpoint,
|
|
507
1311
|
csrf,
|
|
508
|
-
codec
|
|
1312
|
+
codec,
|
|
1313
|
+
bodySizeLimit,
|
|
1314
|
+
maxArguments,
|
|
1315
|
+
secret,
|
|
1316
|
+
chaosReconnectEvery,
|
|
1317
|
+
buildId
|
|
509
1318
|
} = {}) {
|
|
510
1319
|
if (provideEvent !== undefined) config.provideEvent = provideEvent;
|
|
511
1320
|
if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
|
|
@@ -517,6 +1326,23 @@ function configureServerFunctionsServer({
|
|
|
517
1326
|
if (endpoint !== undefined) config.endpoint = endpoint;
|
|
518
1327
|
if (csrf !== undefined) config.csrf = csrf;
|
|
519
1328
|
if (codec !== undefined) configureServerFunctionsCodec(codec);
|
|
1329
|
+
if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
|
|
1330
|
+
if (maxArguments !== undefined) config.maxArguments = maxArguments;
|
|
1331
|
+
if (secret !== undefined) setFlashSecret(secret);
|
|
1332
|
+
if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
|
|
1333
|
+
if (buildId !== undefined) config.buildId = buildId;
|
|
1334
|
+
}
|
|
1335
|
+
const flightSources = new Map();
|
|
1336
|
+
function registerFlightDataSource(source, hook) {
|
|
1337
|
+
assertFlightSource(source);
|
|
1338
|
+
flightSources.set(source, hook);
|
|
1339
|
+
return () => {
|
|
1340
|
+
if (flightSources.get(source) === hook) flightSources.delete(source);
|
|
1341
|
+
};
|
|
1342
|
+
}
|
|
1343
|
+
function resolveWrapInvocation(hook) {
|
|
1344
|
+
if (hook === undefined || typeof hook === "function") return hook;
|
|
1345
|
+
throw new Error(`Invalid wrapInvocation: expected a function, received ${hook === null ? "null" : typeof hook}. A hook that is not callable cannot wrap the call - configure a function, or leave ` + `wrapInvocation undefined.`);
|
|
520
1346
|
}
|
|
521
1347
|
function provideEvent(event, fn) {
|
|
522
1348
|
if (config.provideEvent) return config.provideEvent(event, fn);
|
|
@@ -524,8 +1350,198 @@ function provideEvent(event, fn) {
|
|
|
524
1350
|
if (ctx) return ctx.run(event, fn);
|
|
525
1351
|
throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
|
|
526
1352
|
}
|
|
527
|
-
const
|
|
528
|
-
const
|
|
1353
|
+
const PROVIDE_EVENT_TWICE = "provideEvent invoked the server function callback more than once: a second invocation " + "would commit the call's side effects twice. The hook must call fn exactly once and return " + "its result.";
|
|
1354
|
+
const PROVIDE_EVENT_NEVER = "provideEvent returned without invoking the server function callback: the call would have " + "answered as a void success without running the function. The hook must call fn exactly once " + "and return its result.";
|
|
1355
|
+
function provideEventOnce(provide, event, run) {
|
|
1356
|
+
let invocations = 0;
|
|
1357
|
+
const settle = () => {
|
|
1358
|
+
if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
|
|
1359
|
+
};
|
|
1360
|
+
const result = provide(event, () => {
|
|
1361
|
+
if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
|
|
1362
|
+
return run();
|
|
1363
|
+
});
|
|
1364
|
+
const promised = nativePromise(result);
|
|
1365
|
+
if (promised) {
|
|
1366
|
+
return promised.then(value => {
|
|
1367
|
+
settle();
|
|
1368
|
+
return value;
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
settle();
|
|
1372
|
+
return result;
|
|
1373
|
+
}
|
|
1374
|
+
function scopeDeferredResult(value, scope) {
|
|
1375
|
+
const bound = bindDeferredBody(value, scope);
|
|
1376
|
+
if (bound !== value || value === null || typeof value !== "object") return bound;
|
|
1377
|
+
return scopeDeferredContents(value, scope);
|
|
1378
|
+
}
|
|
1379
|
+
class ScopeFrame {
|
|
1380
|
+
constructor(value, prototype, keys, descriptors) {
|
|
1381
|
+
this.value = value;
|
|
1382
|
+
this.prototype = prototype;
|
|
1383
|
+
this.next = null;
|
|
1384
|
+
this.keys = keys;
|
|
1385
|
+
this.descriptors = descriptors;
|
|
1386
|
+
this.i = 0;
|
|
1387
|
+
this.changed = false;
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
function frameShell(frame) {
|
|
1391
|
+
return frame.next ??= frame.keys ? Object.create(frame.prototype, frame.descriptors) : frame.value.slice();
|
|
1392
|
+
}
|
|
1393
|
+
function enterScopeCarrier(value, state) {
|
|
1394
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return value;
|
|
1395
|
+
if (state.seen.has(value)) {
|
|
1396
|
+
state.cyclic.add(value);
|
|
1397
|
+
const seen = state.seen.get(value);
|
|
1398
|
+
return seen instanceof ScopeFrame ? frameShell(seen) : seen;
|
|
1399
|
+
}
|
|
1400
|
+
const bound = bindDeferredBody(value, state.scope);
|
|
1401
|
+
if (bound !== value) {
|
|
1402
|
+
state.seen.set(value, bound);
|
|
1403
|
+
return bound;
|
|
1404
|
+
}
|
|
1405
|
+
if (typeof value !== "object") return value;
|
|
1406
|
+
if (Array.isArray(value)) {
|
|
1407
|
+
if (Object.isFrozen(value)) {
|
|
1408
|
+
state.seen.set(value, value);
|
|
1409
|
+
return value;
|
|
1410
|
+
}
|
|
1411
|
+
const frame = new ScopeFrame(value, null, null, null);
|
|
1412
|
+
state.seen.set(value, frame);
|
|
1413
|
+
return frame;
|
|
1414
|
+
}
|
|
1415
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1416
|
+
if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
|
|
1417
|
+
state.seen.set(value, value);
|
|
1418
|
+
return value;
|
|
1419
|
+
}
|
|
1420
|
+
const frame = new ScopeFrame(value, prototype, Object.keys(value), Object.getOwnPropertyDescriptors(value));
|
|
1421
|
+
state.seen.set(value, frame);
|
|
1422
|
+
return frame;
|
|
1423
|
+
}
|
|
1424
|
+
function scopeDeferredContents(root, scope) {
|
|
1425
|
+
const state = {
|
|
1426
|
+
seen: new Map(),
|
|
1427
|
+
cyclic: new Set(),
|
|
1428
|
+
scope
|
|
1429
|
+
};
|
|
1430
|
+
const entered = enterScopeCarrier(root, state);
|
|
1431
|
+
if (!(entered instanceof ScopeFrame)) return entered;
|
|
1432
|
+
const stack = [entered];
|
|
1433
|
+
let delivered = NOTHING;
|
|
1434
|
+
for (;;) {
|
|
1435
|
+
const top = stack[stack.length - 1];
|
|
1436
|
+
const length = top.keys ? top.keys.length : top.value.length;
|
|
1437
|
+
let pushed = null;
|
|
1438
|
+
while (top.i < length) {
|
|
1439
|
+
const i = top.i;
|
|
1440
|
+
let original;
|
|
1441
|
+
let writable = true;
|
|
1442
|
+
if (top.keys) {
|
|
1443
|
+
const descriptor = top.descriptors[top.keys[i]];
|
|
1444
|
+
writable = "value" in descriptor && descriptor.writable === true;
|
|
1445
|
+
original = writable ? descriptor.value : undefined;
|
|
1446
|
+
} else {
|
|
1447
|
+
original = top.value[i];
|
|
1448
|
+
}
|
|
1449
|
+
if (!writable) {
|
|
1450
|
+
top.i++;
|
|
1451
|
+
continue;
|
|
1452
|
+
}
|
|
1453
|
+
let bound;
|
|
1454
|
+
if (delivered !== NOTHING) {
|
|
1455
|
+
bound = delivered;
|
|
1456
|
+
delivered = NOTHING;
|
|
1457
|
+
} else {
|
|
1458
|
+
bound = enterScopeCarrier(original, state);
|
|
1459
|
+
if (bound instanceof ScopeFrame) {
|
|
1460
|
+
pushed = bound;
|
|
1461
|
+
break;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (bound !== original) {
|
|
1465
|
+
if (top.keys) frameShell(top)[top.keys[i]] = bound;else frameShell(top)[i] = bound;
|
|
1466
|
+
top.changed = true;
|
|
1467
|
+
}
|
|
1468
|
+
top.i++;
|
|
1469
|
+
}
|
|
1470
|
+
if (pushed !== null) {
|
|
1471
|
+
stack.push(pushed);
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
stack.pop();
|
|
1475
|
+
let out;
|
|
1476
|
+
if (top.changed || state.cyclic.has(top.value)) {
|
|
1477
|
+
out = frameShell(top);
|
|
1478
|
+
state.seen.set(top.value, out);
|
|
1479
|
+
} else {
|
|
1480
|
+
state.seen.set(top.value, top.value);
|
|
1481
|
+
out = top.value;
|
|
1482
|
+
}
|
|
1483
|
+
if (stack.length === 0) return out;
|
|
1484
|
+
delivered = out;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
function bindDeferredBody(value, scope) {
|
|
1488
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return value;
|
|
1489
|
+
const promised = scope(() => nativePromise(value));
|
|
1490
|
+
if (promised) {
|
|
1491
|
+
return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
|
|
1492
|
+
}
|
|
1493
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
1494
|
+
let reader;
|
|
1495
|
+
return new ReadableStream({
|
|
1496
|
+
async pull(controller) {
|
|
1497
|
+
try {
|
|
1498
|
+
const step = await scope(() => {
|
|
1499
|
+
if (!reader) reader = value.getReader();
|
|
1500
|
+
return reader.read();
|
|
1501
|
+
});
|
|
1502
|
+
if (step.done) controller.close();else controller.enqueue(step.value);
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
controller.error(error);
|
|
1505
|
+
}
|
|
1506
|
+
},
|
|
1507
|
+
cancel(reason) {
|
|
1508
|
+
return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
1509
|
+
}
|
|
1510
|
+
}, {
|
|
1511
|
+
highWaterMark: 0
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
const scopedIterator = symbol => ({
|
|
1515
|
+
[symbol]() {
|
|
1516
|
+
const iterator = scope(() => value[symbol]());
|
|
1517
|
+
return new Proxy(iterator, {
|
|
1518
|
+
get(target, property) {
|
|
1519
|
+
const member = Reflect.get(target, property, target);
|
|
1520
|
+
return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
|
|
1521
|
+
}
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
});
|
|
1525
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
1526
|
+
return scopedIterator(Symbol.asyncIterator);
|
|
1527
|
+
}
|
|
1528
|
+
if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
1529
|
+
return scopedIterator(Symbol.iterator);
|
|
1530
|
+
}
|
|
1531
|
+
return value;
|
|
1532
|
+
}
|
|
1533
|
+
function processState(key, create) {
|
|
1534
|
+
const slot = Symbol.for(key);
|
|
1535
|
+
return globalThis[slot] || (globalThis[slot] = create());
|
|
1536
|
+
}
|
|
1537
|
+
const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
|
|
1538
|
+
const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
|
|
1539
|
+
const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
|
|
1540
|
+
const CARRIED = processState("solid.ServerFunctionCarriedGrants", () => new Set());
|
|
1541
|
+
function declaresRead(id) {
|
|
1542
|
+
const granted = METHODS.get(id);
|
|
1543
|
+
return granted !== undefined && granted === REGISTRATIONS.get(id);
|
|
1544
|
+
}
|
|
529
1545
|
const INVOCATIONS = new WeakMap();
|
|
530
1546
|
let rpcProvided = false;
|
|
531
1547
|
function provideRPC() {
|
|
@@ -538,6 +1554,15 @@ function provideRPC() {
|
|
|
538
1554
|
}
|
|
539
1555
|
function registerServerFunction(id, callback) {
|
|
540
1556
|
provideRPC();
|
|
1557
|
+
if (REGISTRATIONS.get(id) !== callback) {
|
|
1558
|
+
if (DEV && declaresRead(id)) {
|
|
1559
|
+
METHODS.set(id, callback);
|
|
1560
|
+
CARRIED.add(id);
|
|
1561
|
+
} else {
|
|
1562
|
+
METHODS.delete(id);
|
|
1563
|
+
CARRIED.delete(id);
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
541
1566
|
REGISTRATIONS.set(id, callback);
|
|
542
1567
|
return callback;
|
|
543
1568
|
}
|
|
@@ -549,6 +1574,9 @@ function getServerFunction(id) {
|
|
|
549
1574
|
throw new Error("invalid server function: " + id);
|
|
550
1575
|
}
|
|
551
1576
|
function registerServerReference(id, fn, name) {
|
|
1577
|
+
if (typeof fn !== "function") {
|
|
1578
|
+
throw new Error(`Server function${name ? ` \`${name}\`` : ""} (${id}) is not a function: a module-level ` + `"use server" export must evaluate to a server function (got ${fn === null ? "null" : typeof fn}). Move non-function exports out of the directive module.`);
|
|
1579
|
+
}
|
|
552
1580
|
registerServerFunction(id, fn);
|
|
553
1581
|
return {
|
|
554
1582
|
id,
|
|
@@ -556,85 +1584,163 @@ function registerServerReference(id, fn, name) {
|
|
|
556
1584
|
name
|
|
557
1585
|
};
|
|
558
1586
|
}
|
|
559
|
-
function
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
1587
|
+
function inProcessInvoker(call) {
|
|
1588
|
+
return (args, options) => {
|
|
1589
|
+
const signal = options && options.signal;
|
|
1590
|
+
if (!signal) return call(...args);
|
|
1591
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
1592
|
+
return new Promise((resolve, reject) => {
|
|
1593
|
+
const onAbort = () => reject(signal.reason);
|
|
1594
|
+
signal.addEventListener("abort", onAbort, {
|
|
1595
|
+
once: true
|
|
1596
|
+
});
|
|
1597
|
+
let result;
|
|
1598
|
+
try {
|
|
1599
|
+
result = call(...args);
|
|
1600
|
+
} catch (error) {
|
|
1601
|
+
signal.removeEventListener("abort", onAbort);
|
|
1602
|
+
return reject(error);
|
|
1603
|
+
}
|
|
1604
|
+
Promise.resolve(result).then(value => {
|
|
1605
|
+
signal.removeEventListener("abort", onAbort);
|
|
1606
|
+
resolve(value);
|
|
1607
|
+
}, error => {
|
|
1608
|
+
signal.removeEventListener("abort", onAbort);
|
|
1609
|
+
reject(error);
|
|
1610
|
+
});
|
|
1611
|
+
});
|
|
1612
|
+
};
|
|
1613
|
+
}
|
|
1614
|
+
function createServerReference({
|
|
1615
|
+
id,
|
|
1616
|
+
fn,
|
|
1617
|
+
name
|
|
1618
|
+
}) {
|
|
564
1619
|
if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
|
|
565
1620
|
provideRPC();
|
|
566
1621
|
const metadata = name === undefined ? {} : {
|
|
567
1622
|
name
|
|
568
1623
|
};
|
|
569
|
-
|
|
1624
|
+
const invokeChannel = inProcessInvoker((...args) => proxy(...args));
|
|
1625
|
+
const proxy = new Proxy(fn, {
|
|
570
1626
|
get(target, prop) {
|
|
571
1627
|
if (prop === "id") return id;
|
|
572
1628
|
if (prop === "url") {
|
|
573
|
-
return
|
|
1629
|
+
return serverFunctionAddress(config.endpoint, id);
|
|
574
1630
|
}
|
|
575
1631
|
if (prop === SERVER_FUNCTION_METADATA) return metadata;
|
|
1632
|
+
if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
|
|
576
1633
|
return target[prop];
|
|
577
1634
|
},
|
|
578
1635
|
apply(target, thisArg, args) {
|
|
579
1636
|
const ogEvt = getRequestEvent();
|
|
580
1637
|
if (!ogEvt) throw new Error("Cannot call server function outside of a request");
|
|
581
1638
|
const evt = {
|
|
582
|
-
...ogEvt
|
|
1639
|
+
...ogEvt,
|
|
1640
|
+
locals: {
|
|
1641
|
+
...ogEvt.locals
|
|
1642
|
+
}
|
|
583
1643
|
};
|
|
584
1644
|
INVOCATIONS.set(evt, {
|
|
585
|
-
id
|
|
1645
|
+
id,
|
|
1646
|
+
live: false
|
|
586
1647
|
});
|
|
587
1648
|
evt.serverOnly = true;
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
1649
|
+
const scope = run => provideEvent(evt, run);
|
|
1650
|
+
const wrap = resolveWrapInvocation(config.wrapInvocation);
|
|
1651
|
+
const hook = requestErrorHook(ogEvt);
|
|
1652
|
+
let result;
|
|
1653
|
+
try {
|
|
1654
|
+
result = provideEventOnce(provideEvent, evt, () => {
|
|
1655
|
+
const run = () => fn.apply(thisArg, args);
|
|
1656
|
+
return observeInvocation({
|
|
1657
|
+
id,
|
|
1658
|
+
direct: true,
|
|
1659
|
+
event: evt,
|
|
1660
|
+
args
|
|
1661
|
+
}, () => reportDirectFailure(() => wrap ? wrap(run, {
|
|
1662
|
+
id,
|
|
1663
|
+
args,
|
|
1664
|
+
event: evt,
|
|
1665
|
+
direct: true
|
|
1666
|
+
}) : run(), id, hook));
|
|
1667
|
+
});
|
|
1668
|
+
} catch (error) {
|
|
1669
|
+
throw directEnvelopeValue(error, evt);
|
|
1670
|
+
}
|
|
1671
|
+
result = result && typeof result.then === "function" ? result.then(value => directEnvelopeValue(value, evt), error => {
|
|
1672
|
+
throw directEnvelopeValue(error, evt);
|
|
1673
|
+
}) : directEnvelopeValue(result, evt);
|
|
1674
|
+
result = scopeDeferredResult(result, scope);
|
|
597
1675
|
const transform = config.transformDirectResult;
|
|
598
1676
|
if (transform && result && typeof result.then === "function") {
|
|
599
|
-
return result.then(value => transform(value, {
|
|
1677
|
+
return result.then(value => scopeDeferredResult(transform(value, {
|
|
600
1678
|
id,
|
|
601
1679
|
args,
|
|
602
1680
|
event: evt
|
|
603
|
-
}));
|
|
1681
|
+
}), scope));
|
|
604
1682
|
}
|
|
605
|
-
return transform ? transform(result, {
|
|
1683
|
+
return transform ? scopeDeferredResult(transform(result, {
|
|
606
1684
|
id,
|
|
607
1685
|
args,
|
|
608
1686
|
event: evt
|
|
609
|
-
}) : result;
|
|
1687
|
+
}), scope) : result;
|
|
610
1688
|
}
|
|
611
1689
|
});
|
|
1690
|
+
REFERENCE_BINDINGS.set(proxy, fn);
|
|
1691
|
+
return proxy;
|
|
612
1692
|
}
|
|
613
1693
|
function GET(fn) {
|
|
614
1694
|
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
615
1695
|
throw new Error("GET expects a server function reference");
|
|
616
1696
|
}
|
|
617
|
-
|
|
618
|
-
|
|
1697
|
+
const id = fn.id;
|
|
1698
|
+
const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
|
|
1699
|
+
const existing = METHODS.get(id);
|
|
1700
|
+
if (existing !== undefined && existing !== binding) {
|
|
1701
|
+
if (CARRIED.has(id)) return fn;
|
|
1702
|
+
if (DEV) {
|
|
1703
|
+
throw new Error(`GET() would rebind the existing grant for server function "${id}" to a different ` + `function. A GET declaration is made about a function, not an id - two references ` + `sharing one id cannot both hold it. Give the functions distinct ids, or drop the ` + `stale declaration.`);
|
|
1704
|
+
}
|
|
1705
|
+
METHODS.delete(id);
|
|
1706
|
+
return fn;
|
|
1707
|
+
}
|
|
1708
|
+
METHODS.set(id, binding);
|
|
1709
|
+
CARRIED.delete(id);
|
|
1710
|
+
const reference = withMeta(fn, {
|
|
619
1711
|
method: "GET"
|
|
620
1712
|
});
|
|
1713
|
+
guardDeclaredMethod(getServerFunctionMetadata(reference), id);
|
|
1714
|
+
return reference;
|
|
1715
|
+
}
|
|
1716
|
+
function guardDeclaredMethod(metadata, id) {
|
|
1717
|
+
let declared = metadata.method;
|
|
1718
|
+
Object.defineProperty(metadata, "method", {
|
|
1719
|
+
configurable: true,
|
|
1720
|
+
enumerable: true,
|
|
1721
|
+
get: () => declared,
|
|
1722
|
+
set(next) {
|
|
1723
|
+
if (next === declared) return;
|
|
1724
|
+
if (DEV) {
|
|
1725
|
+
throw new Error(`withMeta({ method }) cannot change the GET() declaration of server function ` + `"${id}". The method is declaration-scoped: it was granted about the function ` + `by GET(fn), and a metadata write cannot re-shape the wire grant.`);
|
|
1726
|
+
}
|
|
1727
|
+
METHODS.delete(id);
|
|
1728
|
+
declared = next;
|
|
1729
|
+
}
|
|
1730
|
+
});
|
|
621
1731
|
}
|
|
622
1732
|
function live(fn) {
|
|
623
1733
|
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
624
1734
|
throw new Error("live expects a server function reference");
|
|
625
1735
|
}
|
|
1736
|
+
if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
|
|
626
1737
|
const metadata = {
|
|
627
1738
|
...getServerFunctionMetadata(fn),
|
|
628
1739
|
live: true
|
|
629
1740
|
};
|
|
630
|
-
const wrapped = async (...args) =>
|
|
631
|
-
const result = await fn(...args);
|
|
632
|
-
if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
|
|
633
|
-
result[LIVE_SOURCE] = true;
|
|
634
|
-
}
|
|
635
|
-
return result;
|
|
636
|
-
};
|
|
1741
|
+
const wrapped = async (...args) => brandLive(await fn(...args));
|
|
637
1742
|
wrapped[SERVER_FUNCTION_METADATA] = metadata;
|
|
1743
|
+
wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
|
|
638
1744
|
wrapped.id = fn.id;
|
|
639
1745
|
Object.defineProperty(wrapped, "url", {
|
|
640
1746
|
get: () => fn.url,
|
|
@@ -642,59 +1748,255 @@ function live(fn) {
|
|
|
642
1748
|
});
|
|
643
1749
|
return wrapped;
|
|
644
1750
|
}
|
|
1751
|
+
function broadcast(fn) {
|
|
1752
|
+
const ref = live(fn);
|
|
1753
|
+
ref[SERVER_FUNCTION_METADATA].broadcast = true;
|
|
1754
|
+
BROADCASTS.add(fn.id);
|
|
1755
|
+
return ref;
|
|
1756
|
+
}
|
|
1757
|
+
function encodedArguments(request, argsEncoding, argumentBytes) {
|
|
1758
|
+
if (request.method !== "POST") return argsEncoding || "";
|
|
1759
|
+
if (!argumentBytes) return undefined;
|
|
1760
|
+
return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
|
|
1761
|
+
}
|
|
1762
|
+
const BROADCASTS = new Set();
|
|
1763
|
+
function brandLive(answer) {
|
|
1764
|
+
if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
|
|
1765
|
+
answer[LIVE_SOURCE] = true;
|
|
1766
|
+
}
|
|
1767
|
+
return answer;
|
|
1768
|
+
}
|
|
645
1769
|
function getServerFunctionInvocation() {
|
|
646
1770
|
return getEventServerFunctionInvocation(getRequestEvent());
|
|
647
1771
|
}
|
|
648
1772
|
function getEventServerFunctionInvocation(event) {
|
|
649
1773
|
return event && INVOCATIONS.get(event);
|
|
650
1774
|
}
|
|
651
|
-
function
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
1775
|
+
function resolveAddress(url) {
|
|
1776
|
+
return parseServerFunctionAddress(url.pathname, config.endpoint);
|
|
1777
|
+
}
|
|
1778
|
+
const DECODE_DEPTH_LIMIT = 64;
|
|
1779
|
+
function assertDecodeDepth(value) {
|
|
1780
|
+
let level = [value];
|
|
1781
|
+
for (let depth = 0; level.length > 0; depth++) {
|
|
1782
|
+
if (depth > DECODE_DEPTH_LIMIT) {
|
|
1783
|
+
throw new TypeError("Server function arguments exceed the decode depth limit");
|
|
1784
|
+
}
|
|
1785
|
+
const next = [];
|
|
1786
|
+
for (const node of level) {
|
|
1787
|
+
if (node === null || typeof node !== "object") continue;
|
|
1788
|
+
if (Array.isArray(node)) {
|
|
1789
|
+
for (const child of node) next.push(child);
|
|
1790
|
+
} else {
|
|
1791
|
+
for (const key of Object.keys(node)) next.push(node[key]);
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
level = next;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
|
|
1798
|
+
function stripUnsafeArgumentKeys(value) {
|
|
1799
|
+
const stack = [value];
|
|
1800
|
+
const seen = new Set();
|
|
1801
|
+
while (stack.length) {
|
|
1802
|
+
const v = stack.pop();
|
|
1803
|
+
if (v === null || typeof v !== "object" || seen.has(v)) continue;
|
|
1804
|
+
seen.add(v);
|
|
1805
|
+
for (const key of UNSAFE_ARGUMENT_KEYS) {
|
|
1806
|
+
delete v[key];
|
|
1807
|
+
}
|
|
1808
|
+
for (const key of Object.keys(v)) stack.push(v[key]);
|
|
1809
|
+
if (v instanceof Map) {
|
|
1810
|
+
for (const [k, entry] of v) stack.push(k, entry);
|
|
1811
|
+
} else if (v instanceof Set) {
|
|
1812
|
+
for (const member of v) stack.push(member);
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
return value;
|
|
1816
|
+
}
|
|
1817
|
+
async function bufferBodyWithin(request, limit) {
|
|
1818
|
+
const reader = request.body.getReader();
|
|
1819
|
+
const signal = request.signal;
|
|
1820
|
+
const chunks = [];
|
|
1821
|
+
let total = 0;
|
|
1822
|
+
const onAbort = () => {
|
|
1823
|
+
reader.cancel(signal.reason).catch(() => {});
|
|
1824
|
+
};
|
|
1825
|
+
if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
|
|
1826
|
+
once: true
|
|
1827
|
+
});
|
|
1828
|
+
try {
|
|
1829
|
+
for (;;) {
|
|
1830
|
+
const {
|
|
1831
|
+
done,
|
|
1832
|
+
value
|
|
1833
|
+
} = await reader.read();
|
|
1834
|
+
if (signal.aborted) throw signal.reason;
|
|
1835
|
+
if (done) break;
|
|
1836
|
+
total += value.byteLength;
|
|
1837
|
+
if (total > limit) {
|
|
1838
|
+
reader.cancel().catch(() => {});
|
|
1839
|
+
return null;
|
|
1840
|
+
}
|
|
1841
|
+
chunks.push(value);
|
|
1842
|
+
}
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
reader.cancel(error).catch(() => {});
|
|
1845
|
+
throw error;
|
|
1846
|
+
} finally {
|
|
1847
|
+
signal.removeEventListener("abort", onAbort);
|
|
1848
|
+
reader.releaseLock();
|
|
1849
|
+
}
|
|
1850
|
+
const body = new Uint8Array(total);
|
|
1851
|
+
let offset = 0;
|
|
1852
|
+
for (const chunk of chunks) {
|
|
1853
|
+
body.set(chunk, offset);
|
|
1854
|
+
offset += chunk.byteLength;
|
|
1855
|
+
}
|
|
1856
|
+
return body;
|
|
1857
|
+
}
|
|
1858
|
+
function withBufferedBody(request, body) {
|
|
1859
|
+
return new Request(request.url, {
|
|
1860
|
+
method: request.method,
|
|
1861
|
+
headers: request.headers,
|
|
1862
|
+
signal: request.signal,
|
|
1863
|
+
body
|
|
1864
|
+
});
|
|
1865
|
+
}
|
|
1866
|
+
const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
|
|
1867
|
+
const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
|
|
1868
|
+
function unknownFormatError(tag) {
|
|
1869
|
+
const error = new TypeError(`Server function body carries an unrecognized ${BODY_FORMAT_HEADER} tag ("${tag}"): the ` + "caller encodes a newer wire format than this build can decode (version skew), or an " + "intermediary duplicated the header. The body was refused rather than reinterpreted.");
|
|
1870
|
+
error[FORMAT_SKEW] = true;
|
|
1871
|
+
return error;
|
|
1872
|
+
}
|
|
1873
|
+
async function decodeArguments(decode, payload) {
|
|
1874
|
+
if (payload === null) return await decode(undefined);
|
|
1875
|
+
const refuseNamed = () => {
|
|
1876
|
+
const text = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
|
|
1877
|
+
if (namesRefusedType(text)) throw refusedArgumentError();
|
|
1878
|
+
};
|
|
1879
|
+
const connection = {};
|
|
1880
|
+
let value;
|
|
1881
|
+
try {
|
|
1882
|
+
value = await decode({
|
|
1883
|
+
connection
|
|
1884
|
+
});
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
if (connection.ended) connection.ended.then(end => end.sweep());
|
|
1887
|
+
refuseNamed();
|
|
1888
|
+
throw error;
|
|
1889
|
+
}
|
|
1890
|
+
if (connection.ended) {
|
|
1891
|
+
const {
|
|
1892
|
+
open,
|
|
1893
|
+
sweep
|
|
1894
|
+
} = await connection.ended;
|
|
1895
|
+
sweep();
|
|
1896
|
+
if (open) refuseNamed();
|
|
655
1897
|
}
|
|
656
|
-
return
|
|
1898
|
+
return value;
|
|
1899
|
+
}
|
|
1900
|
+
let decodeModule;
|
|
1901
|
+
async function loadArgumentCodec(codec) {
|
|
1902
|
+
decodeModule = await import('@solidjs/web/serialization/decode');
|
|
1903
|
+
return argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS);
|
|
657
1904
|
}
|
|
658
|
-
|
|
1905
|
+
const argumentCodecFor = codec => decodeModule ? argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS) : loadArgumentCodec(codec);
|
|
1906
|
+
async function parseArguments(request, url, scripted, codec, buffered) {
|
|
659
1907
|
const parsed = [];
|
|
660
1908
|
const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
1909
|
+
const args = url.searchParams.get("args");
|
|
1910
|
+
if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
|
|
1911
|
+
let result;
|
|
1912
|
+
if (args.startsWith(";0x")) {
|
|
1913
|
+
let argumentCodec = argumentCodecFor(codec);
|
|
1914
|
+
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
|
|
1915
|
+
result = await decodeArguments(wire => deserializeStream(new Response(args), argumentCodec, wire), args);
|
|
1916
|
+
} else {
|
|
1917
|
+
result = JSON.parse(args);
|
|
1918
|
+
assertDecodeDepth(result);
|
|
1919
|
+
}
|
|
1920
|
+
if (!Array.isArray(result)) {
|
|
1921
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
1922
|
+
}
|
|
1923
|
+
stripUnsafeArgumentKeys(result);
|
|
1924
|
+
for (const arg of result) {
|
|
1925
|
+
parsed.push(arg);
|
|
668
1926
|
}
|
|
1927
|
+
} else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
|
|
1928
|
+
parsed.push(url.searchParams);
|
|
669
1929
|
}
|
|
670
1930
|
if (request.method === "POST" && request.body !== null) {
|
|
671
|
-
|
|
1931
|
+
if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
|
|
1932
|
+
throw unknownFormatError(bodyFormat);
|
|
1933
|
+
}
|
|
1934
|
+
const body = request.clone();
|
|
1935
|
+
let decoded;
|
|
1936
|
+
if (bodyFormat === BodyFormat.Serialized) {
|
|
1937
|
+
let argumentCodec = argumentCodecFor(codec);
|
|
1938
|
+
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
|
|
1939
|
+
if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
|
|
1940
|
+
const form = await body.formData();
|
|
1941
|
+
const encoded = form.get(UPLOAD_ARGS_PART);
|
|
1942
|
+
if (typeof encoded !== "string") {
|
|
1943
|
+
throw new TypeError("Malformed server function upload");
|
|
1944
|
+
}
|
|
1945
|
+
const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
|
|
1946
|
+
decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
|
|
1947
|
+
} else {
|
|
1948
|
+
decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
|
|
1949
|
+
}
|
|
1950
|
+
} else {
|
|
1951
|
+
decoded = await extractBody(body, codec);
|
|
1952
|
+
}
|
|
672
1953
|
if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
|
|
673
|
-
|
|
1954
|
+
if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
|
|
1955
|
+
if (!Array.isArray(decoded)) {
|
|
1956
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
1957
|
+
}
|
|
1958
|
+
return stripUnsafeArgumentKeys(decoded);
|
|
1959
|
+
}
|
|
1960
|
+
if (decoded === undefined) {
|
|
1961
|
+
if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
|
|
1962
|
+
return parsed;
|
|
1963
|
+
}
|
|
1964
|
+
throw new TypeError("Server function body carries no usable encoding");
|
|
674
1965
|
}
|
|
675
1966
|
parsed.push(decoded);
|
|
676
1967
|
}
|
|
677
1968
|
return parsed;
|
|
678
1969
|
}
|
|
679
|
-
async function foldFlightData(
|
|
1970
|
+
async function foldFlightData(hooks, event, headers, outcome, context = {}) {
|
|
680
1971
|
if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
|
|
681
1972
|
digestOutcome(event, outcome);
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
1973
|
+
const folded = [];
|
|
1974
|
+
for (const [source, hook] of hooks) {
|
|
1975
|
+
try {
|
|
1976
|
+
const slice = await hook(event, outcome);
|
|
1977
|
+
if (slice !== undefined) folded.push([source, slice]);
|
|
1978
|
+
} catch (error) {
|
|
1979
|
+
console.error(`Error collecting flight data for source "${source}"`, error);
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
if (folded.length === 0) return outcome.value;
|
|
1983
|
+
const data = Object.fromEntries(folded);
|
|
1984
|
+
headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
|
|
685
1985
|
if (context.transformFlightResult) {
|
|
686
1986
|
const transformed = await context.transformFlightResult(event, {
|
|
687
1987
|
value: outcome.value,
|
|
688
1988
|
data
|
|
689
1989
|
}, context);
|
|
690
1990
|
if (transformed !== undefined) {
|
|
691
|
-
|
|
1991
|
+
const owned = ownResponse(transformed);
|
|
1992
|
+
for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
|
|
692
1993
|
headers.forEach((value, key) => {
|
|
693
|
-
if (key !== "set-cookie" && !
|
|
694
|
-
|
|
1994
|
+
if (key !== "set-cookie" && !owned.headers.has(key)) {
|
|
1995
|
+
owned.headers.set(key, value);
|
|
695
1996
|
}
|
|
696
1997
|
});
|
|
697
|
-
|
|
1998
|
+
owned.headers.set(SINGLE_FLIGHT_HEADER, headers.get(SINGLE_FLIGHT_HEADER));
|
|
1999
|
+
return owned;
|
|
698
2000
|
}
|
|
699
2001
|
}
|
|
700
2002
|
return outcome.value === undefined ? {
|
|
@@ -761,7 +2063,7 @@ function foldSetCookies(headers, setCookies) {
|
|
|
761
2063
|
}
|
|
762
2064
|
function mergeResponseHeaders(target, source) {
|
|
763
2065
|
source.forEach((value, key) => {
|
|
764
|
-
if (key !== "set-cookie") target.append(key, value);
|
|
2066
|
+
if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
|
|
765
2067
|
});
|
|
766
2068
|
if (source.getSetCookie) {
|
|
767
2069
|
for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
|
|
@@ -770,10 +2072,52 @@ function mergeResponseHeaders(target, source) {
|
|
|
770
2072
|
}
|
|
771
2073
|
}
|
|
772
2074
|
const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
|
|
2075
|
+
function maskRedirect(headers, response, requestUrl) {
|
|
2076
|
+
const target = response.headers && response.headers.get("Location");
|
|
2077
|
+
if (target) {
|
|
2078
|
+
headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
|
|
2079
|
+
}
|
|
2080
|
+
headers.delete("Location");
|
|
2081
|
+
}
|
|
2082
|
+
const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
|
|
2083
|
+
function enforceComposedHeaderInvariants(response) {
|
|
2084
|
+
for (const name of BOUNDED_COMPOSED_HEADERS) {
|
|
2085
|
+
const value = response.headers.get(name);
|
|
2086
|
+
if (value === null) continue;
|
|
2087
|
+
if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
|
|
2088
|
+
return refuseComposedHeader(response, name, `${name} response header refused at ${value.length} characters`, DEV ? `The ${name} response header is ${value.length} characters; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} it would overflow receivers (an 8 KiB proxy ` + `buffer holds the whole header block) and the response dies at the socket after ` + `the mutation committed. Refused rather than trimmed: a cut redirect target is a ` + `different address, a dropped revalidate key is a silently stale cache. The ` + `redirect()/reload() helpers enforce this bound with the full reasoning at the ` + `call site.` : null);
|
|
2089
|
+
}
|
|
2090
|
+
if (name === REVALIDATE_HEADER) continue;
|
|
2091
|
+
const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
|
|
2092
|
+
if (!isHttpNavigationTarget(target)) {
|
|
2093
|
+
return refuseComposedHeader(response, name, `${name} response header refused: non-http(s) navigation target`, DEV ? `The ${name} response header carries a navigation target with a non-http(s) ` + `scheme ("${target.slice(0, 64)}"). A javascript: target is same-origin script ` + `execution in any integration that navigates to it, so only http(s) and ` + `relative targets leave this transport. If the target came from request data ` + `(?next= and friends), validate it against your own origin before redirecting.` : null);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
return response;
|
|
2097
|
+
}
|
|
2098
|
+
function refuseComposedHeader(response, name, headerMessage, body) {
|
|
2099
|
+
if (response.body) {
|
|
2100
|
+
try {
|
|
2101
|
+
const cancelled = response.body.cancel();
|
|
2102
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
2103
|
+
} catch {}
|
|
2104
|
+
}
|
|
2105
|
+
const headers = new Headers();
|
|
2106
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
|
|
2107
|
+
return new Response(body, {
|
|
2108
|
+
status: 500,
|
|
2109
|
+
headers
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
function warnScripted304(functionId) {
|
|
2113
|
+
if (DEV) {
|
|
2114
|
+
console.warn(`Server function "${functionId}" answered a scripted call with 304 Not Modified. ` + `The client transport sends no conditional headers, so nothing was asked to be ` + `revalidated: the call resolves to undefined, not "unchanged". For conditional ` + `reads, declare the function GET and set ETag/Cache-Control response headers - ` + `the browser owns that exchange and replays its cached answer on a 304.`);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
773
2117
|
function createNoJSHandler({
|
|
774
2118
|
base = ""
|
|
775
2119
|
} = {}) {
|
|
776
|
-
return function handleNoJS(result, request, args, thrown) {
|
|
2120
|
+
return async function handleNoJS(result, request, args, thrown) {
|
|
777
2121
|
const url = new URL(request.url);
|
|
778
2122
|
let back = new URL(base || "/", url.origin).toString();
|
|
779
2123
|
try {
|
|
@@ -798,8 +2142,9 @@ function createNoJSHandler({
|
|
|
798
2142
|
Location: back
|
|
799
2143
|
});
|
|
800
2144
|
}
|
|
801
|
-
if (result && !(result instanceof Response)) {
|
|
802
|
-
|
|
2145
|
+
if (result !== undefined && !(result instanceof Response)) {
|
|
2146
|
+
const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
|
|
2147
|
+
if (flash !== null) headers.append("Set-Cookie", flash);
|
|
803
2148
|
}
|
|
804
2149
|
return new Response(null, {
|
|
805
2150
|
status,
|
|
@@ -813,44 +2158,309 @@ function isFormPost(request) {
|
|
|
813
2158
|
const type = request.headers.get("content-type") || "";
|
|
814
2159
|
return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
|
|
815
2160
|
}
|
|
816
|
-
function
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
let onAbort = null;
|
|
821
|
-
const teardown = () => {
|
|
822
|
-
if (closed) return;
|
|
823
|
-
closed = true;
|
|
824
|
-
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
825
|
-
if (cancelSerialize) cancelSerialize();
|
|
826
|
-
if (closeIterator) closeIterator();
|
|
2161
|
+
function guardFailures(value, state) {
|
|
2162
|
+
if (!state) state = {
|
|
2163
|
+
seen: new WeakMap(),
|
|
2164
|
+
cyclic: new WeakSet()
|
|
827
2165
|
};
|
|
828
|
-
|
|
2166
|
+
const entered = enterGuard(value, state);
|
|
2167
|
+
if (!(entered instanceof Frame)) return entered;
|
|
2168
|
+
const stack = [entered];
|
|
2169
|
+
let delivered = NOTHING;
|
|
2170
|
+
for (;;) {
|
|
2171
|
+
const top = stack[stack.length - 1];
|
|
2172
|
+
const items = top.items;
|
|
2173
|
+
let pushed = null;
|
|
2174
|
+
while (top.i < items.length) {
|
|
2175
|
+
const i = top.i;
|
|
2176
|
+
let original;
|
|
2177
|
+
if (top.kind === OBJECT) {
|
|
2178
|
+
const descriptor = top.descriptors[items[i]];
|
|
2179
|
+
if ("value" in descriptor) {
|
|
2180
|
+
original = descriptor.value;
|
|
2181
|
+
} else if (typeof descriptor.get === "function") {
|
|
2182
|
+
if (top.accessorRead !== i) {
|
|
2183
|
+
try {
|
|
2184
|
+
top.accessorValue = descriptor.get.call(top.value);
|
|
2185
|
+
} catch (error) {
|
|
2186
|
+
throw wireServerFunctionError(error, "channel");
|
|
2187
|
+
}
|
|
2188
|
+
top.accessorRead = i;
|
|
2189
|
+
}
|
|
2190
|
+
original = top.accessorValue;
|
|
2191
|
+
} else {
|
|
2192
|
+
top.i++;
|
|
2193
|
+
continue;
|
|
2194
|
+
}
|
|
2195
|
+
} else {
|
|
2196
|
+
original = items[i];
|
|
2197
|
+
}
|
|
2198
|
+
let guarded;
|
|
2199
|
+
if (delivered !== NOTHING) {
|
|
2200
|
+
guarded = delivered;
|
|
2201
|
+
delivered = NOTHING;
|
|
2202
|
+
} else {
|
|
2203
|
+
guarded = enterGuard(original, state);
|
|
2204
|
+
if (guarded instanceof Frame) {
|
|
2205
|
+
pushed = guarded;
|
|
2206
|
+
break;
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
if (top.kind === ARRAY) {
|
|
2210
|
+
if (guarded !== original) {
|
|
2211
|
+
top.next[i] = guarded;
|
|
2212
|
+
top.changed = true;
|
|
2213
|
+
}
|
|
2214
|
+
} else if (top.kind === MAP) {
|
|
2215
|
+
if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
|
|
2216
|
+
if (guarded !== original) top.changed = true;
|
|
2217
|
+
} else if (top.kind === SET) {
|
|
2218
|
+
top.next.add(guarded);
|
|
2219
|
+
if (guarded !== original) top.changed = true;
|
|
2220
|
+
} else if (guarded !== original || top.accessorRead === i) {
|
|
2221
|
+
Object.defineProperty(top.next, items[i], {
|
|
2222
|
+
value: guarded,
|
|
2223
|
+
writable: true,
|
|
2224
|
+
configurable: true,
|
|
2225
|
+
enumerable: top.descriptors[items[i]].enumerable
|
|
2226
|
+
});
|
|
2227
|
+
top.changed = true;
|
|
2228
|
+
}
|
|
2229
|
+
top.i++;
|
|
2230
|
+
}
|
|
2231
|
+
if (pushed !== null) {
|
|
2232
|
+
stack.push(pushed);
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
stack.pop();
|
|
2236
|
+
const out = keepGuarded(top.value, top.next, top.changed, state);
|
|
2237
|
+
if (stack.length === 0) return out;
|
|
2238
|
+
delivered = out;
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const NOTHING = Symbol();
|
|
2242
|
+
const ARRAY = 0;
|
|
2243
|
+
const MAP = 1;
|
|
2244
|
+
const SET = 2;
|
|
2245
|
+
const OBJECT = 3;
|
|
2246
|
+
class Frame {
|
|
2247
|
+
constructor(kind, value, next, items, descriptors) {
|
|
2248
|
+
this.kind = kind;
|
|
2249
|
+
this.value = value;
|
|
2250
|
+
this.next = next;
|
|
2251
|
+
this.items = items;
|
|
2252
|
+
this.descriptors = descriptors;
|
|
2253
|
+
this.i = 0;
|
|
2254
|
+
this.changed = false;
|
|
2255
|
+
this.accessorRead = -1;
|
|
2256
|
+
this.accessorValue = undefined;
|
|
2257
|
+
this.pendingKey = undefined;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
function guardOperation(state, run) {
|
|
2261
|
+
return state.scope ? state.scope(run) : run();
|
|
2262
|
+
}
|
|
2263
|
+
function enterGuard(value, state) {
|
|
2264
|
+
if (value === null || typeof value !== "object") return value;
|
|
2265
|
+
if (state.seen.has(value)) {
|
|
2266
|
+
state.cyclic.add(value);
|
|
2267
|
+
return state.seen.get(value);
|
|
2268
|
+
}
|
|
2269
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
2270
|
+
let reader;
|
|
2271
|
+
const gate = state.gate;
|
|
2272
|
+
let finished = false;
|
|
2273
|
+
const close = () => {
|
|
2274
|
+
if (finished) return;
|
|
2275
|
+
finished = true;
|
|
2276
|
+
try {
|
|
2277
|
+
const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
|
|
2278
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
2279
|
+
} catch {}
|
|
2280
|
+
};
|
|
2281
|
+
const guardedStream = new ReadableStream({
|
|
2282
|
+
async pull(controller) {
|
|
2283
|
+
try {
|
|
2284
|
+
if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
|
|
2285
|
+
if (finished) {
|
|
2286
|
+
controller.close();
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
if (!reader) reader = guardOperation(state, () => value.getReader());
|
|
2290
|
+
const {
|
|
2291
|
+
done,
|
|
2292
|
+
value: chunk
|
|
2293
|
+
} = await guardOperation(state, () => reader.read());
|
|
2294
|
+
done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
|
|
2295
|
+
} catch (error) {
|
|
2296
|
+
controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
|
|
2297
|
+
}
|
|
2298
|
+
},
|
|
2299
|
+
cancel(reason) {
|
|
2300
|
+
finished = true;
|
|
2301
|
+
return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
2302
|
+
}
|
|
2303
|
+
});
|
|
2304
|
+
if (gate) gate.onOpen(close);
|
|
2305
|
+
state.seen.set(value, guardedStream);
|
|
2306
|
+
return guardedStream;
|
|
2307
|
+
}
|
|
2308
|
+
if (typeof value.then === "function") {
|
|
2309
|
+
const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
|
|
2310
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2311
|
+
});
|
|
2312
|
+
guardedPromise.catch(() => {});
|
|
2313
|
+
state.seen.set(value, guardedPromise);
|
|
2314
|
+
return guardedPromise;
|
|
2315
|
+
}
|
|
2316
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
829
2317
|
const source = value;
|
|
830
|
-
|
|
2318
|
+
const gate = state.gate;
|
|
2319
|
+
const guardedIterable = {
|
|
831
2320
|
[Symbol.asyncIterator]() {
|
|
832
|
-
const
|
|
2321
|
+
const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
|
|
833
2322
|
let finished = false;
|
|
834
|
-
|
|
2323
|
+
const close = () => {
|
|
835
2324
|
if (finished) return;
|
|
836
2325
|
finished = true;
|
|
837
2326
|
try {
|
|
838
|
-
const returned =
|
|
2327
|
+
const returned = iterator.return && guardOperation(state, () => iterator.return());
|
|
839
2328
|
if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
|
|
840
2329
|
} catch {}
|
|
841
2330
|
};
|
|
842
|
-
if (
|
|
2331
|
+
if (gate) gate.onOpen(close);
|
|
2332
|
+
const step = () => finished ? Promise.resolve({
|
|
2333
|
+
done: true,
|
|
2334
|
+
value: undefined
|
|
2335
|
+
}) : guardOperation(state, () => iterator.next()).then(step => {
|
|
2336
|
+
if (step.done) {
|
|
2337
|
+
finished = true;
|
|
2338
|
+
return step;
|
|
2339
|
+
}
|
|
2340
|
+
return {
|
|
2341
|
+
done: false,
|
|
2342
|
+
value: guardOperation(state, () => guardFailures(step.value, state))
|
|
2343
|
+
};
|
|
2344
|
+
}, error => {
|
|
2345
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2346
|
+
});
|
|
843
2347
|
return {
|
|
844
|
-
next: () => finished ?
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
2348
|
+
next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
|
|
2349
|
+
return: () => {
|
|
2350
|
+
close();
|
|
2351
|
+
return Promise.resolve({
|
|
2352
|
+
done: true,
|
|
2353
|
+
value: undefined
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
848
2356
|
};
|
|
849
2357
|
}
|
|
850
2358
|
};
|
|
2359
|
+
state.seen.set(value, guardedIterable);
|
|
2360
|
+
return guardedIterable;
|
|
2361
|
+
}
|
|
2362
|
+
if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
2363
|
+
const scopedIterable = scopeDeferredResult(value, state.scope);
|
|
2364
|
+
state.seen.set(value, scopedIterable);
|
|
2365
|
+
return scopedIterable;
|
|
2366
|
+
}
|
|
2367
|
+
if (Array.isArray(value)) {
|
|
2368
|
+
const next = value.slice();
|
|
2369
|
+
state.seen.set(value, next);
|
|
2370
|
+
return new Frame(ARRAY, value, next, value, null);
|
|
2371
|
+
}
|
|
2372
|
+
if (value instanceof Map) {
|
|
2373
|
+
const next = new Map();
|
|
2374
|
+
state.seen.set(value, next);
|
|
2375
|
+
const items = [];
|
|
2376
|
+
for (const entry of value) items.push(entry[0], entry[1]);
|
|
2377
|
+
return new Frame(MAP, value, next, items, null);
|
|
851
2378
|
}
|
|
2379
|
+
if (value instanceof Set) {
|
|
2380
|
+
const next = new Set();
|
|
2381
|
+
state.seen.set(value, next);
|
|
2382
|
+
return new Frame(SET, value, next, [...value], null);
|
|
2383
|
+
}
|
|
2384
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2385
|
+
if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
|
|
2386
|
+
state.seen.set(value, value);
|
|
2387
|
+
return value;
|
|
2388
|
+
}
|
|
2389
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
2390
|
+
for (const key of Object.keys(descriptors)) {
|
|
2391
|
+
descriptors[key].configurable = true;
|
|
2392
|
+
if ("value" in descriptors[key]) descriptors[key].writable = true;
|
|
2393
|
+
}
|
|
2394
|
+
const next = Object.create(prototype, descriptors);
|
|
2395
|
+
state.seen.set(value, next);
|
|
2396
|
+
const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
|
|
2397
|
+
const descriptor = descriptors[key];
|
|
2398
|
+
return descriptor.enumerable || "value" in descriptor;
|
|
2399
|
+
});
|
|
2400
|
+
return new Frame(OBJECT, value, next, children, descriptors);
|
|
2401
|
+
}
|
|
2402
|
+
function keepGuarded(value, next, changed, state) {
|
|
2403
|
+
if (changed || state.cyclic.has(value)) return next;
|
|
2404
|
+
state.seen.set(value, value);
|
|
2405
|
+
return value;
|
|
2406
|
+
}
|
|
2407
|
+
function serializeResponseStream(value, codecOptions, signal, scope, live) {
|
|
2408
|
+
let closed = false;
|
|
2409
|
+
const frame = live ? payload => {
|
|
2410
|
+
const id = live.pending;
|
|
2411
|
+
live.pending = undefined;
|
|
2412
|
+
return createEventChunk(payload, id);
|
|
2413
|
+
} : createChunk;
|
|
2414
|
+
let stopLive = null;
|
|
2415
|
+
const stopHeartbeat = () => {
|
|
2416
|
+
if (stopLive !== null) {
|
|
2417
|
+
stopLive();
|
|
2418
|
+
stopLive = null;
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
let streamController = null;
|
|
2422
|
+
let demandWaiters = null;
|
|
2423
|
+
const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
|
|
2424
|
+
const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
|
|
2425
|
+
const supplyDemand = () => {
|
|
2426
|
+
const resolvers = demandWaiters;
|
|
2427
|
+
demandWaiters = null;
|
|
2428
|
+
if (resolvers) for (const resolve of resolvers) resolve();
|
|
2429
|
+
};
|
|
2430
|
+
const sourceClosers = new Set();
|
|
2431
|
+
const gate = {
|
|
2432
|
+
wantsMore,
|
|
2433
|
+
awaitDemand,
|
|
2434
|
+
onOpen(close) {
|
|
2435
|
+
if (closed) close();else sourceClosers.add(close);
|
|
2436
|
+
}
|
|
2437
|
+
};
|
|
2438
|
+
const guardState = {
|
|
2439
|
+
seen: new WeakMap(),
|
|
2440
|
+
cyclic: new WeakSet(),
|
|
2441
|
+
gate,
|
|
2442
|
+
scope
|
|
2443
|
+
};
|
|
2444
|
+
value = guardOperation(guardState, () => guardFailures(value, guardState));
|
|
2445
|
+
let cancelSerialize = null;
|
|
2446
|
+
let onAbort = null;
|
|
2447
|
+
const finishSource = () => {
|
|
2448
|
+
for (const close of sourceClosers) close();
|
|
2449
|
+
sourceClosers.clear();
|
|
2450
|
+
supplyDemand();
|
|
2451
|
+
};
|
|
2452
|
+
const teardown = () => {
|
|
2453
|
+
if (closed) return;
|
|
2454
|
+
closed = true;
|
|
2455
|
+
stopHeartbeat();
|
|
2456
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2457
|
+
if (cancelSerialize) cancelSerialize();
|
|
2458
|
+
finishSource();
|
|
2459
|
+
};
|
|
852
2460
|
return new ReadableStream({
|
|
853
2461
|
async start(controller) {
|
|
2462
|
+
streamController = controller;
|
|
2463
|
+
if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
|
|
854
2464
|
if (signal) {
|
|
855
2465
|
if (signal.aborted) {
|
|
856
2466
|
teardown();
|
|
@@ -880,35 +2490,364 @@ function serializeResponseStream(value, codecOptions, signal) {
|
|
|
880
2490
|
cancelSerialize = serializeJSON(value, {
|
|
881
2491
|
...codecOptions,
|
|
882
2492
|
onParse(node) {
|
|
883
|
-
if (
|
|
2493
|
+
if (closed) return;
|
|
2494
|
+
const chunk = frame(JSON.stringify(node));
|
|
2495
|
+
if (live && live.nodes) live.nodes.set(chunk, node);
|
|
2496
|
+
controller.enqueue(chunk);
|
|
884
2497
|
},
|
|
885
2498
|
onDone() {
|
|
886
2499
|
if (closed) return;
|
|
887
2500
|
closed = true;
|
|
2501
|
+
stopHeartbeat();
|
|
888
2502
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2503
|
+
finishSource();
|
|
889
2504
|
controller.close();
|
|
890
2505
|
},
|
|
891
2506
|
onError(error) {
|
|
892
2507
|
if (closed) return;
|
|
893
2508
|
closed = true;
|
|
2509
|
+
stopHeartbeat();
|
|
894
2510
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
895
|
-
|
|
2511
|
+
finishSource();
|
|
2512
|
+
try {
|
|
2513
|
+
const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
|
|
2514
|
+
controller.enqueue(frame(encodeErrorTrailer(delivered)));
|
|
2515
|
+
controller.close();
|
|
2516
|
+
} catch {
|
|
2517
|
+
try {
|
|
2518
|
+
controller.error(error);
|
|
2519
|
+
} catch {}
|
|
2520
|
+
}
|
|
896
2521
|
}
|
|
897
2522
|
});
|
|
898
2523
|
},
|
|
2524
|
+
pull() {
|
|
2525
|
+
supplyDemand();
|
|
2526
|
+
},
|
|
899
2527
|
cancel() {
|
|
900
2528
|
teardown();
|
|
901
2529
|
}
|
|
902
2530
|
});
|
|
903
2531
|
}
|
|
904
|
-
function serializedResponse(value, headers, codec, signal) {
|
|
2532
|
+
function serializedResponse(value, headers, codec, signal, scope) {
|
|
905
2533
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
906
2534
|
headers.set("Content-Type", "text/plain");
|
|
907
|
-
return new Response(serializeResponseStream(value, codec, signal), {
|
|
2535
|
+
return new Response(serializeResponseStream(value, codec, signal, scope), {
|
|
2536
|
+
headers
|
|
2537
|
+
});
|
|
2538
|
+
}
|
|
2539
|
+
const LIVE_HEARTBEAT_INTERVAL = 20000;
|
|
2540
|
+
function armLiveBody(controller, teardown) {
|
|
2541
|
+
let stopped = false;
|
|
2542
|
+
const heartbeat = setInterval(() => {
|
|
2543
|
+
if (stopped) return;
|
|
2544
|
+
try {
|
|
2545
|
+
controller.enqueue(EVENT_STREAM_HEARTBEAT);
|
|
2546
|
+
} catch {}
|
|
2547
|
+
}, LIVE_HEARTBEAT_INTERVAL);
|
|
2548
|
+
if (typeof heartbeat === "object" && heartbeat && typeof heartbeat.unref === "function") heartbeat.unref();
|
|
2549
|
+
let chaos = null;
|
|
2550
|
+
if (DEV && config.chaosReconnectEvery > 0) {
|
|
2551
|
+
chaos = setTimeout(() => {
|
|
2552
|
+
if (stopped) return;
|
|
2553
|
+
teardown();
|
|
2554
|
+
try {
|
|
2555
|
+
controller.error(new Error("Live response ended by the chaos knob."));
|
|
2556
|
+
} catch {}
|
|
2557
|
+
}, config.chaosReconnectEvery);
|
|
2558
|
+
if (typeof chaos === "object" && chaos && typeof chaos.unref === "function") chaos.unref();
|
|
2559
|
+
}
|
|
2560
|
+
return () => {
|
|
2561
|
+
if (stopped) return;
|
|
2562
|
+
stopped = true;
|
|
2563
|
+
clearInterval(heartbeat);
|
|
2564
|
+
if (chaos !== null) clearTimeout(chaos);
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
function liveSource(value, lastEventId, position, scope, refs) {
|
|
2568
|
+
const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
|
|
2569
|
+
if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
|
|
2570
|
+
const digest = digestOf(value);
|
|
2571
|
+
if (digest !== undefined && digest === lastEventId) return async function* () {}();
|
|
2572
|
+
position.pending = digest;
|
|
2573
|
+
return value;
|
|
2574
|
+
}
|
|
2575
|
+
const source = value;
|
|
2576
|
+
return {
|
|
2577
|
+
[Symbol.asyncIterator]() {
|
|
2578
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
2579
|
+
let first = true;
|
|
2580
|
+
const step = () => iterator.next().then(result => {
|
|
2581
|
+
if (result.done) return result;
|
|
2582
|
+
if (refs) refs.turn();
|
|
2583
|
+
const digest = digestOf(result.value);
|
|
2584
|
+
if (refs) position.yields.push({
|
|
2585
|
+
value: result.value,
|
|
2586
|
+
digest
|
|
2587
|
+
});
|
|
2588
|
+
if (first) {
|
|
2589
|
+
first = false;
|
|
2590
|
+
if (digest !== undefined && digest === lastEventId) return step();
|
|
2591
|
+
}
|
|
2592
|
+
position.pending = digest;
|
|
2593
|
+
return result;
|
|
2594
|
+
});
|
|
2595
|
+
return {
|
|
2596
|
+
next: step,
|
|
2597
|
+
return: v => iterator.return ? iterator.return(v) : Promise.resolve({
|
|
2598
|
+
done: true,
|
|
2599
|
+
value: v
|
|
2600
|
+
}),
|
|
2601
|
+
throw: e => iterator.throw ? iterator.throw(e) : Promise.reject(e)
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
};
|
|
2605
|
+
}
|
|
2606
|
+
function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
|
|
2607
|
+
if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
|
|
2608
|
+
return encodeResult(value, headers, status, codec, request.signal, scope);
|
|
2609
|
+
}
|
|
2610
|
+
if (shareKey !== undefined && value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
|
|
2611
|
+
const shared = sharedSourceResponse(shareKey, value, headers, status, codec, request);
|
|
2612
|
+
if (shared) return shared;
|
|
2613
|
+
}
|
|
2614
|
+
const position = {
|
|
2615
|
+
pending: undefined
|
|
2616
|
+
};
|
|
2617
|
+
const source = liveSource(value, request.headers.get(LAST_EVENT_ID_HEADER), position, scope);
|
|
2618
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
2619
|
+
headers.set("Content-Type", "text/event-stream");
|
|
2620
|
+
headers.set("Cache-Control", "no-store");
|
|
2621
|
+
headers.set("X-Accel-Buffering", "no");
|
|
2622
|
+
try {
|
|
2623
|
+
return new Response(serializeResponseStream(source, codec, request.signal, scope, position), {
|
|
2624
|
+
status,
|
|
2625
|
+
headers
|
|
2626
|
+
});
|
|
2627
|
+
} catch (error) {
|
|
2628
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
const SHARED_SOURCES = new Map();
|
|
2632
|
+
class GenerationalRefs extends Map {
|
|
2633
|
+
count = 0;
|
|
2634
|
+
touched = new Set();
|
|
2635
|
+
get size() {
|
|
2636
|
+
return this.count;
|
|
2637
|
+
}
|
|
2638
|
+
get(key) {
|
|
2639
|
+
const id = super.get(key);
|
|
2640
|
+
if (id !== undefined) this.touched.add(key);
|
|
2641
|
+
return id;
|
|
2642
|
+
}
|
|
2643
|
+
set(key, value) {
|
|
2644
|
+
if (!super.has(key)) this.count++;
|
|
2645
|
+
this.touched.add(key);
|
|
2646
|
+
return super.set(key, value);
|
|
2647
|
+
}
|
|
2648
|
+
turn() {
|
|
2649
|
+
for (const key of [...super.keys()]) if (!this.touched.has(key)) super.delete(key);
|
|
2650
|
+
this.touched = new Set();
|
|
2651
|
+
}
|
|
2652
|
+
idOf(key) {
|
|
2653
|
+
return super.get(key);
|
|
2654
|
+
}
|
|
2655
|
+
reserve() {
|
|
2656
|
+
return this.count++;
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
function sharedSourceResponse(key, value, headers, status, codec, request) {
|
|
2660
|
+
let shared = SHARED_SOURCES.get(key);
|
|
2661
|
+
let snapshot;
|
|
2662
|
+
if (shared && !shared.ended) {
|
|
2663
|
+
snapshot = sharedSnapshot(shared);
|
|
2664
|
+
if (snapshot === null) return undefined;
|
|
2665
|
+
if (value !== shared.source) closeUnread(value);
|
|
2666
|
+
} else shared = startSharedSource(key, value, codec);
|
|
2667
|
+
return tapSharedSource(shared, request, headers, status, snapshot);
|
|
2668
|
+
}
|
|
2669
|
+
function closeUnread(value) {
|
|
2670
|
+
try {
|
|
2671
|
+
const closing = typeof value.return === "function" ? value.return() : typeof value.cancel === "function" ? value.cancel() : undefined;
|
|
2672
|
+
if (closing && typeof closing.then === "function") closing.then(undefined, () => {});
|
|
2673
|
+
} catch {}
|
|
2674
|
+
}
|
|
2675
|
+
function startSharedSource(key, value, codec) {
|
|
2676
|
+
const refs = new GenerationalRefs();
|
|
2677
|
+
const shared = {
|
|
2678
|
+
key,
|
|
2679
|
+
codec,
|
|
2680
|
+
refs,
|
|
2681
|
+
encode: null,
|
|
2682
|
+
head: null,
|
|
2683
|
+
node: null,
|
|
2684
|
+
value: undefined,
|
|
2685
|
+
position: undefined,
|
|
2686
|
+
stream: undefined,
|
|
2687
|
+
source: value,
|
|
2688
|
+
taps: new Set(),
|
|
2689
|
+
ended: false,
|
|
2690
|
+
teardown: new AbortController()
|
|
2691
|
+
};
|
|
2692
|
+
SHARED_SOURCES.set(key, shared);
|
|
2693
|
+
const event = broadcastEvent();
|
|
2694
|
+
const store = globalThis[RequestContext];
|
|
2695
|
+
const scope = run => store ? store.run(event, run) : run();
|
|
2696
|
+
const live = {
|
|
2697
|
+
pending: undefined,
|
|
2698
|
+
yields: [],
|
|
2699
|
+
nodes: new WeakMap()
|
|
2700
|
+
};
|
|
2701
|
+
const body = serializeResponseStream(liveSource(value, undefined, live, scope, refs), {
|
|
2702
|
+
...codec,
|
|
2703
|
+
refs
|
|
2704
|
+
}, shared.teardown.signal, scope, live);
|
|
2705
|
+
pumpSharedSource(shared, body.getReader(), live);
|
|
2706
|
+
return shared;
|
|
2707
|
+
}
|
|
2708
|
+
async function pumpSharedSource(shared, reader, {
|
|
2709
|
+
nodes,
|
|
2710
|
+
yields
|
|
2711
|
+
}) {
|
|
2712
|
+
try {
|
|
2713
|
+
shared.encode = (await import('@solidjs/web/serialization')).serializeJSON;
|
|
2714
|
+
while (true) {
|
|
2715
|
+
const {
|
|
2716
|
+
done,
|
|
2717
|
+
value: chunk
|
|
2718
|
+
} = await reader.read();
|
|
2719
|
+
if (done) break;
|
|
2720
|
+
const node = nodes.get(chunk);
|
|
2721
|
+
if (shared.head === null) shared.head = chunk;else if (node && node.t === 32 && (shared.stream ??= node.i) === node.i) {
|
|
2722
|
+
const {
|
|
2723
|
+
value,
|
|
2724
|
+
digest
|
|
2725
|
+
} = yields.shift();
|
|
2726
|
+
shared.node = node;
|
|
2727
|
+
shared.value = value;
|
|
2728
|
+
shared.position = digest;
|
|
2729
|
+
}
|
|
2730
|
+
for (const tap of shared.taps) tap.write(chunk);
|
|
2731
|
+
}
|
|
2732
|
+
} catch {}
|
|
2733
|
+
shared.ended = true;
|
|
2734
|
+
if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
|
|
2735
|
+
for (const tap of [...shared.taps]) tap.end();
|
|
2736
|
+
}
|
|
2737
|
+
function sharedSnapshot(shared) {
|
|
2738
|
+
if (shared.node === null) return undefined;
|
|
2739
|
+
const own = new Map();
|
|
2740
|
+
let root;
|
|
2741
|
+
let done = false;
|
|
2742
|
+
const cancel = shared.encode(shared.value, {
|
|
2743
|
+
...shared.codec,
|
|
2744
|
+
refs: own,
|
|
2745
|
+
onParse(node) {
|
|
2746
|
+
root ??= node;
|
|
2747
|
+
},
|
|
2748
|
+
onDone() {
|
|
2749
|
+
done = true;
|
|
2750
|
+
},
|
|
2751
|
+
onError() {}
|
|
2752
|
+
});
|
|
2753
|
+
if (!done || root === undefined) {
|
|
2754
|
+
cancel();
|
|
2755
|
+
return null;
|
|
2756
|
+
}
|
|
2757
|
+
const ids = new Map();
|
|
2758
|
+
for (const [value, id] of own) ids.set(id, shared.refs.idOf(value) ?? shared.refs.reserve());
|
|
2759
|
+
return createEventChunk(JSON.stringify({
|
|
2760
|
+
...shared.node,
|
|
2761
|
+
f: renumberNode(root, ids)
|
|
2762
|
+
}), shared.position);
|
|
2763
|
+
}
|
|
2764
|
+
function renumberNode(node, ids) {
|
|
2765
|
+
if (Array.isArray(node)) return node.map(item => renumberNode(item, ids));
|
|
2766
|
+
if (node === null || typeof node !== "object") return node;
|
|
2767
|
+
const out = {};
|
|
2768
|
+
for (const key in node) out[key] = key === "i" && typeof node[key] === "number" ? ids.get(node[key]) ?? node[key] : renumberNode(node[key], ids);
|
|
2769
|
+
return out;
|
|
2770
|
+
}
|
|
2771
|
+
function tapSharedSource(shared, request, headers, status, snapshot) {
|
|
2772
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
2773
|
+
headers.set("Content-Type", "text/event-stream");
|
|
2774
|
+
headers.set("Cache-Control", "no-store");
|
|
2775
|
+
headers.set("X-Accel-Buffering", "no");
|
|
2776
|
+
const signal = request.signal;
|
|
2777
|
+
let closed = false;
|
|
2778
|
+
let stopLive = null;
|
|
2779
|
+
let tap = null;
|
|
2780
|
+
const leave = () => {
|
|
2781
|
+
if (closed) return;
|
|
2782
|
+
closed = true;
|
|
2783
|
+
if (stopLive) stopLive();
|
|
2784
|
+
if (signal) signal.removeEventListener("abort", leave);
|
|
2785
|
+
shared.taps.delete(tap);
|
|
2786
|
+
if (!shared.taps.size && !shared.ended) {
|
|
2787
|
+
shared.ended = true;
|
|
2788
|
+
if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
|
|
2789
|
+
shared.teardown.abort();
|
|
2790
|
+
}
|
|
2791
|
+
};
|
|
2792
|
+
const body = new ReadableStream({
|
|
2793
|
+
start(controller) {
|
|
2794
|
+
tap = {
|
|
2795
|
+
write(chunk) {
|
|
2796
|
+
if (closed) return;
|
|
2797
|
+
try {
|
|
2798
|
+
controller.enqueue(chunk);
|
|
2799
|
+
} catch {
|
|
2800
|
+
leave();
|
|
2801
|
+
}
|
|
2802
|
+
},
|
|
2803
|
+
end() {
|
|
2804
|
+
leave();
|
|
2805
|
+
try {
|
|
2806
|
+
controller.close();
|
|
2807
|
+
} catch {}
|
|
2808
|
+
}
|
|
2809
|
+
};
|
|
2810
|
+
stopLive = armLiveBody(controller, leave);
|
|
2811
|
+
if (shared.head) controller.enqueue(shared.head);
|
|
2812
|
+
if (snapshot) controller.enqueue(snapshot);
|
|
2813
|
+
if (shared.ended || signal && signal.aborted) return tap.end();
|
|
2814
|
+
shared.taps.add(tap);
|
|
2815
|
+
if (signal) signal.addEventListener("abort", leave);
|
|
2816
|
+
},
|
|
2817
|
+
cancel() {
|
|
2818
|
+
leave();
|
|
2819
|
+
}
|
|
2820
|
+
});
|
|
2821
|
+
return new Response(body, {
|
|
2822
|
+
status,
|
|
908
2823
|
headers
|
|
909
2824
|
});
|
|
910
2825
|
}
|
|
911
|
-
function
|
|
2826
|
+
function broadcastEvent() {
|
|
2827
|
+
const event = {
|
|
2828
|
+
broadcast: true
|
|
2829
|
+
};
|
|
2830
|
+
for (const name of ["request", "locals", "clientAddress", "nativeEvent"]) Object.defineProperty(event, name, {
|
|
2831
|
+
get() {
|
|
2832
|
+
if (DEV) console.warn(`A broadcast server function read the request (\`event.${name}\`) while producing ` + "its answer, which every viewer shares; read per-viewer state before returning it.");
|
|
2833
|
+
return undefined;
|
|
2834
|
+
}
|
|
2835
|
+
});
|
|
2836
|
+
return event;
|
|
2837
|
+
}
|
|
2838
|
+
function encodeResult(value, headers, status, codec, signal, scope) {
|
|
2839
|
+
if (NULL_BODY_STATUSES.has(status)) {
|
|
2840
|
+
if (value === undefined || value === null) {
|
|
2841
|
+
if (status !== 304) headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
2842
|
+
return new Response(null, {
|
|
2843
|
+
status,
|
|
2844
|
+
headers
|
|
2845
|
+
});
|
|
2846
|
+
}
|
|
2847
|
+
const error = new Error(`Server function answered status ${status}, which forbids a response body, with a value. ` + `Return respond(undefined, { status: ${status} }) for a bodiless answer, or drop the ` + `status to send the value.`);
|
|
2848
|
+
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
|
|
2849
|
+
return encodeResult(error, headers, 500, codec, signal, scope);
|
|
2850
|
+
}
|
|
912
2851
|
const direct = getHeadersAndBody(value);
|
|
913
2852
|
if (direct) {
|
|
914
2853
|
for (const [key, val] of Object.entries(direct.headers || {})) {
|
|
@@ -920,54 +2859,137 @@ function encodeResult(value, headers, status, codec, signal) {
|
|
|
920
2859
|
});
|
|
921
2860
|
}
|
|
922
2861
|
if (value === undefined) {
|
|
2862
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
923
2863
|
return new Response(null, {
|
|
924
2864
|
status,
|
|
925
2865
|
headers
|
|
926
2866
|
});
|
|
927
2867
|
}
|
|
928
2868
|
try {
|
|
929
|
-
|
|
2869
|
+
const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
|
|
2870
|
+
if (jsonSafe) {
|
|
930
2871
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
|
|
931
2872
|
headers.set("Content-Type", "application/json");
|
|
932
|
-
|
|
2873
|
+
const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
|
|
2874
|
+
return new Response(body, {
|
|
933
2875
|
status,
|
|
934
2876
|
headers
|
|
935
2877
|
});
|
|
936
2878
|
}
|
|
937
2879
|
} catch {
|
|
938
2880
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
status,
|
|
942
|
-
|
|
943
|
-
|
|
2881
|
+
try {
|
|
2882
|
+
const response = serializedResponse(value, headers, codec, signal, scope);
|
|
2883
|
+
return status === 200 ? response : new Response(response.body, {
|
|
2884
|
+
status,
|
|
2885
|
+
headers
|
|
2886
|
+
});
|
|
2887
|
+
} catch (error) {
|
|
2888
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
const ERROR_HEADER_VALUE_LIMIT = 1024;
|
|
2892
|
+
function boundedErrorHeaderValue(message) {
|
|
2893
|
+
let label = message.length > 256 ? message.slice(0, 256) : message;
|
|
2894
|
+
let encoded = encodeErrorHeaderValue(label);
|
|
2895
|
+
while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
|
|
2896
|
+
label = label.slice(0, Math.ceil(label.length / 2));
|
|
2897
|
+
encoded = encodeErrorHeaderValue(label);
|
|
2898
|
+
}
|
|
2899
|
+
return encoded;
|
|
944
2900
|
}
|
|
945
2901
|
const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
|
|
946
2902
|
let DEV = false === true;
|
|
947
2903
|
function setServerFunctionsDev(dev) {
|
|
948
2904
|
DEV = !!dev;
|
|
949
2905
|
}
|
|
2906
|
+
const REQUEST_ERROR_HOOKS = new WeakMap();
|
|
2907
|
+
function siteFor(handling, event, direct) {
|
|
2908
|
+
const invocation = event ? INVOCATIONS.get(event) : undefined;
|
|
2909
|
+
const site = {
|
|
2910
|
+
kind: "server-function",
|
|
2911
|
+
handling,
|
|
2912
|
+
direct
|
|
2913
|
+
};
|
|
2914
|
+
if (invocation) site.functionId = invocation.id;
|
|
2915
|
+
if (event) site.event = event;
|
|
2916
|
+
return site;
|
|
2917
|
+
}
|
|
2918
|
+
function wireServerFunctionError(value, handling, event = currentEvent()) {
|
|
2919
|
+
const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
|
|
2920
|
+
return report.mapped ? report.value : sanitizeServerError(value);
|
|
2921
|
+
}
|
|
2922
|
+
function currentEvent() {
|
|
2923
|
+
const store = globalThis[RequestContext];
|
|
2924
|
+
return store ? store.getStore() : undefined;
|
|
2925
|
+
}
|
|
2926
|
+
function reportDirectFailure(run, id, hook) {
|
|
2927
|
+
const report = error => {
|
|
2928
|
+
if (error instanceof Response || isResponseEnvelope(error)) throw error;
|
|
2929
|
+
reportServerError(error, {
|
|
2930
|
+
kind: "server-function",
|
|
2931
|
+
handling: "thrown",
|
|
2932
|
+
functionId: id,
|
|
2933
|
+
direct: true
|
|
2934
|
+
}, null, hook);
|
|
2935
|
+
throw error;
|
|
2936
|
+
};
|
|
2937
|
+
let result;
|
|
2938
|
+
try {
|
|
2939
|
+
result = run();
|
|
2940
|
+
} catch (error) {
|
|
2941
|
+
report(error);
|
|
2942
|
+
}
|
|
2943
|
+
return result && typeof result.then === "function" ? result.then(undefined, report) : result;
|
|
2944
|
+
}
|
|
2945
|
+
function directEnvelopeValue(result, event) {
|
|
2946
|
+
if (!isResponseEnvelope(result)) return result;
|
|
2947
|
+
const {
|
|
2948
|
+
response,
|
|
2949
|
+
value
|
|
2950
|
+
} = result;
|
|
2951
|
+
const stub = event.response;
|
|
2952
|
+
if (response && stub && stub.headers && response.headers.getSetCookie) {
|
|
2953
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
2954
|
+
stub.headers.append("Set-Cookie", cookie);
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
return value;
|
|
2958
|
+
}
|
|
950
2959
|
function sanitizeServerError(value) {
|
|
951
2960
|
if (DEV) return value;
|
|
952
2961
|
if (isSafeError(value)) return value;
|
|
953
|
-
|
|
2962
|
+
const wire = new Error(GENERIC_SERVER_ERROR_MESSAGE);
|
|
2963
|
+
return wire;
|
|
954
2964
|
}
|
|
955
|
-
function
|
|
956
|
-
return (
|
|
2965
|
+
function serverFunctionUrl(fn, ...args) {
|
|
2966
|
+
return serverFunctionUrlFor(config.endpoint, fn, args);
|
|
2967
|
+
}
|
|
2968
|
+
function serverFunctionActionUrl(fn, ...boundArgs) {
|
|
2969
|
+
return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
|
|
2970
|
+
}
|
|
2971
|
+
function parseServerFunctionActionUrl(url) {
|
|
2972
|
+
const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
|
|
2973
|
+
return parsed && parsed.id;
|
|
957
2974
|
}
|
|
958
2975
|
async function matchesOrigin(origin, request, matcher) {
|
|
959
2976
|
if (matcher === undefined) return origin === new URL(request.url).origin;
|
|
960
|
-
if (typeof matcher === "function") return
|
|
2977
|
+
if (typeof matcher === "function") return (await matcher(origin, request)) === true;
|
|
961
2978
|
return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
|
|
962
2979
|
}
|
|
963
2980
|
async function allowsServerFunctionRequest(request, options) {
|
|
964
2981
|
const fetchSite = request.headers.get("Sec-Fetch-Site");
|
|
965
2982
|
if (fetchSite === "same-origin") return true;
|
|
966
|
-
if (fetchSite === "
|
|
967
|
-
return false;
|
|
968
|
-
}
|
|
2983
|
+
if (fetchSite === "none") return false;
|
|
969
2984
|
const origin = request.headers.get("Origin");
|
|
970
|
-
if (
|
|
2985
|
+
if (fetchSite === "same-site" || fetchSite === "cross-site") {
|
|
2986
|
+
if (origin === null || options.origin === undefined) return false;
|
|
2987
|
+
return (await matchesOrigin(origin, request, options.origin)) ? origin : false;
|
|
2988
|
+
}
|
|
2989
|
+
if (origin !== null) {
|
|
2990
|
+
if (!(await matchesOrigin(origin, request, options.origin))) return false;
|
|
2991
|
+
return origin === new URL(request.url).origin ? true : origin;
|
|
2992
|
+
}
|
|
971
2993
|
const referer = request.headers.get("Referer");
|
|
972
2994
|
if (referer !== null) {
|
|
973
2995
|
try {
|
|
@@ -979,21 +3001,23 @@ async function allowsServerFunctionRequest(request, options) {
|
|
|
979
3001
|
return options.allowRequestsWithoutOriginCheck === true;
|
|
980
3002
|
}
|
|
981
3003
|
const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
|
|
982
|
-
function
|
|
983
|
-
const current =
|
|
984
|
-
if (current === "*") return
|
|
3004
|
+
function appendVary(headers, names) {
|
|
3005
|
+
const current = headers.get("Vary");
|
|
3006
|
+
if (current === "*") return;
|
|
985
3007
|
const values = current ? current.split(",").map(value => value.trim()) : [];
|
|
986
|
-
const
|
|
987
|
-
for (const
|
|
988
|
-
if (!
|
|
3008
|
+
const seen = new Set(values.map(value => value.toLowerCase()));
|
|
3009
|
+
for (const name of names) {
|
|
3010
|
+
if (!seen.has(name.toLowerCase())) values.push(name);
|
|
989
3011
|
}
|
|
990
|
-
|
|
3012
|
+
headers.set("Vary", values.join(", "));
|
|
3013
|
+
}
|
|
3014
|
+
function withHeaders(response, write) {
|
|
991
3015
|
try {
|
|
992
|
-
response.headers
|
|
3016
|
+
write(response.headers);
|
|
993
3017
|
return response;
|
|
994
3018
|
} catch {
|
|
995
3019
|
const headers = new Headers(response.headers);
|
|
996
|
-
headers
|
|
3020
|
+
write(headers);
|
|
997
3021
|
return new Response(response.body, {
|
|
998
3022
|
status: response.status,
|
|
999
3023
|
statusText: response.statusText,
|
|
@@ -1001,6 +3025,42 @@ function withCSRFVary(response) {
|
|
|
1001
3025
|
});
|
|
1002
3026
|
}
|
|
1003
3027
|
}
|
|
3028
|
+
function withCSRFVary(response) {
|
|
3029
|
+
return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
|
|
3030
|
+
}
|
|
3031
|
+
const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, BUILD_HEADER].join(", ");
|
|
3032
|
+
const PREFLIGHT_MAX_AGE = "600";
|
|
3033
|
+
const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
|
|
3034
|
+
function withCORS(response, cors) {
|
|
3035
|
+
if (cors === null) return response;
|
|
3036
|
+
return withHeaders(response, headers => {
|
|
3037
|
+
headers.set("Access-Control-Allow-Origin", cors.origin);
|
|
3038
|
+
if (cors.credentials) headers.set("Access-Control-Allow-Credentials", "true");
|
|
3039
|
+
const exposed = [];
|
|
3040
|
+
for (const name of headers.keys()) {
|
|
3041
|
+
if (CORS_SAFELISTED_RESPONSE_HEADERS.has(name) || name === "set-cookie" || name === "vary" || name.startsWith("access-control-")) {
|
|
3042
|
+
continue;
|
|
3043
|
+
}
|
|
3044
|
+
exposed.push(name);
|
|
3045
|
+
}
|
|
3046
|
+
if (exposed.length > 0) headers.set("Access-Control-Expose-Headers", exposed.join(", "));
|
|
3047
|
+
appendVary(headers, ["Origin"]);
|
|
3048
|
+
});
|
|
3049
|
+
}
|
|
3050
|
+
function preflightResponse(request) {
|
|
3051
|
+
const requested = request.headers.get("Access-Control-Request-Headers");
|
|
3052
|
+
const response = new Response(null, {
|
|
3053
|
+
status: 204,
|
|
3054
|
+
headers: {
|
|
3055
|
+
"Access-Control-Allow-Methods": "POST, GET, HEAD",
|
|
3056
|
+
"Access-Control-Allow-Headers": requested !== null && requested.trim() !== "" ? requested : TRANSPORT_REQUEST_HEADERS,
|
|
3057
|
+
"Access-Control-Max-Age": PREFLIGHT_MAX_AGE,
|
|
3058
|
+
"Cache-Control": "no-store"
|
|
3059
|
+
}
|
|
3060
|
+
});
|
|
3061
|
+
appendVary(response.headers, ["Access-Control-Request-Method", "Access-Control-Request-Headers"]);
|
|
3062
|
+
return response;
|
|
3063
|
+
}
|
|
1004
3064
|
function forbiddenResponse() {
|
|
1005
3065
|
return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
|
|
1006
3066
|
status: 403,
|
|
@@ -1009,56 +3069,198 @@ function forbiddenResponse() {
|
|
|
1009
3069
|
}
|
|
1010
3070
|
}));
|
|
1011
3071
|
}
|
|
3072
|
+
function nativePromise(value) {
|
|
3073
|
+
if (value instanceof Promise) return value;
|
|
3074
|
+
try {
|
|
3075
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
|
|
3076
|
+
} catch {}
|
|
3077
|
+
}
|
|
1012
3078
|
async function handleServerFunctionRequest(request, options = {}) {
|
|
1013
|
-
const codec =
|
|
3079
|
+
const codec = {
|
|
3080
|
+
...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
|
|
3081
|
+
};
|
|
3082
|
+
codec.serializeErrorStacks ??= DEV;
|
|
1014
3083
|
const url = new URL(request.url);
|
|
3084
|
+
const method = request.method;
|
|
3085
|
+
const address = resolveAddress(url);
|
|
3086
|
+
const functionId = address && address.id;
|
|
3087
|
+
const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
|
|
1015
3088
|
const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
|
|
1016
|
-
const protectsRequest = csrf !== false;
|
|
1017
|
-
|
|
1018
|
-
|
|
3089
|
+
const protectsRequest = csrf !== false && (!declaredRead || CARRIED.has(functionId) || typeof csrf === "object" && csrf.protectDeclaredReads === true);
|
|
3090
|
+
const csrfOptions = csrf === true ? {} : csrf;
|
|
3091
|
+
let verdict = true;
|
|
3092
|
+
let readVariesByOrigin = false;
|
|
3093
|
+
if (protectsRequest) {
|
|
3094
|
+
verdict = await allowsServerFunctionRequest(request, csrfOptions);
|
|
3095
|
+
} else if (csrfOptions !== false && csrfOptions.origin !== undefined) {
|
|
3096
|
+
readVariesByOrigin = true;
|
|
3097
|
+
const admitted = await allowsServerFunctionRequest(request, csrfOptions);
|
|
3098
|
+
if (typeof admitted === "string") verdict = admitted;
|
|
3099
|
+
}
|
|
3100
|
+
const cors = typeof verdict === "string" ? {
|
|
3101
|
+
origin: verdict,
|
|
3102
|
+
credentials: csrfOptions.allowCredentials === true
|
|
3103
|
+
} : null;
|
|
3104
|
+
const finish = response => {
|
|
3105
|
+
const finalized = withCORS(finalizeTransportResponse(response, method), cors);
|
|
3106
|
+
return readVariesByOrigin && cors === null ? withHeaders(finalized, headers => appendVary(headers, ["Origin"])) : finalized;
|
|
3107
|
+
};
|
|
3108
|
+
if (cors !== null && method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
|
|
3109
|
+
return finish(preflightResponse(request));
|
|
3110
|
+
}
|
|
3111
|
+
let serverFunction;
|
|
3112
|
+
if (functionId) {
|
|
3113
|
+
try {
|
|
3114
|
+
serverFunction = getServerFunction(functionId);
|
|
3115
|
+
} catch {
|
|
3116
|
+
return finish(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
|
|
3117
|
+
status: 404,
|
|
3118
|
+
headers: {
|
|
3119
|
+
[UNKNOWN_HEADER]: "true"
|
|
3120
|
+
}
|
|
3121
|
+
}));
|
|
3122
|
+
}
|
|
3123
|
+
}
|
|
3124
|
+
if (verdict === false) {
|
|
3125
|
+
return finish(forbiddenResponse());
|
|
1019
3126
|
}
|
|
1020
|
-
const instance = request.headers.get(INSTANCE_HEADER);
|
|
1021
|
-
const functionId = resolveFunctionId(request, url);
|
|
1022
3127
|
if (!functionId) {
|
|
1023
3128
|
const response = new Response(DEV ? "Server function not found" : null, {
|
|
1024
3129
|
status: 404
|
|
1025
3130
|
});
|
|
1026
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3131
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1027
3132
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
3133
|
+
const callerBuild = request.headers.get(BUILD_HEADER);
|
|
3134
|
+
if (config.buildId && callerBuild !== null && callerBuild !== config.buildId) {
|
|
3135
|
+
return finish(new Response(DEV ? `Server function call from build "${callerBuild}" refused by build "${config.buildId}"` : null, {
|
|
3136
|
+
status: 409,
|
|
3137
|
+
headers: {
|
|
3138
|
+
[UNKNOWN_HEADER]: "true",
|
|
3139
|
+
[BUILD_HEADER]: config.buildId,
|
|
3140
|
+
"Cache-Control": "no-store"
|
|
3141
|
+
}
|
|
3142
|
+
}));
|
|
1036
3143
|
}
|
|
1037
|
-
|
|
3144
|
+
const scripted = address.data || address.live;
|
|
3145
|
+
const live = address.live;
|
|
3146
|
+
if (method !== "POST" && !declaredRead) {
|
|
1038
3147
|
const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
|
|
1039
3148
|
status: 405,
|
|
1040
3149
|
headers: {
|
|
1041
|
-
Allow: "POST"
|
|
3150
|
+
Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
|
|
1042
3151
|
}
|
|
1043
3152
|
});
|
|
1044
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3153
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1045
3154
|
}
|
|
1046
|
-
const
|
|
1047
|
-
|
|
1048
|
-
|
|
3155
|
+
const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
|
|
3156
|
+
const argsEncoding = url.searchParams.get("args");
|
|
3157
|
+
if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
|
|
3158
|
+
const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
|
|
3159
|
+
status: 413
|
|
3160
|
+
});
|
|
3161
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3162
|
+
}
|
|
3163
|
+
let argumentBytes = null;
|
|
3164
|
+
if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
|
|
3165
|
+
const raw = request.headers.get("content-length");
|
|
3166
|
+
const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
3167
|
+
if (declared > bodySizeLimit) {
|
|
3168
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
3169
|
+
status: 413
|
|
3170
|
+
});
|
|
3171
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3172
|
+
}
|
|
3173
|
+
let buffered;
|
|
3174
|
+
try {
|
|
3175
|
+
buffered = await bufferBodyWithin(request, bodySizeLimit);
|
|
3176
|
+
} catch {
|
|
3177
|
+
const response = new Response(DEV ? "Malformed server function arguments" : null, {
|
|
3178
|
+
status: 400
|
|
3179
|
+
});
|
|
3180
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3181
|
+
}
|
|
3182
|
+
if (buffered === null) {
|
|
3183
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
3184
|
+
status: 413
|
|
3185
|
+
});
|
|
3186
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3187
|
+
}
|
|
3188
|
+
request = withBufferedBody(request, buffered);
|
|
3189
|
+
argumentBytes = buffered;
|
|
3190
|
+
}
|
|
3191
|
+
let event;
|
|
3192
|
+
try {
|
|
3193
|
+
event = options.createEvent ? options.createEvent(request) : {
|
|
3194
|
+
request,
|
|
3195
|
+
locals: {}
|
|
3196
|
+
};
|
|
3197
|
+
const promised = nativePromise(event);
|
|
3198
|
+
if (promised) event = await promised;
|
|
3199
|
+
} catch (error) {
|
|
3200
|
+
const safe = sanitizeServerError(error);
|
|
3201
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
3202
|
+
const headers = new Headers();
|
|
3203
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
|
|
3204
|
+
const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
|
|
3205
|
+
status: 500
|
|
3206
|
+
});
|
|
3207
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3208
|
+
}
|
|
3209
|
+
const commitResponse = raw => {
|
|
3210
|
+
if ((method === "GET" || method === "HEAD") && (sharedCacheMayStore(departingHeader(raw, event, "Cache-Control")) || cdnMayStore(departingHeader(raw, event, "CDN-Cache-Control")))) {
|
|
3211
|
+
withholdTrace(event);
|
|
3212
|
+
}
|
|
3213
|
+
return commitEventResponse(raw, event);
|
|
3214
|
+
};
|
|
3215
|
+
const refuseCommitted = raw => {
|
|
3216
|
+
const response = commitResponse(raw);
|
|
3217
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1049
3218
|
};
|
|
1050
3219
|
const provide = options.provideEvent || provideEvent;
|
|
3220
|
+
const scope = run => provide(event, run);
|
|
3221
|
+
if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
|
|
1051
3222
|
const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
|
|
1052
3223
|
const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
|
|
1053
|
-
const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
|
|
3224
|
+
const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
|
|
1054
3225
|
const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
3226
|
+
let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
|
|
3227
|
+
if (handleNoJS === undefined && !scripted && isFormPost(request)) {
|
|
3228
|
+
const fetchMode = request.headers.get("Sec-Fetch-Mode");
|
|
3229
|
+
if (fetchMode === null || fetchMode === "navigate") {
|
|
3230
|
+
handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
|
|
3231
|
+
} else {
|
|
3232
|
+
const response = new Response(DEV ? "The bare server-function address answers form navigations with the " + "no-JS redirect convention. Scripted callers use the data address " + `(…/data/${functionId}) or send the ${BODY_FORMAT_HEADER} tag.` : null, {
|
|
3233
|
+
status: 400
|
|
3234
|
+
});
|
|
3235
|
+
return refuseCommitted(response);
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
3238
|
+
const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
|
|
3239
|
+
const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
|
|
3240
|
+
const hook = source === "true" ? flightHook : flightSources.get(source);
|
|
3241
|
+
return hook ? [[source, hook]] : [];
|
|
3242
|
+
}) : [];
|
|
3243
|
+
const collectsFlight = flightHooks.length > 0;
|
|
3244
|
+
let parsed;
|
|
3245
|
+
try {
|
|
3246
|
+
parsed = await parseArguments(request, url, scripted, codec, argumentBytes);
|
|
3247
|
+
} catch (error) {
|
|
3248
|
+
const named = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true ? error : refusedArgument(error);
|
|
3249
|
+
const response = new Response(DEV ? named ? named.message : "Malformed server function arguments" : null, {
|
|
3250
|
+
status: 400
|
|
3251
|
+
});
|
|
3252
|
+
return refuseCommitted(response);
|
|
3253
|
+
}
|
|
3254
|
+
const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
|
|
3255
|
+
if (parsed.length > maxArguments) {
|
|
3256
|
+
const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
|
|
3257
|
+
status: 400
|
|
3258
|
+
});
|
|
3259
|
+
return refuseCommitted(response);
|
|
3260
|
+
}
|
|
1058
3261
|
const flightContext = {
|
|
1059
3262
|
id: functionId,
|
|
1060
3263
|
args: parsed,
|
|
1061
|
-
instance,
|
|
1062
3264
|
request,
|
|
1063
3265
|
collectsFlight,
|
|
1064
3266
|
codec,
|
|
@@ -1067,19 +3269,30 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1067
3269
|
const headers = new Headers();
|
|
1068
3270
|
const dispatch = async () => {
|
|
1069
3271
|
try {
|
|
1070
|
-
|
|
3272
|
+
const invokeOnce = async () => {
|
|
3273
|
+
const shared = !!live && BROADCASTS.has(functionId);
|
|
1071
3274
|
INVOCATIONS.set(event, {
|
|
1072
|
-
id: functionId
|
|
3275
|
+
id: functionId,
|
|
3276
|
+
live: !!live,
|
|
3277
|
+
broadcast: shared || undefined,
|
|
3278
|
+
shareKey: shared ? encodedArguments(request, argsEncoding, argumentBytes) : undefined
|
|
1073
3279
|
});
|
|
1074
3280
|
const run = () => serverFunction(...parsed);
|
|
1075
|
-
return
|
|
3281
|
+
return observeInvocation({
|
|
3282
|
+
id: functionId,
|
|
3283
|
+
direct: false,
|
|
3284
|
+
event,
|
|
3285
|
+
request,
|
|
3286
|
+
args: parsed
|
|
3287
|
+
}, () => wrapInvocation ? wrapInvocation(run, {
|
|
1076
3288
|
id: functionId,
|
|
1077
3289
|
args: parsed,
|
|
1078
3290
|
event,
|
|
1079
3291
|
request,
|
|
1080
3292
|
direct: false
|
|
1081
|
-
}) : run();
|
|
1082
|
-
}
|
|
3293
|
+
}) : run());
|
|
3294
|
+
};
|
|
3295
|
+
let result = await provideEventOnce(provide, event, invokeOnce);
|
|
1083
3296
|
if (transformResult) {
|
|
1084
3297
|
result = await transformResult(event, result, flightContext);
|
|
1085
3298
|
}
|
|
@@ -1090,25 +3303,29 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1090
3303
|
response,
|
|
1091
3304
|
value
|
|
1092
3305
|
} = result;
|
|
1093
|
-
if (!
|
|
3306
|
+
if (!scripted && !handleNoJS && response && response.body && isJSONSafe(value)) {
|
|
1094
3307
|
return response;
|
|
1095
3308
|
}
|
|
1096
3309
|
if (response && response.headers) {
|
|
1097
3310
|
mergeResponseHeaders(headers, response.headers);
|
|
1098
3311
|
}
|
|
1099
|
-
if (response && response.status && (
|
|
3312
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
1100
3313
|
status = response.status;
|
|
3314
|
+
} else if (response && response.status) {
|
|
3315
|
+
maskRedirect(headers, response, request.url);
|
|
1101
3316
|
}
|
|
1102
3317
|
metadata = response;
|
|
1103
3318
|
result = value;
|
|
1104
3319
|
} else if (result instanceof Response) {
|
|
1105
3320
|
if (result.headers && result.headers.has("X-Content-Raw")) return result;
|
|
1106
|
-
if (
|
|
3321
|
+
if (scripted) {
|
|
1107
3322
|
if (result.headers) {
|
|
1108
3323
|
mergeResponseHeaders(headers, result.headers);
|
|
1109
3324
|
}
|
|
1110
|
-
if (result.status && (result.status
|
|
3325
|
+
if (result.status && !validRedirectStatuses.has(result.status)) {
|
|
1111
3326
|
status = result.status;
|
|
3327
|
+
} else if (result.status) {
|
|
3328
|
+
maskRedirect(headers, result, request.url);
|
|
1112
3329
|
}
|
|
1113
3330
|
metadata = result;
|
|
1114
3331
|
if (result.body == null) {
|
|
@@ -1117,7 +3334,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1117
3334
|
}
|
|
1118
3335
|
}
|
|
1119
3336
|
if (collectsFlight) {
|
|
1120
|
-
result = await foldFlightData(
|
|
3337
|
+
result = await foldFlightData(flightHooks, event, headers, {
|
|
1121
3338
|
id: functionId,
|
|
1122
3339
|
value: result,
|
|
1123
3340
|
response: metadata,
|
|
@@ -1126,20 +3343,44 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1126
3343
|
}, flightContext);
|
|
1127
3344
|
if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
|
|
1128
3345
|
}
|
|
1129
|
-
if (!
|
|
1130
|
-
if (handleNoJS)
|
|
3346
|
+
if (!scripted) {
|
|
3347
|
+
if (handleNoJS) {
|
|
3348
|
+
return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
|
|
3349
|
+
}
|
|
1131
3350
|
if (result instanceof Response) return result;
|
|
1132
|
-
return encodeResult(result, headers,
|
|
3351
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
3352
|
+
}
|
|
3353
|
+
if (status === 304) warnScripted304(functionId);
|
|
3354
|
+
if (live) {
|
|
3355
|
+
const invocation = INVOCATIONS.get(event);
|
|
3356
|
+
return encodeLiveResult(result, headers, status, codec, request, scope, invocation && invocation.broadcast && invocation.shareKey !== undefined ? invocation.id + "\0" + invocation.shareKey : undefined);
|
|
1133
3357
|
}
|
|
1134
|
-
return encodeResult(result, headers, status, codec, request.signal);
|
|
3358
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
1135
3359
|
} catch (x) {
|
|
1136
|
-
|
|
1137
|
-
|
|
3360
|
+
const respondThrown = value => {
|
|
3361
|
+
const safe = wireServerFunctionError(value, "thrown", event);
|
|
3362
|
+
if (!scripted) {
|
|
3363
|
+
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
3364
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
3365
|
+
return new Response(DEV ? message : null, {
|
|
3366
|
+
status: 500
|
|
3367
|
+
});
|
|
3368
|
+
}
|
|
3369
|
+
const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
|
|
3370
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
|
|
3371
|
+
return encodeResult(safe, headers, 500, codec, request.signal, scope);
|
|
3372
|
+
};
|
|
3373
|
+
if (transformResult) {
|
|
3374
|
+
try {
|
|
1138
3375
|
x = await transformResult(event, x, {
|
|
1139
3376
|
...flightContext,
|
|
1140
3377
|
thrown: true
|
|
1141
3378
|
});
|
|
3379
|
+
} catch (hookError) {
|
|
3380
|
+
return respondThrown(hookError);
|
|
1142
3381
|
}
|
|
3382
|
+
}
|
|
3383
|
+
if (x instanceof Response || isResponseEnvelope(x)) {
|
|
1143
3384
|
let status = 200;
|
|
1144
3385
|
let metadata;
|
|
1145
3386
|
if (isResponseEnvelope(x)) {
|
|
@@ -1150,8 +3391,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1150
3391
|
if (response && response.headers) {
|
|
1151
3392
|
mergeResponseHeaders(headers, response.headers);
|
|
1152
3393
|
}
|
|
1153
|
-
if (response && response.status && (!
|
|
3394
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
1154
3395
|
status = response.status;
|
|
3396
|
+
} else if (response && response.status) {
|
|
3397
|
+
maskRedirect(headers, response, request.url);
|
|
1155
3398
|
}
|
|
1156
3399
|
metadata = response;
|
|
1157
3400
|
x = value;
|
|
@@ -1159,8 +3402,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1159
3402
|
if (x.headers) {
|
|
1160
3403
|
mergeResponseHeaders(headers, x.headers);
|
|
1161
3404
|
}
|
|
1162
|
-
if (x.status && (!
|
|
3405
|
+
if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
|
|
1163
3406
|
status = x.status;
|
|
3407
|
+
} else if (x.status) {
|
|
3408
|
+
maskRedirect(headers, x, request.url);
|
|
1164
3409
|
}
|
|
1165
3410
|
metadata = x;
|
|
1166
3411
|
if (x.body == null) {
|
|
@@ -1168,7 +3413,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1168
3413
|
}
|
|
1169
3414
|
}
|
|
1170
3415
|
if (collectsFlight) {
|
|
1171
|
-
x = await foldFlightData(
|
|
3416
|
+
x = await foldFlightData(flightHooks, event, headers, {
|
|
1172
3417
|
id: functionId,
|
|
1173
3418
|
value: x,
|
|
1174
3419
|
response: metadata,
|
|
@@ -1176,32 +3421,111 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1176
3421
|
thrown: true
|
|
1177
3422
|
}, flightContext);
|
|
1178
3423
|
if (x instanceof Response && x.headers.has("X-Content-Raw")) {
|
|
3424
|
+
x = ownResponse(x);
|
|
1179
3425
|
x.headers.set(ERROR_HEADER, "true");
|
|
1180
3426
|
return x;
|
|
1181
3427
|
}
|
|
1182
3428
|
}
|
|
1183
3429
|
headers.set(ERROR_HEADER, "true");
|
|
1184
|
-
if (!
|
|
3430
|
+
if (!scripted) {
|
|
1185
3431
|
if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
|
|
1186
3432
|
if (x instanceof Response) return x;
|
|
1187
3433
|
}
|
|
1188
|
-
|
|
3434
|
+
if (scripted && status === 304) warnScripted304(functionId);
|
|
3435
|
+
return encodeResult(x, headers, status, codec, request.signal, scope);
|
|
1189
3436
|
}
|
|
1190
|
-
|
|
1191
|
-
if (!instance) {
|
|
1192
|
-
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
1193
|
-
const message = safe instanceof Error ? safe.message : String(safe);
|
|
1194
|
-
return new Response(DEV ? message : null, {
|
|
1195
|
-
status: 500
|
|
1196
|
-
});
|
|
1197
|
-
}
|
|
1198
|
-
const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
|
|
1199
|
-
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
|
|
1200
|
-
return encodeResult(safe, headers, 200, codec, request.signal);
|
|
3437
|
+
return respondThrown(x);
|
|
1201
3438
|
}
|
|
1202
3439
|
};
|
|
1203
|
-
const response =
|
|
1204
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3440
|
+
const response = commitResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())));
|
|
3441
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3442
|
+
}
|
|
3443
|
+
function departingHeader(response, event, name) {
|
|
3444
|
+
const own = response.headers.get(name);
|
|
3445
|
+
if (own !== null) return own;
|
|
3446
|
+
const stub = event.response;
|
|
3447
|
+
return stub && stub.headers && !stub.committed ? stub.headers.get(name) : null;
|
|
3448
|
+
}
|
|
3449
|
+
function cdnMayStore(cdnCacheControl) {
|
|
3450
|
+
return cdnCacheControl !== null && !forbidsStoring(cdnCacheControl);
|
|
3451
|
+
}
|
|
3452
|
+
function sharedCacheMayStore(cacheControl) {
|
|
3453
|
+
let shared = false;
|
|
3454
|
+
return !!cacheControl && !eachDirective(cacheControl, name => {
|
|
3455
|
+
if (name === "public" || name === "s-maxage") shared = true;
|
|
3456
|
+
}) && shared;
|
|
3457
|
+
}
|
|
3458
|
+
function forbidsStoring(value) {
|
|
3459
|
+
return eachDirective(value, () => {});
|
|
3460
|
+
}
|
|
3461
|
+
function eachDirective(value, visit) {
|
|
3462
|
+
let start = 0;
|
|
3463
|
+
let quoted = false;
|
|
3464
|
+
for (let i = 0; i <= value.length; i++) {
|
|
3465
|
+
const c = value[i];
|
|
3466
|
+
if (quoted) {
|
|
3467
|
+
if (c === "\\") i++;else if (c === '"') quoted = false;
|
|
3468
|
+
continue;
|
|
3469
|
+
}
|
|
3470
|
+
if (c === '"') {
|
|
3471
|
+
quoted = true;
|
|
3472
|
+
continue;
|
|
3473
|
+
}
|
|
3474
|
+
if (c !== "," && i < value.length) continue;
|
|
3475
|
+
const directive = value.slice(start, i);
|
|
3476
|
+
start = i + 1;
|
|
3477
|
+
const eq = directive.indexOf("=");
|
|
3478
|
+
const name = (eq === -1 ? directive : directive.slice(0, eq)).trim().toLowerCase();
|
|
3479
|
+
if (name === "no-store" || name === "private" && eq === -1) return true;
|
|
3480
|
+
visit(name);
|
|
3481
|
+
}
|
|
3482
|
+
return false;
|
|
3483
|
+
}
|
|
3484
|
+
function withholdTrace(event) {
|
|
3485
|
+
if (event.response && event.response.committed) return;
|
|
3486
|
+
traceForEvent(event).emit = false;
|
|
3487
|
+
}
|
|
3488
|
+
function ownResponse(response) {
|
|
3489
|
+
try {
|
|
3490
|
+
return new Response(response.body, response);
|
|
3491
|
+
} catch {
|
|
3492
|
+
return response;
|
|
3493
|
+
}
|
|
3494
|
+
}
|
|
3495
|
+
function finalizeTransportResponse(response, method) {
|
|
3496
|
+
const stripBody = method === "HEAD" && response.body !== null;
|
|
3497
|
+
const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
|
|
3498
|
+
const defaultsSniff = !response.headers.has("X-Content-Type-Options");
|
|
3499
|
+
if (stripBody || defaultsCache || defaultsSniff) {
|
|
3500
|
+
try {
|
|
3501
|
+
if (defaultsCache) {
|
|
3502
|
+
response.headers.set("Cache-Control", "no-store");
|
|
3503
|
+
}
|
|
3504
|
+
if (defaultsSniff) {
|
|
3505
|
+
response.headers.set("X-Content-Type-Options", "nosniff");
|
|
3506
|
+
}
|
|
3507
|
+
if (!stripBody) return response;
|
|
3508
|
+
response.body.cancel().catch(() => {});
|
|
3509
|
+
return new Response(null, {
|
|
3510
|
+
status: response.status,
|
|
3511
|
+
statusText: response.statusText,
|
|
3512
|
+
headers: response.headers
|
|
3513
|
+
});
|
|
3514
|
+
} catch {
|
|
3515
|
+
const headers = new Headers(response.headers);
|
|
3516
|
+
if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
|
|
3517
|
+
if (defaultsSniff && !headers.has("X-Content-Type-Options")) {
|
|
3518
|
+
headers.set("X-Content-Type-Options", "nosniff");
|
|
3519
|
+
}
|
|
3520
|
+
if (stripBody) response.body.cancel().catch(() => {});
|
|
3521
|
+
return new Response(stripBody ? null : response.body, {
|
|
3522
|
+
status: response.status,
|
|
3523
|
+
statusText: response.statusText,
|
|
3524
|
+
headers
|
|
3525
|
+
});
|
|
3526
|
+
}
|
|
3527
|
+
}
|
|
3528
|
+
return response;
|
|
1205
3529
|
}
|
|
1206
3530
|
|
|
1207
|
-
export { ERROR_HEADER, FLASH_COOKIE,
|
|
3531
|
+
export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, broadcast, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };
|