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