@solidjs/web 2.0.0-rc.6 → 2.0.0-rc.8

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.
Files changed (82) hide show
  1. package/dist/{server.cjs → server.dev.js} +274 -272
  2. package/dist/server.js +119 -36
  3. package/dist/{dev.js → web.dev.js} +131 -399
  4. package/dist/web.js +78 -388
  5. package/dist/{web.cjs → web.observe.js} +174 -622
  6. package/frames/dist/client.dev.js +11 -3
  7. package/frames/dist/client.js +11 -3
  8. package/frames/dist/{server.cjs → server.dev.js} +375 -125
  9. package/frames/dist/server.js +253 -32
  10. package/frames/package.json +7 -15
  11. package/package.json +88 -251
  12. package/serialization/decode/package.json +3 -9
  13. package/serialization/dist/decode.js +18 -4
  14. package/serialization/dist/serialization.js +18 -4
  15. package/serialization/package.json +3 -9
  16. package/serialization/types/serializer-decode.d.ts +49 -2
  17. package/server-functions/dist/client.js +13 -14
  18. package/server-functions/dist/server.dev.js +359 -85
  19. package/server-functions/dist/server.js +352 -86
  20. package/server-functions/package.json +6 -24
  21. package/server-functions/rich-args/package.json +3 -9
  22. package/storage/package.json +3 -9
  23. package/types/client.d.ts +17 -3
  24. package/types/frames/frame-client.d.ts +1 -1
  25. package/types/frames/serializer-decode.d.ts +49 -2
  26. package/types/head.d.ts +3 -0
  27. package/types/index.d.ts +18 -7
  28. package/types/index.server.d.ts +31 -9
  29. package/types/render.d.ts +3 -1
  30. package/types/serializer-decode.d.ts +49 -2
  31. package/types/server-functions/flash.d.ts +12 -3
  32. package/types/server-functions/server.d.ts +50 -3
  33. package/types/server-mock.d.ts +43 -7
  34. package/types/server.d.ts +48 -6
  35. package/dist/dev.cjs +0 -2590
  36. package/frames/dist/client.cjs +0 -2035
  37. package/frames/dist/client.dev.cjs +0 -2055
  38. package/serialization/dist/decode.cjs +0 -141
  39. package/serialization/dist/serialization.cjs +0 -261
  40. package/serialization/types-cjs/index.d.cts +0 -101
  41. package/serialization/types-cjs/package.json +0 -3
  42. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  43. package/serialization/types-cjs/serializer.d.cts +0 -101
  44. package/server-functions/dist/client.cjs +0 -1070
  45. package/server-functions/dist/rich-args.cjs +0 -11
  46. package/server-functions/dist/server.cjs +0 -2133
  47. package/server-functions/dist/server.dev.cjs +0 -2153
  48. package/storage/dist/storage.cjs +0 -12
  49. package/storage/types-cjs/index.d.cts +0 -28
  50. package/storage/types-cjs/package.json +0 -3
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/client.d.cts +0 -200
  53. package/types-cjs/constants.d.cts +0 -20
  54. package/types-cjs/cookies.d.cts +0 -41
  55. package/types-cjs/frames/client.d.cts +0 -36
  56. package/types-cjs/frames/frame-client.d.cts +0 -370
  57. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  58. package/types-cjs/frames/frame-sink.d.cts +0 -92
  59. package/types-cjs/frames/frame-transport.d.cts +0 -189
  60. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  61. package/types-cjs/frames/serializer.d.cts +0 -101
  62. package/types-cjs/frames/server.d.cts +0 -52
  63. package/types-cjs/head.d.cts +0 -16
  64. package/types-cjs/index.d.cts +0 -180
  65. package/types-cjs/index.server.d.cts +0 -125
  66. package/types-cjs/jsx-properties.d.cts +0 -93
  67. package/types-cjs/jsx.d.cts +0 -4146
  68. package/types-cjs/package.json +0 -3
  69. package/types-cjs/patch-driver.d.cts +0 -3
  70. package/types-cjs/reconcile.d.cts +0 -1
  71. package/types-cjs/render.d.cts +0 -4
  72. package/types-cjs/response.d.cts +0 -81
  73. package/types-cjs/serializer-decode.d.cts +0 -172
  74. package/types-cjs/serializer.d.cts +0 -101
  75. package/types-cjs/server-functions/client.d.cts +0 -184
  76. package/types-cjs/server-functions/flash.d.cts +0 -27
  77. package/types-cjs/server-functions/registry.d.cts +0 -100
  78. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  79. package/types-cjs/server-functions/server.d.cts +0 -522
  80. package/types-cjs/server-functions/shared.d.cts +0 -283
  81. package/types-cjs/server-mock.d.cts +0 -301
  82. package/types-cjs/server.d.cts +0 -366
@@ -1,2153 +0,0 @@
1
- 'use strict';
2
-
3
- var solidJs = require('solid-js');
4
-
5
- const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
6
- function isHttpNavigationTarget(target) {
7
- try {
8
- const protocol = new URL(target, "http://base.invalid").protocol;
9
- return protocol === "http:" || protocol === "https:";
10
- } catch {
11
- return false;
12
- }
13
- }
14
-
15
- const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
16
- function isResponseEnvelope(value) {
17
- return !!(value && typeof value === "object" && value[ENVELOPE]);
18
- }
19
- const SAFE_ERROR = Symbol.for("solid.SafeError");
20
- function isSafeError(value) {
21
- return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
22
- }
23
- const REVALIDATE_HEADER = "X-Revalidate";
24
- const RESPONSE_HEADER_VALUE_LIMIT = 4096;
25
- const NULL_BODY_STATUSES = new Set([204, 205, 304]);
26
-
27
- const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
28
- function getServerFunctionMetadata(fn) {
29
- if (typeof fn !== "function") return undefined;
30
- return fn[SERVER_FUNCTION_METADATA] || undefined;
31
- }
32
- function isServerFunction(fn) {
33
- return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
34
- }
35
- function withMeta(fn, meta) {
36
- const metadata = getServerFunctionMetadata(fn);
37
- if (!metadata) {
38
- throw new Error("withMeta expects a server function reference");
39
- }
40
- Object.assign(metadata, meta);
41
- return fn;
42
- }
43
- const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
44
- const INVOKE_OPTION_REDIRECTS = {
45
- 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.",
46
- method: "The method is declaration-scoped: declare the function with GET(fn).",
47
- body: "The arguments are the body: pass them in the args array.",
48
- timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
49
- };
50
- function invoke(fn, options, ...args) {
51
- const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
52
- if (!channel) {
53
- 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.");
54
- }
55
- if (options === null || typeof options !== "object") {
56
- throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
57
- }
58
- const picked = {};
59
- for (const key in options) {
60
- if (key !== "signal" && key !== "keepalive" && key !== "priority") {
61
- 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."));
62
- }
63
- }
64
- if (options.signal !== undefined) picked.signal = options.signal;
65
- if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
66
- if (options.priority !== undefined) picked.priority = options.priority;
67
- return channel(args, picked);
68
- }
69
- const LIVE_SOURCE = Symbol.for("solid.LiveSource");
70
- const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
71
- function provideServerFunctionRPC(rpc) {
72
- globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
73
- }
74
-
75
- function parseCookieHeader(header) {
76
- const cookies = {};
77
- if (!header) return cookies;
78
- for (const part of header.split(";")) {
79
- const eq = part.indexOf("=");
80
- if (eq < 0) continue;
81
- const name = decodeSafe(part.slice(0, eq).trim());
82
- let value = part.slice(eq + 1).trim();
83
- if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
84
- value = value.slice(1, -1);
85
- }
86
- cookies[name] = decodeSafe(value);
87
- }
88
- return cookies;
89
- }
90
- function decodeSafe(text) {
91
- try {
92
- return decodeURIComponent(text);
93
- } catch {
94
- return text;
95
- }
96
- }
97
- function serializeCookie(name, value, options = {}) {
98
- assertServableCookie(name, options);
99
- let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
100
- cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
101
- if (options.domain) cookie += `; Domain=${options.domain}`;
102
- if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
103
- if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
104
- if (options.httpOnly) cookie += "; HttpOnly";
105
- if (options.secure) cookie += "; Secure";
106
- if (options.partitioned) cookie += "; Partitioned";
107
- if (options.sameSite) {
108
- const sameSite = options.sameSite.toLowerCase();
109
- cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
110
- }
111
- return cookie;
112
- }
113
- function assertServableCookie(name, options) {
114
- const reject = reason => {
115
- throw new Error(`serializeCookie: every browser silently rejects this cookie — ${reason}. ` + `It would never come back on a request, with no error anywhere.`);
116
- };
117
- const lower = name.toLowerCase();
118
- if (lower.startsWith("__host-")) {
119
- if (!options.secure) reject(`the __Host- prefix on \`${name}\` requires \`secure: true\``);
120
- 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`);
121
- if (options.domain) reject(`the __Host- prefix on \`${name}\` forbids \`Domain\` (got \`${options.domain}\`)`);
122
- } else if (lower.startsWith("__secure-") && !options.secure) {
123
- reject(`the __Secure- prefix on \`${name}\` requires \`secure: true\``);
124
- }
125
- if (options.sameSite && options.sameSite.toLowerCase() === "none" && !options.secure) {
126
- reject("`SameSite=None` requires `secure: true`");
127
- }
128
- if (options.partitioned && !options.secure) {
129
- reject("`Partitioned` requires `secure: true`");
130
- }
131
- }
132
- const FLASH_COOKIE = "flash";
133
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
134
- function hasFlashCookie(cookieHeader) {
135
- return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
136
- }
137
- function clearFlashCookie() {
138
- return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
139
- }
140
-
141
- const codecConfig = {
142
- codec: undefined
143
- };
144
- function configureServerFunctionsCodec(codec) {
145
- codecConfig.codec = codec;
146
- }
147
- function getServerFunctionsCodec() {
148
- return codecConfig.codec;
149
- }
150
- const UNNAMED_FLIGHT_SOURCE = "true";
151
- const flightConfig = {
152
- consumers: new Map()
153
- };
154
- function assertFlightSource(source) {
155
- if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
156
- 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).`);
157
- }
158
- }
159
- function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
160
- const named = typeof sourceOrConsumer === "string";
161
- if (named) assertFlightSource(sourceOrConsumer);
162
- const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
163
- const consumer = named ? maybeConsumer : sourceOrConsumer;
164
- flightConfig.consumers.set(source, consumer);
165
- return () => {
166
- if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
167
- };
168
- }
169
- function serverFunctionAddress(endpoint, id) {
170
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
171
- return `${mount}/${encodeURIComponent(id)}`;
172
- }
173
- function parseServerFunctionAddress(pathname, endpoint) {
174
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
175
- if (!pathname.startsWith(mount)) return null;
176
- const rest = pathname.slice(mount.length);
177
- if (!rest.startsWith("/")) return null;
178
- let segment = rest.slice(1);
179
- let data = false;
180
- if (segment.startsWith("data/")) {
181
- segment = segment.slice(5);
182
- data = true;
183
- }
184
- if (!segment || segment.includes("/")) return null;
185
- try {
186
- return {
187
- id: decodeURIComponent(segment),
188
- data
189
- };
190
- } catch {
191
- return null;
192
- }
193
- }
194
- const ERROR_HEADER = "X-Server-Function-Error";
195
- const ERROR_HEADER_MARKER = "=?1?";
196
- const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
197
- function encodeErrorHeaderValue(value) {
198
- let stripped = String(value).replace(/[\r\n]+/g, "");
199
- if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
200
- return stripped;
201
- }
202
- if (typeof stripped.toWellFormed === "function") {
203
- stripped = stripped.toWellFormed();
204
- } else {
205
- stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
206
- }
207
- return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
208
- }
209
- function decodeErrorHeaderValue(value) {
210
- if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
211
- return value;
212
- }
213
- try {
214
- return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
215
- } catch {
216
- return value;
217
- }
218
- }
219
- const INSTANCE_HEADER = "X-Server-Function-Instance";
220
- const BODY_FORMAT_HEADER = "X-Server-Function-Format";
221
- const UNKNOWN_HEADER = "X-Server-Function-Unknown";
222
- const REDIRECT_HEADER = "X-Server-Function-Redirect";
223
- function decodeRedirectHeaderValue(value) {
224
- if (typeof value !== "string") return undefined;
225
- const at = value.indexOf(" ");
226
- if (at < 0) return undefined;
227
- const status = Number(value.slice(0, at));
228
- const url = value.slice(at + 1);
229
- if (!Number.isInteger(status) || !url) return undefined;
230
- if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
231
- let parsed;
232
- try {
233
- parsed = new URL(url);
234
- } catch {
235
- return undefined;
236
- }
237
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
238
- return {
239
- status,
240
- url
241
- };
242
- }
243
- const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
244
- const FILE_FORM_KEY = "__server_function_file__";
245
- const BodyFormat = {
246
- Serialized: "0",
247
- String: "1",
248
- FormData: "2",
249
- URLSearchParams: "3",
250
- Blob: "4",
251
- File: "5",
252
- ArrayBuffer: "6",
253
- Uint8Array: "7",
254
- Json: "8",
255
- Void: "9"
256
- };
257
- const JSON_SAFE_DEPTH_LIMIT = 4096;
258
- const EXIT = {};
259
- function isJSONSafe(value) {
260
- const stack = [value];
261
- const ancestors = new Set();
262
- while (stack.length) {
263
- const v = stack.pop();
264
- if (v === EXIT) {
265
- ancestors.delete(stack.pop());
266
- continue;
267
- }
268
- if (v === null) continue;
269
- const t = typeof v;
270
- if (t === "string" || t === "boolean") continue;
271
- if (t === "number") {
272
- if (!Number.isFinite(v)) return false;
273
- continue;
274
- }
275
- if (t !== "object") return false;
276
- if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
277
- ancestors.add(v);
278
- stack.push(v, EXIT);
279
- if (Array.isArray(v)) {
280
- for (let i = 0; i < v.length; i++) stack.push(v[i]);
281
- } else {
282
- const proto = Object.getPrototypeOf(v);
283
- if (proto !== Object.prototype && proto !== null) return false;
284
- if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
285
- for (const k in v) {
286
- const descriptor = Object.getOwnPropertyDescriptor(v, k);
287
- if (descriptor === undefined || !("value" in descriptor)) return false;
288
- stack.push(descriptor.value);
289
- }
290
- }
291
- }
292
- return true;
293
- }
294
- function getHeadersAndBody(body) {
295
- switch (true) {
296
- case typeof body === "string":
297
- return {
298
- headers: {
299
- "Content-Type": "text/plain",
300
- [BODY_FORMAT_HEADER]: BodyFormat.String
301
- },
302
- body
303
- };
304
- case body instanceof FormData:
305
- return {
306
- headers: {
307
- [BODY_FORMAT_HEADER]: BodyFormat.FormData
308
- },
309
- body
310
- };
311
- case body instanceof URLSearchParams:
312
- return {
313
- headers: {
314
- "Content-Type": "application/x-www-form-urlencoded",
315
- [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
316
- },
317
- body
318
- };
319
- case typeof File !== "undefined" && body instanceof File:
320
- {
321
- const formData = new FormData();
322
- formData.append(FILE_FORM_KEY, body, body.name);
323
- return {
324
- headers: {
325
- [BODY_FORMAT_HEADER]: BodyFormat.File
326
- },
327
- body: formData
328
- };
329
- }
330
- case body instanceof Blob:
331
- return {
332
- headers: {
333
- [BODY_FORMAT_HEADER]: BodyFormat.Blob
334
- },
335
- body
336
- };
337
- case body instanceof ArrayBuffer:
338
- return {
339
- headers: {
340
- [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
341
- },
342
- body
343
- };
344
- case body instanceof Uint8Array:
345
- return {
346
- headers: {
347
- [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
348
- },
349
- body: new Uint8Array(body)
350
- };
351
- default:
352
- return undefined;
353
- }
354
- }
355
- async function extractBody(source, codecOptions) {
356
- const contentType = source.headers.get("content-type");
357
- const format = source.headers.get(BODY_FORMAT_HEADER);
358
- const clone = source.clone();
359
- switch (true) {
360
- case format === BodyFormat.Serialized:
361
- return await deserializeStream(clone, codecOptions);
362
- case format === BodyFormat.Json:
363
- return JSON.parse(await clone.text());
364
- case format === BodyFormat.String:
365
- return await clone.text();
366
- case format === BodyFormat.File:
367
- {
368
- const formData = await clone.formData();
369
- return formData.get(FILE_FORM_KEY);
370
- }
371
- case format === BodyFormat.FormData:
372
- case contentType && contentType.startsWith("multipart/form-data"):
373
- return await clone.formData();
374
- case format === BodyFormat.URLSearchParams:
375
- case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
376
- return new URLSearchParams(await clone.text());
377
- case format === BodyFormat.Blob:
378
- return await clone.blob();
379
- case format === BodyFormat.ArrayBuffer:
380
- return await clone.arrayBuffer();
381
- case format === BodyFormat.Uint8Array:
382
- return new Uint8Array(await clone.arrayBuffer());
383
- }
384
- return undefined;
385
- }
386
- function createChunk(data) {
387
- const encoder = new TextEncoder();
388
- const encodeData = encoder.encode(data);
389
- const bytes = encodeData.length;
390
- const chunk = new Uint8Array(12 + bytes);
391
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
392
- chunk.set(encodeData, 12);
393
- return chunk;
394
- }
395
- class ChunkReader {
396
- constructor(stream) {
397
- this.reader = stream.getReader();
398
- this.store = new Uint8Array(0);
399
- this.buffer = this.store;
400
- this.done = false;
401
- }
402
- async readChunk() {
403
- const chunk = await this.reader.read();
404
- if (chunk.done) {
405
- this.done = true;
406
- return;
407
- }
408
- const incoming = chunk.value;
409
- const store = this.store;
410
- const start = this.buffer.byteOffset;
411
- const end = start + this.buffer.length;
412
- const needed = this.buffer.length + incoming.length;
413
- if (end + incoming.length <= store.length) {
414
- store.set(incoming, end);
415
- this.buffer = store.subarray(start, end + incoming.length);
416
- } else if (needed <= store.length) {
417
- store.copyWithin(0, start, end);
418
- store.set(incoming, this.buffer.length);
419
- this.buffer = store.subarray(0, needed);
420
- } else {
421
- const grown = new Uint8Array(Math.max(needed, store.length * 2));
422
- grown.set(this.buffer);
423
- grown.set(incoming, this.buffer.length);
424
- this.store = grown;
425
- this.buffer = grown.subarray(0, needed);
426
- }
427
- }
428
- async next() {
429
- while (this.buffer.length < 12) {
430
- if (this.done) {
431
- if (this.buffer.length === 0) return {
432
- done: true,
433
- value: undefined
434
- };
435
- throw new Error("Malformed server function stream.");
436
- }
437
- await this.readChunk();
438
- }
439
- const decoder = new TextDecoder();
440
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
441
- if (Number.isNaN(bytes)) {
442
- throw new Error("Malformed server function stream.");
443
- }
444
- while (bytes > this.buffer.length - 12) {
445
- if (this.done) {
446
- throw new Error("Malformed server function stream.");
447
- }
448
- await this.readChunk();
449
- }
450
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
451
- this.buffer = this.buffer.subarray(12 + bytes);
452
- return {
453
- done: false,
454
- value: partial
455
- };
456
- }
457
- async drain(interpret) {
458
- while (true) {
459
- const result = await this.next();
460
- if (result.done) {
461
- break;
462
- }
463
- interpret(result.value);
464
- }
465
- }
466
- }
467
- const ERROR_TRAILER_PREFIX = "!";
468
- function encodeErrorTrailer(error) {
469
- const shaped = error instanceof Error ? error : new Error(String(error));
470
- return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
471
- name: shaped.name,
472
- message: shaped.message
473
- } : {
474
- message: shaped.message
475
- });
476
- }
477
- function errorFromTrailer(payload) {
478
- let shape;
479
- try {
480
- shape = JSON.parse(payload.slice(1));
481
- } catch {
482
- shape = null;
483
- }
484
- const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
485
- if (shape && typeof shape.name === "string") error.name = shape.name;
486
- return error;
487
- }
488
- async function deserializeStream(source, codecOptions) {
489
- if (!source.body) {
490
- throw new Error("missing body");
491
- }
492
- const reader = new ChunkReader(source.body);
493
- const result = await reader.next();
494
- if (!result.done) {
495
- if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
496
- throw errorFromTrailer(result.value);
497
- }
498
- const {
499
- createJSONDeserializer
500
- } = await import('@solidjs/web/serialization/decode');
501
- const deserializeChunk = createJSONDeserializer(codecOptions);
502
- function interpretChunk(chunk) {
503
- if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
504
- throw errorFromTrailer(chunk);
505
- }
506
- return deserializeChunk(JSON.parse(chunk));
507
- }
508
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
509
- return interpretChunk(result.value);
510
- }
511
- return undefined;
512
- }
513
- async function deserializeString(text, codecOptions) {
514
- return await deserializeStream(new Response(text), codecOptions);
515
- }
516
- async function decodeResponse(response, codecOptions) {
517
- if (!response.body) return undefined;
518
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
519
- }
520
- async function decodeResponsePayload(response, codecOptions) {
521
- const decoded = await decodeResponse(response, codecOptions);
522
- if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
523
- return {
524
- value: decoded.value,
525
- flightData: decoded.data
526
- };
527
- }
528
- return {
529
- value: decoded
530
- };
531
- }
532
-
533
- typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
534
- const RequestContext = Symbol.for("solid.RequestContext");
535
- function getRequestEvent() {
536
- return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || solidJs.sharedConfig.context && solidJs.sharedConfig.context.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.") : undefined;
537
- }
538
- function reportLostHeaderWrite(method, name) {
539
- 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).";
540
- throw new Error(message);
541
- }
542
- function commitResponseStub(stub, {
543
- allowLateLocation = false
544
- } = {}) {
545
- if (!stub || stub.committed) return stub;
546
- stub.committed = true;
547
- const headers = stub.headers;
548
- if (!headers || typeof headers.set !== "function") return stub;
549
- for (const method of ["set", "append", "delete"]) {
550
- const original = headers[method].bind(headers);
551
- headers[method] = function (name, ...rest) {
552
- if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
553
- return original(name, ...rest);
554
- }
555
- reportLostHeaderWrite(method, name);
556
- };
557
- }
558
- return stub;
559
- }
560
- function copyInitHeaders(init) {
561
- if (!init || !init.getSetCookie) return new Headers(init);
562
- const headers = new Headers();
563
- init.forEach((value, key) => {
564
- if (key !== "set-cookie") headers.append(key, value);
565
- });
566
- for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
567
- return headers;
568
- }
569
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
570
- ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
571
- function fillsStubGap(key, headers, response) {
572
- if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
573
- if (response.body === null && (key === "content-type" || key === "content-length")) return false;
574
- return !headers.has(key);
575
- }
576
- function commitEventResponse(response, event = getRequestEvent()) {
577
- const stub = event && event.response;
578
- if (!stub || !stub.headers || stub.committed) return response;
579
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
580
- commitResponseStub(stub);
581
- let hasGaps = false;
582
- stub.headers.forEach((value, key) => {
583
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
584
- });
585
- if (!cookies.length && !hasGaps) return response;
586
- const headers = copyInitHeaders(response.headers);
587
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
588
- stub.headers.forEach((value, key) => {
589
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
590
- });
591
- return new Response(response.body, {
592
- status: response.status,
593
- statusText: response.statusText,
594
- headers
595
- });
596
- }
597
-
598
- function encodeInputValue(value) {
599
- if (value instanceof FormData) return {
600
- $f: [...value.entries()].filter(([, v]) => typeof v === "string")
601
- };
602
- if (value instanceof URLSearchParams) return {
603
- $u: [...value.entries()]
604
- };
605
- return value;
606
- }
607
- function decodeInputValue(value) {
608
- if (value && typeof value === "object") {
609
- if (Array.isArray(value.$f)) {
610
- const form = new FormData();
611
- for (const [k, v] of value.$f) form.append(k, v);
612
- return form;
613
- }
614
- if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
615
- }
616
- return value;
617
- }
618
- function encodeFlashCookie(url, result, input, thrown) {
619
- const isError = result instanceof Error;
620
- const payload = {
621
- url,
622
- result: isError ? result.message : result,
623
- error: isError,
624
- thrown: !!thrown,
625
- input: input.map(encodeInputValue)
626
- };
627
- if (fitsCookie(payload)) return flashCookie(payload);
628
- payload.truncated = true;
629
- payload.input = [];
630
- if (!fitsCookie(payload)) {
631
- if (typeof payload.result === "string") {
632
- let prefix = payload.result;
633
- while (prefix.length > 0 && !fitsCookie({
634
- ...payload,
635
- result: prefix
636
- })) {
637
- prefix = prefix.slice(0, prefix.length >> 1);
638
- }
639
- payload.result = prefix.length > 0 ? prefix : true;
640
- } else {
641
- payload.result = true;
642
- }
643
- }
644
- return flashCookie(payload);
645
- }
646
- function flashCookie(payload) {
647
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
648
- secure: true,
649
- httpOnly: true
650
- });
651
- }
652
- const COOKIE_PAIR_BUDGET = 4000;
653
- function fitsCookie(payload) {
654
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
655
- }
656
- function decodeFlashCookie(cookieHeader) {
657
- const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
658
- if (!match) return;
659
- try {
660
- const payload = JSON.parse(match);
661
- if (!payload || !payload.result) return;
662
- const result = payload.error ? new Error(payload.result) : payload.result;
663
- const submission = {
664
- input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
665
- url: payload.url,
666
- result: payload.thrown ? undefined : result,
667
- error: payload.thrown ? result : undefined
668
- };
669
- if (payload.truncated) submission.truncated = true;
670
- return submission;
671
- } catch (error) {
672
- console.error(error);
673
- }
674
- }
675
-
676
- const config = {
677
- provideEvent: undefined,
678
- wrapInvocation: undefined,
679
- collectFlightData: undefined,
680
- transformResult: undefined,
681
- transformFlightResult: undefined,
682
- transformDirectResult: undefined,
683
- handleNoJS: undefined,
684
- endpoint: "/_server",
685
- csrf: true,
686
- bodySizeLimit: 1_048_576,
687
- maxArguments: 1000
688
- };
689
- function configureServerFunctionsServer({
690
- provideEvent,
691
- wrapInvocation,
692
- collectFlightData,
693
- transformResult,
694
- transformFlightResult,
695
- transformDirectResult,
696
- handleNoJS,
697
- endpoint,
698
- csrf,
699
- codec,
700
- bodySizeLimit,
701
- maxArguments
702
- } = {}) {
703
- if (provideEvent !== undefined) config.provideEvent = provideEvent;
704
- if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
705
- if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
706
- if (transformResult !== undefined) config.transformResult = transformResult;
707
- if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
708
- if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
709
- if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
710
- if (endpoint !== undefined) config.endpoint = endpoint;
711
- if (csrf !== undefined) config.csrf = csrf;
712
- if (codec !== undefined) configureServerFunctionsCodec(codec);
713
- if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
714
- if (maxArguments !== undefined) config.maxArguments = maxArguments;
715
- }
716
- const flightSources = new Map();
717
- function registerFlightDataSource(source, hook) {
718
- assertFlightSource(source);
719
- flightSources.set(source, hook);
720
- return () => {
721
- if (flightSources.get(source) === hook) flightSources.delete(source);
722
- };
723
- }
724
- function provideEvent(event, fn) {
725
- if (config.provideEvent) return config.provideEvent(event, fn);
726
- const ctx = globalThis[RequestContext];
727
- if (ctx) return ctx.run(event, fn);
728
- throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
729
- }
730
- function scopeDeferredResult(value, scope) {
731
- if (value === null || typeof value !== "object" && typeof value !== "function") return value;
732
- const promised = scope(() => nativePromise(value));
733
- if (promised) {
734
- return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
735
- }
736
- if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
737
- let reader;
738
- return new ReadableStream({
739
- async pull(controller) {
740
- try {
741
- const step = await scope(() => {
742
- if (!reader) reader = value.getReader();
743
- return reader.read();
744
- });
745
- if (step.done) controller.close();else controller.enqueue(step.value);
746
- } catch (error) {
747
- controller.error(error);
748
- }
749
- },
750
- cancel(reason) {
751
- return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
752
- }
753
- }, {
754
- highWaterMark: 0
755
- });
756
- }
757
- const scopedIterator = symbol => ({
758
- [symbol]() {
759
- const iterator = scope(() => value[symbol]());
760
- return new Proxy(iterator, {
761
- get(target, property) {
762
- const member = Reflect.get(target, property, target);
763
- return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
764
- }
765
- });
766
- }
767
- });
768
- if (typeof value[Symbol.asyncIterator] === "function") {
769
- return scopedIterator(Symbol.asyncIterator);
770
- }
771
- if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
772
- return scopedIterator(Symbol.iterator);
773
- }
774
- return value;
775
- }
776
- const REGISTRATIONS = new Map();
777
- const METHODS = new Map();
778
- const INVOCATIONS = new WeakMap();
779
- let rpcProvided = false;
780
- function provideRPC() {
781
- if (rpcProvided) return;
782
- rpcProvided = true;
783
- provideServerFunctionRPC({
784
- GET,
785
- decodeResponse
786
- });
787
- }
788
- function registerServerFunction(id, callback) {
789
- provideRPC();
790
- if (REGISTRATIONS.get(id) !== callback) METHODS.delete(id);
791
- REGISTRATIONS.set(id, callback);
792
- return callback;
793
- }
794
- function getServerFunction(id) {
795
- const fn = REGISTRATIONS.get(id);
796
- if (fn) {
797
- return fn;
798
- }
799
- throw new Error("invalid server function: " + id);
800
- }
801
- function registerServerReference(id, fn, name) {
802
- if (typeof fn !== "function") {
803
- 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.`);
804
- }
805
- registerServerFunction(id, fn);
806
- return {
807
- id,
808
- fn,
809
- name
810
- };
811
- }
812
- function inProcessInvoker(call) {
813
- return (args, options) => {
814
- const signal = options && options.signal;
815
- if (!signal) return call(...args);
816
- if (signal.aborted) return Promise.reject(signal.reason);
817
- return new Promise((resolve, reject) => {
818
- const onAbort = () => reject(signal.reason);
819
- signal.addEventListener("abort", onAbort, {
820
- once: true
821
- });
822
- let result;
823
- try {
824
- result = call(...args);
825
- } catch (error) {
826
- signal.removeEventListener("abort", onAbort);
827
- return reject(error);
828
- }
829
- Promise.resolve(result).then(value => {
830
- signal.removeEventListener("abort", onAbort);
831
- resolve(value);
832
- }, error => {
833
- signal.removeEventListener("abort", onAbort);
834
- reject(error);
835
- });
836
- });
837
- };
838
- }
839
- function createServerReference({
840
- id,
841
- fn,
842
- name
843
- }) {
844
- if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
845
- provideRPC();
846
- const metadata = name === undefined ? {} : {
847
- name
848
- };
849
- const invokeChannel = inProcessInvoker((...args) => proxy(...args));
850
- const proxy = new Proxy(fn, {
851
- get(target, prop) {
852
- if (prop === "id") return id;
853
- if (prop === "url") {
854
- return serverFunctionAddress(config.endpoint, id);
855
- }
856
- if (prop === SERVER_FUNCTION_METADATA) return metadata;
857
- if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
858
- return target[prop];
859
- },
860
- apply(target, thisArg, args) {
861
- const ogEvt = getRequestEvent();
862
- if (!ogEvt) throw new Error("Cannot call server function outside of a request");
863
- const evt = {
864
- ...ogEvt,
865
- locals: {
866
- ...ogEvt.locals
867
- }
868
- };
869
- INVOCATIONS.set(evt, {
870
- id
871
- });
872
- evt.serverOnly = true;
873
- const scope = run => provideEvent(evt, run);
874
- let result = provideEvent(evt, () => {
875
- const run = () => fn.apply(thisArg, args);
876
- return config.wrapInvocation ? config.wrapInvocation(run, {
877
- id,
878
- args,
879
- event: evt,
880
- direct: true
881
- }) : run();
882
- });
883
- result = scopeDeferredResult(result, scope);
884
- const transform = config.transformDirectResult;
885
- if (transform && result && typeof result.then === "function") {
886
- return result.then(value => scopeDeferredResult(transform(value, {
887
- id,
888
- args,
889
- event: evt
890
- }), scope));
891
- }
892
- return transform ? scopeDeferredResult(transform(result, {
893
- id,
894
- args,
895
- event: evt
896
- }), scope) : result;
897
- }
898
- });
899
- return proxy;
900
- }
901
- function GET(fn) {
902
- if (!isServerFunction(fn) || typeof fn.id !== "string") {
903
- throw new Error("GET expects a server function reference");
904
- }
905
- METHODS.set(fn.id, "GET");
906
- return withMeta(fn, {
907
- method: "GET"
908
- });
909
- }
910
- function live(fn) {
911
- if (!isServerFunction(fn) || typeof fn.id !== "string") {
912
- throw new Error("live expects a server function reference");
913
- }
914
- const metadata = {
915
- ...getServerFunctionMetadata(fn),
916
- live: true
917
- };
918
- const wrapped = async (...args) => {
919
- const result = await fn(...args);
920
- if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
921
- result[LIVE_SOURCE] = true;
922
- }
923
- return result;
924
- };
925
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
926
- wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
927
- wrapped.id = fn.id;
928
- Object.defineProperty(wrapped, "url", {
929
- get: () => fn.url,
930
- configurable: true
931
- });
932
- return wrapped;
933
- }
934
- function getServerFunctionInvocation() {
935
- return getEventServerFunctionInvocation(getRequestEvent());
936
- }
937
- function getEventServerFunctionInvocation(event) {
938
- return event && INVOCATIONS.get(event);
939
- }
940
- function resolveAddress(url) {
941
- return parseServerFunctionAddress(url.pathname, config.endpoint);
942
- }
943
- const DECODE_DEPTH_LIMIT = 64;
944
- function assertDecodeDepth(value) {
945
- let level = [value];
946
- for (let depth = 0; level.length > 0; depth++) {
947
- if (depth > DECODE_DEPTH_LIMIT) {
948
- throw new TypeError("Server function arguments exceed the decode depth limit");
949
- }
950
- const next = [];
951
- for (const node of level) {
952
- if (node === null || typeof node !== "object") continue;
953
- if (Array.isArray(node)) {
954
- for (const child of node) next.push(child);
955
- } else {
956
- for (const key of Object.keys(node)) next.push(node[key]);
957
- }
958
- }
959
- level = next;
960
- }
961
- }
962
- const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
963
- function stripUnsafeArgumentKeys(value) {
964
- const stack = [value];
965
- const seen = new Set();
966
- while (stack.length) {
967
- const v = stack.pop();
968
- if (v === null || typeof v !== "object" || seen.has(v)) continue;
969
- seen.add(v);
970
- for (const key of UNSAFE_ARGUMENT_KEYS) {
971
- delete v[key];
972
- }
973
- for (const key of Object.keys(v)) stack.push(v[key]);
974
- if (v instanceof Map) {
975
- for (const [k, entry] of v) stack.push(k, entry);
976
- } else if (v instanceof Set) {
977
- for (const member of v) stack.push(member);
978
- }
979
- }
980
- return value;
981
- }
982
- async function bufferBodyWithin(request, limit) {
983
- const reader = request.body.getReader();
984
- const signal = request.signal;
985
- const chunks = [];
986
- let total = 0;
987
- const onAbort = () => {
988
- reader.cancel(signal.reason).catch(() => {});
989
- };
990
- if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
991
- once: true
992
- });
993
- try {
994
- for (;;) {
995
- const {
996
- done,
997
- value
998
- } = await reader.read();
999
- if (signal.aborted) throw signal.reason;
1000
- if (done) break;
1001
- total += value.byteLength;
1002
- if (total > limit) {
1003
- reader.cancel().catch(() => {});
1004
- return null;
1005
- }
1006
- chunks.push(value);
1007
- }
1008
- } catch (error) {
1009
- reader.cancel(error).catch(() => {});
1010
- throw error;
1011
- } finally {
1012
- signal.removeEventListener("abort", onAbort);
1013
- reader.releaseLock();
1014
- }
1015
- const body = new Uint8Array(total);
1016
- let offset = 0;
1017
- for (const chunk of chunks) {
1018
- body.set(chunk, offset);
1019
- offset += chunk.byteLength;
1020
- }
1021
- return new Request(request, {
1022
- body
1023
- });
1024
- }
1025
- async function parseArguments(request, url, scripted, codec) {
1026
- const parsed = [];
1027
- const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
1028
- const args = url.searchParams.get("args");
1029
- if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1030
- let result;
1031
- if (args.startsWith(";0x")) {
1032
- result = await deserializeString(args, codec);
1033
- } else {
1034
- result = JSON.parse(args);
1035
- assertDecodeDepth(result);
1036
- }
1037
- if (!Array.isArray(result)) {
1038
- throw new TypeError("Server function arguments must encode an array");
1039
- }
1040
- stripUnsafeArgumentKeys(result);
1041
- for (const arg of result) {
1042
- parsed.push(arg);
1043
- }
1044
- } else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
1045
- parsed.push(url.searchParams);
1046
- }
1047
- if (request.method === "POST" && request.body !== null) {
1048
- const decoded = await extractBody(request.clone(), codec);
1049
- if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1050
- if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1051
- if (!Array.isArray(decoded)) {
1052
- throw new TypeError("Server function arguments must encode an array");
1053
- }
1054
- return stripUnsafeArgumentKeys(decoded);
1055
- }
1056
- if (decoded === undefined) {
1057
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1058
- return parsed;
1059
- }
1060
- throw new TypeError("Server function body carries no usable encoding");
1061
- }
1062
- parsed.push(decoded);
1063
- }
1064
- return parsed;
1065
- }
1066
- async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1067
- if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
1068
- digestOutcome(event, outcome);
1069
- const folded = [];
1070
- for (const [source, hook] of hooks) {
1071
- try {
1072
- const slice = await hook(event, outcome);
1073
- if (slice !== undefined) folded.push([source, slice]);
1074
- } catch (error) {
1075
- console.error(`Error collecting flight data for source "${source}"`, error);
1076
- }
1077
- }
1078
- if (folded.length === 0) return outcome.value;
1079
- const data = Object.fromEntries(folded);
1080
- headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
1081
- if (context.transformFlightResult) {
1082
- const transformed = await context.transformFlightResult(event, {
1083
- value: outcome.value,
1084
- data
1085
- }, context);
1086
- if (transformed !== undefined) {
1087
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1088
- headers.forEach((value, key) => {
1089
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1090
- transformed.headers.set(key, value);
1091
- }
1092
- });
1093
- return transformed;
1094
- }
1095
- }
1096
- return outcome.value === undefined ? {
1097
- data
1098
- } : {
1099
- value: outcome.value,
1100
- data
1101
- };
1102
- }
1103
- function digestOutcome(event, outcome) {
1104
- const {
1105
- request,
1106
- response
1107
- } = outcome;
1108
- outcome.revalidateKeys = response?.headers.get(REVALIDATE_HEADER)?.split(",");
1109
- outcome.foldedHeaders = foldSetCookies(request.headers, [...(event.response?.headers?.getSetCookie() ?? []), ...(response?.headers?.getSetCookie() ?? [])]);
1110
- try {
1111
- const referrer = request.headers.get("referer");
1112
- if (referrer) {
1113
- const location = response?.headers.get("Location");
1114
- const target = location ? new URL(location, request.url) : new URL(referrer);
1115
- if (target.origin === new URL(request.url).origin) outcome.targetUrl = target.toString();
1116
- }
1117
- } catch {
1118
- }
1119
- }
1120
- function parseSetCookie(setCookie) {
1121
- const [pair, ...attributes] = setCookie.split(";");
1122
- const eq = pair.indexOf("=");
1123
- if (eq < 0) return undefined;
1124
- const parsed = {
1125
- name: pair.slice(0, eq).trim(),
1126
- value: pair.slice(eq + 1).trim()
1127
- };
1128
- for (const attribute of attributes) {
1129
- const attrEq = attribute.indexOf("=");
1130
- const key = (attrEq < 0 ? attribute : attribute.slice(0, attrEq)).trim().toLowerCase();
1131
- const value = attrEq < 0 ? "" : attribute.slice(attrEq + 1).trim();
1132
- if (key === "max-age") parsed.maxAge = Number(value);else if (key === "expires") parsed.expires = new Date(value);
1133
- }
1134
- return parsed;
1135
- }
1136
- function foldSetCookies(headers, setCookies) {
1137
- const folded = new Headers(headers);
1138
- if (!setCookies.length) return folded;
1139
- const cookies = {};
1140
- for (const pair of folded.get("cookie")?.split(";") ?? []) {
1141
- const eq = pair.indexOf("=");
1142
- if (eq > -1) cookies[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
1143
- }
1144
- for (const setCookie of setCookies) {
1145
- const parsed = parseSetCookie(setCookie);
1146
- if (!parsed) continue;
1147
- if (parsed.maxAge != null && parsed.maxAge <= 0 || parsed.expires != null && parsed.expires.getTime() <= Date.now()) {
1148
- delete cookies[parsed.name];
1149
- } else {
1150
- cookies[parsed.name] = parsed.value;
1151
- }
1152
- }
1153
- folded.delete("cookie");
1154
- const serialized = Object.entries(cookies).map(([name, value]) => `${name}=${value}`).join("; ");
1155
- if (serialized) folded.set("cookie", serialized);
1156
- return folded;
1157
- }
1158
- function mergeResponseHeaders(target, source) {
1159
- source.forEach((value, key) => {
1160
- if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1161
- });
1162
- if (source.getSetCookie) {
1163
- for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
1164
- } else if (source.has("set-cookie")) {
1165
- target.append("Set-Cookie", source.get("set-cookie"));
1166
- }
1167
- }
1168
- const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
1169
- function maskRedirect(headers, response, requestUrl) {
1170
- const target = response.headers && response.headers.get("Location");
1171
- if (target) {
1172
- headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
1173
- }
1174
- headers.delete("Location");
1175
- }
1176
- const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1177
- function enforceComposedHeaderInvariants(response) {
1178
- for (const name of BOUNDED_COMPOSED_HEADERS) {
1179
- const value = response.headers.get(name);
1180
- if (value === null) continue;
1181
- if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
1182
- 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);
1183
- }
1184
- if (name === REVALIDATE_HEADER) continue;
1185
- const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1186
- if (!isHttpNavigationTarget(target)) {
1187
- 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);
1188
- }
1189
- }
1190
- return response;
1191
- }
1192
- function refuseComposedHeader(response, name, headerMessage, body) {
1193
- if (response.body) {
1194
- try {
1195
- const cancelled = response.body.cancel();
1196
- if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1197
- } catch {}
1198
- }
1199
- const headers = new Headers();
1200
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
1201
- return new Response(body, {
1202
- status: 500,
1203
- headers
1204
- });
1205
- }
1206
- function warnScripted304(functionId) {
1207
- if (DEV) {
1208
- 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.`);
1209
- }
1210
- }
1211
- function createNoJSHandler({
1212
- base = ""
1213
- } = {}) {
1214
- return function handleNoJS(result, request, args, thrown) {
1215
- const url = new URL(request.url);
1216
- let back = new URL(base || "/", url.origin).toString();
1217
- try {
1218
- const referer = request.headers.get("referer");
1219
- if (referer) back = new URL(referer).toString();
1220
- } catch {}
1221
- let status = 303;
1222
- let headers;
1223
- if (result instanceof Response) {
1224
- headers = new Headers();
1225
- mergeResponseHeaders(headers, result.headers);
1226
- if (result.headers.has("Location")) {
1227
- headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
1228
- if (validRedirectStatuses.has(result.status)) status = result.status;
1229
- } else {
1230
- headers.set("Location", back);
1231
- }
1232
- headers.delete("Content-Type");
1233
- headers.delete("Content-Length");
1234
- } else {
1235
- headers = new Headers({
1236
- Location: back
1237
- });
1238
- }
1239
- if (result && !(result instanceof Response)) {
1240
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1241
- }
1242
- return new Response(null, {
1243
- status,
1244
- headers
1245
- });
1246
- };
1247
- }
1248
- let defaultNoJSHandler;
1249
- function isFormPost(request) {
1250
- if (request.method !== "POST" || request.headers.has(BODY_FORMAT_HEADER)) return false;
1251
- const type = request.headers.get("content-type") || "";
1252
- return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
1253
- }
1254
- function guardFailures(value, state) {
1255
- if (!state) state = {
1256
- seen: new WeakMap(),
1257
- cyclic: new WeakSet()
1258
- };
1259
- const entered = enterGuard(value, state);
1260
- if (!(entered instanceof Frame)) return entered;
1261
- const stack = [entered];
1262
- let delivered = NOTHING;
1263
- for (;;) {
1264
- const top = stack[stack.length - 1];
1265
- const items = top.items;
1266
- let pushed = null;
1267
- while (top.i < items.length) {
1268
- const i = top.i;
1269
- let original;
1270
- if (top.kind === OBJECT) {
1271
- const descriptor = top.descriptors[items[i]];
1272
- if ("value" in descriptor) {
1273
- original = descriptor.value;
1274
- } else if (typeof descriptor.get === "function") {
1275
- if (top.accessorRead !== i) {
1276
- try {
1277
- top.accessorValue = descriptor.get.call(top.value);
1278
- } catch (error) {
1279
- throw sanitizeServerError(error);
1280
- }
1281
- top.accessorRead = i;
1282
- }
1283
- original = top.accessorValue;
1284
- } else {
1285
- top.i++;
1286
- continue;
1287
- }
1288
- } else {
1289
- original = items[i];
1290
- }
1291
- let guarded;
1292
- if (delivered !== NOTHING) {
1293
- guarded = delivered;
1294
- delivered = NOTHING;
1295
- } else {
1296
- guarded = enterGuard(original, state);
1297
- if (guarded instanceof Frame) {
1298
- pushed = guarded;
1299
- break;
1300
- }
1301
- }
1302
- if (top.kind === ARRAY) {
1303
- if (guarded !== original) {
1304
- top.next[i] = guarded;
1305
- top.changed = true;
1306
- }
1307
- } else if (top.kind === MAP) {
1308
- if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
1309
- if (guarded !== original) top.changed = true;
1310
- } else if (top.kind === SET) {
1311
- top.next.add(guarded);
1312
- if (guarded !== original) top.changed = true;
1313
- } else if (guarded !== original || top.accessorRead === i) {
1314
- Object.defineProperty(top.next, items[i], {
1315
- value: guarded,
1316
- writable: true,
1317
- configurable: true,
1318
- enumerable: top.descriptors[items[i]].enumerable
1319
- });
1320
- top.changed = true;
1321
- }
1322
- top.i++;
1323
- }
1324
- if (pushed !== null) {
1325
- stack.push(pushed);
1326
- continue;
1327
- }
1328
- stack.pop();
1329
- const out = keepGuarded(top.value, top.next, top.changed, state);
1330
- if (stack.length === 0) return out;
1331
- delivered = out;
1332
- }
1333
- }
1334
- const NOTHING = Symbol();
1335
- const ARRAY = 0;
1336
- const MAP = 1;
1337
- const SET = 2;
1338
- const OBJECT = 3;
1339
- class Frame {
1340
- constructor(kind, value, next, items, descriptors) {
1341
- this.kind = kind;
1342
- this.value = value;
1343
- this.next = next;
1344
- this.items = items;
1345
- this.descriptors = descriptors;
1346
- this.i = 0;
1347
- this.changed = false;
1348
- this.accessorRead = -1;
1349
- this.accessorValue = undefined;
1350
- this.pendingKey = undefined;
1351
- }
1352
- }
1353
- function guardOperation(state, run) {
1354
- return state.scope ? state.scope(run) : run();
1355
- }
1356
- function enterGuard(value, state) {
1357
- if (value === null || typeof value !== "object") return value;
1358
- if (state.seen.has(value)) {
1359
- state.cyclic.add(value);
1360
- return state.seen.get(value);
1361
- }
1362
- if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1363
- let reader;
1364
- const gate = state.gate;
1365
- let finished = false;
1366
- const close = () => {
1367
- if (finished) return;
1368
- finished = true;
1369
- try {
1370
- const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1371
- if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1372
- } catch {}
1373
- };
1374
- const guardedStream = new ReadableStream({
1375
- async pull(controller) {
1376
- try {
1377
- if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
1378
- if (finished) {
1379
- controller.close();
1380
- return;
1381
- }
1382
- if (!reader) reader = guardOperation(state, () => value.getReader());
1383
- const {
1384
- done,
1385
- value: chunk
1386
- } = await guardOperation(state, () => reader.read());
1387
- done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1388
- } catch (error) {
1389
- controller.error(guardOperation(state, () => sanitizeServerError(error)));
1390
- }
1391
- },
1392
- cancel(reason) {
1393
- finished = true;
1394
- return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1395
- }
1396
- });
1397
- if (gate) gate.onOpen(close);
1398
- state.seen.set(value, guardedStream);
1399
- return guardedStream;
1400
- }
1401
- if (typeof value.then === "function") {
1402
- const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1403
- throw guardOperation(state, () => sanitizeServerError(error));
1404
- });
1405
- guardedPromise.catch(() => {});
1406
- state.seen.set(value, guardedPromise);
1407
- return guardedPromise;
1408
- }
1409
- if (typeof value[Symbol.asyncIterator] === "function") {
1410
- const source = value;
1411
- const gate = state.gate;
1412
- const guardedIterable = {
1413
- [Symbol.asyncIterator]() {
1414
- const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1415
- let finished = false;
1416
- const close = () => {
1417
- if (finished) return;
1418
- finished = true;
1419
- try {
1420
- const returned = iterator.return && guardOperation(state, () => iterator.return());
1421
- if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1422
- } catch {}
1423
- };
1424
- if (gate) gate.onOpen(close);
1425
- const step = () => finished ? Promise.resolve({
1426
- done: true,
1427
- value: undefined
1428
- }) : guardOperation(state, () => iterator.next()).then(step => {
1429
- if (step.done) {
1430
- finished = true;
1431
- return step;
1432
- }
1433
- return {
1434
- done: false,
1435
- value: guardOperation(state, () => guardFailures(step.value, state))
1436
- };
1437
- }, error => {
1438
- throw guardOperation(state, () => sanitizeServerError(error));
1439
- });
1440
- return {
1441
- next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
1442
- return: () => {
1443
- close();
1444
- return Promise.resolve({
1445
- done: true,
1446
- value: undefined
1447
- });
1448
- }
1449
- };
1450
- }
1451
- };
1452
- state.seen.set(value, guardedIterable);
1453
- return guardedIterable;
1454
- }
1455
- if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1456
- const scopedIterable = scopeDeferredResult(value, state.scope);
1457
- state.seen.set(value, scopedIterable);
1458
- return scopedIterable;
1459
- }
1460
- if (Array.isArray(value)) {
1461
- const next = value.slice();
1462
- state.seen.set(value, next);
1463
- return new Frame(ARRAY, value, next, value, null);
1464
- }
1465
- if (value instanceof Map) {
1466
- const next = new Map();
1467
- state.seen.set(value, next);
1468
- const items = [];
1469
- for (const entry of value) items.push(entry[0], entry[1]);
1470
- return new Frame(MAP, value, next, items, null);
1471
- }
1472
- if (value instanceof Set) {
1473
- const next = new Set();
1474
- state.seen.set(value, next);
1475
- return new Frame(SET, value, next, [...value], null);
1476
- }
1477
- const prototype = Object.getPrototypeOf(value);
1478
- if (prototype !== Object.prototype && prototype !== null) {
1479
- state.seen.set(value, value);
1480
- return value;
1481
- }
1482
- const descriptors = Object.getOwnPropertyDescriptors(value);
1483
- for (const key of Object.keys(descriptors)) {
1484
- descriptors[key].configurable = true;
1485
- if ("value" in descriptors[key]) descriptors[key].writable = true;
1486
- }
1487
- const next = Object.create(prototype, descriptors);
1488
- state.seen.set(value, next);
1489
- return new Frame(OBJECT, value, next, Object.keys(value), descriptors);
1490
- }
1491
- function keepGuarded(value, next, changed, state) {
1492
- if (changed || state.cyclic.has(value)) return next;
1493
- state.seen.set(value, value);
1494
- return value;
1495
- }
1496
- function serializeResponseStream(value, codecOptions, signal, scope) {
1497
- let closed = false;
1498
- let streamController = null;
1499
- let demandWaiters = null;
1500
- const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
1501
- const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
1502
- const supplyDemand = () => {
1503
- const resolvers = demandWaiters;
1504
- demandWaiters = null;
1505
- if (resolvers) for (const resolve of resolvers) resolve();
1506
- };
1507
- const sourceClosers = new Set();
1508
- const gate = {
1509
- wantsMore,
1510
- awaitDemand,
1511
- onOpen(close) {
1512
- if (closed) close();else sourceClosers.add(close);
1513
- }
1514
- };
1515
- const guardState = {
1516
- seen: new WeakMap(),
1517
- cyclic: new WeakSet(),
1518
- gate,
1519
- scope
1520
- };
1521
- value = guardOperation(guardState, () => guardFailures(value, guardState));
1522
- let cancelSerialize = null;
1523
- let onAbort = null;
1524
- const finishSource = () => {
1525
- for (const close of sourceClosers) close();
1526
- sourceClosers.clear();
1527
- supplyDemand();
1528
- };
1529
- const teardown = () => {
1530
- if (closed) return;
1531
- closed = true;
1532
- if (onAbort) signal.removeEventListener("abort", onAbort);
1533
- if (cancelSerialize) cancelSerialize();
1534
- finishSource();
1535
- };
1536
- return new ReadableStream({
1537
- async start(controller) {
1538
- streamController = controller;
1539
- if (signal) {
1540
- if (signal.aborted) {
1541
- teardown();
1542
- controller.close();
1543
- return;
1544
- }
1545
- onAbort = () => {
1546
- const alreadyClosed = closed;
1547
- teardown();
1548
- if (!alreadyClosed) {
1549
- try {
1550
- controller.error(signal.reason || new Error("The operation was aborted."));
1551
- } catch {}
1552
- }
1553
- };
1554
- signal.addEventListener("abort", onAbort);
1555
- }
1556
- const {
1557
- serializeJSON
1558
- } = await import('@solidjs/web/serialization');
1559
- if (closed) {
1560
- try {
1561
- controller.close();
1562
- } catch {}
1563
- return;
1564
- }
1565
- cancelSerialize = serializeJSON(value, {
1566
- ...codecOptions,
1567
- onParse(node) {
1568
- if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
1569
- },
1570
- onDone() {
1571
- if (closed) return;
1572
- closed = true;
1573
- if (onAbort) signal.removeEventListener("abort", onAbort);
1574
- finishSource();
1575
- controller.close();
1576
- },
1577
- onError(error) {
1578
- if (closed) return;
1579
- closed = true;
1580
- if (onAbort) signal.removeEventListener("abort", onAbort);
1581
- finishSource();
1582
- try {
1583
- const delivered = sanitizeServerError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error);
1584
- controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
1585
- controller.close();
1586
- } catch {
1587
- try {
1588
- controller.error(error);
1589
- } catch {}
1590
- }
1591
- }
1592
- });
1593
- },
1594
- pull() {
1595
- supplyDemand();
1596
- },
1597
- cancel() {
1598
- teardown();
1599
- }
1600
- });
1601
- }
1602
- function serializedResponse(value, headers, codec, signal, scope) {
1603
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
1604
- headers.set("Content-Type", "text/plain");
1605
- return new Response(serializeResponseStream(value, codec, signal, scope), {
1606
- headers
1607
- });
1608
- }
1609
- function encodeResult(value, headers, status, codec, signal, scope) {
1610
- if (NULL_BODY_STATUSES.has(status)) {
1611
- if (value === undefined || value === null) {
1612
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
1613
- return new Response(null, {
1614
- status,
1615
- headers
1616
- });
1617
- }
1618
- 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.`);
1619
- headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
1620
- return encodeResult(error, headers, 500, codec, signal, scope);
1621
- }
1622
- const direct = getHeadersAndBody(value);
1623
- if (direct) {
1624
- for (const [key, val] of Object.entries(direct.headers || {})) {
1625
- headers.set(key, val);
1626
- }
1627
- return new Response(direct.body, {
1628
- status,
1629
- headers
1630
- });
1631
- }
1632
- if (value === undefined) {
1633
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
1634
- return new Response(null, {
1635
- status,
1636
- headers
1637
- });
1638
- }
1639
- try {
1640
- const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
1641
- if (jsonSafe) {
1642
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
1643
- headers.set("Content-Type", "application/json");
1644
- const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
1645
- return new Response(body, {
1646
- status,
1647
- headers
1648
- });
1649
- }
1650
- } catch {
1651
- }
1652
- try {
1653
- const response = serializedResponse(value, headers, codec, signal, scope);
1654
- return status === 200 ? response : new Response(response.body, {
1655
- status,
1656
- headers
1657
- });
1658
- } catch (error) {
1659
- throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
1660
- }
1661
- }
1662
- const ERROR_HEADER_VALUE_LIMIT = 1024;
1663
- function boundedErrorHeaderValue(message) {
1664
- let label = message.length > 256 ? message.slice(0, 256) : message;
1665
- let encoded = encodeErrorHeaderValue(label);
1666
- while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
1667
- label = label.slice(0, Math.ceil(label.length / 2));
1668
- encoded = encodeErrorHeaderValue(label);
1669
- }
1670
- return encoded;
1671
- }
1672
- const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
1673
- let DEV = true === true;
1674
- function setServerFunctionsDev(dev) {
1675
- DEV = !!dev;
1676
- }
1677
- function sanitizeServerError(value) {
1678
- if (DEV) return value;
1679
- if (isSafeError(value)) return value;
1680
- return new Error(GENERIC_SERVER_ERROR_MESSAGE);
1681
- }
1682
- function observeServerFunctionCalls() {
1683
- return () => {};
1684
- }
1685
- function serverFunctionUrl(id, boundArgs) {
1686
- const address = serverFunctionAddress(config.endpoint, id);
1687
- if (!boundArgs || !boundArgs.length) return address;
1688
- if (!isJSONSafe(boundArgs)) {
1689
- 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.");
1690
- }
1691
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
1692
- }
1693
- function parseServerFunctionUrl(url) {
1694
- const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
1695
- return parsed && parsed.id;
1696
- }
1697
- async function matchesOrigin(origin, request, matcher) {
1698
- if (matcher === undefined) return origin === new URL(request.url).origin;
1699
- if (typeof matcher === "function") return (await matcher(origin, request)) === true;
1700
- return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
1701
- }
1702
- async function allowsServerFunctionRequest(request, options) {
1703
- const fetchSite = request.headers.get("Sec-Fetch-Site");
1704
- if (fetchSite === "same-origin") return true;
1705
- if (fetchSite === "same-site" || fetchSite === "cross-site" || fetchSite === "none") {
1706
- return false;
1707
- }
1708
- const origin = request.headers.get("Origin");
1709
- if (origin !== null) return matchesOrigin(origin, request, options.origin);
1710
- const referer = request.headers.get("Referer");
1711
- if (referer !== null) {
1712
- try {
1713
- return matchesOrigin(new URL(referer).origin, request, options.origin);
1714
- } catch {
1715
- return false;
1716
- }
1717
- }
1718
- return options.allowRequestsWithoutOriginCheck === true;
1719
- }
1720
- const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
1721
- function withCSRFVary(response) {
1722
- const current = response.headers.get("Vary");
1723
- if (current === "*") return response;
1724
- const values = current ? current.split(",").map(value => value.trim()) : [];
1725
- const names = new Set(values.map(value => value.toLowerCase()));
1726
- for (const value of CSRF_VARY) {
1727
- if (!names.has(value.toLowerCase())) values.push(value);
1728
- }
1729
- const vary = values.join(", ");
1730
- try {
1731
- response.headers.set("Vary", vary);
1732
- return response;
1733
- } catch {
1734
- const headers = new Headers(response.headers);
1735
- headers.set("Vary", vary);
1736
- return new Response(response.body, {
1737
- status: response.status,
1738
- statusText: response.statusText,
1739
- headers
1740
- });
1741
- }
1742
- }
1743
- function forbiddenResponse() {
1744
- return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
1745
- status: 403,
1746
- headers: {
1747
- "Cache-Control": "no-store"
1748
- }
1749
- }));
1750
- }
1751
- function nativePromise(value) {
1752
- if (value instanceof Promise) return value;
1753
- try {
1754
- if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
1755
- } catch {}
1756
- }
1757
- async function handleServerFunctionRequest(request, options = {}) {
1758
- const codec = {
1759
- ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
1760
- };
1761
- codec.serializeErrorStacks ??= DEV;
1762
- const url = new URL(request.url);
1763
- const method = request.method;
1764
- const address = resolveAddress(url);
1765
- const functionId = address && address.id;
1766
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
1767
- const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1768
- const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1769
- let serverFunction;
1770
- if (functionId) {
1771
- try {
1772
- serverFunction = getServerFunction(functionId);
1773
- } catch {
1774
- return finalizeTransportResponse(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
1775
- status: 404,
1776
- headers: {
1777
- [UNKNOWN_HEADER]: "true"
1778
- }
1779
- }), method);
1780
- }
1781
- }
1782
- if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
1783
- return finalizeTransportResponse(forbiddenResponse(), method);
1784
- }
1785
- const instance = request.headers.get(INSTANCE_HEADER);
1786
- if (!functionId) {
1787
- const response = new Response(DEV ? "Server function not found" : null, {
1788
- status: 404
1789
- });
1790
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1791
- }
1792
- const scripted = address.data;
1793
- if (method !== "POST" && !declaredRead) {
1794
- const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1795
- status: 405,
1796
- headers: {
1797
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
1798
- }
1799
- });
1800
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1801
- }
1802
- const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
1803
- const argsEncoding = url.searchParams.get("args");
1804
- if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
1805
- const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
1806
- status: 413
1807
- });
1808
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1809
- }
1810
- if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
1811
- const raw = request.headers.get("content-length");
1812
- const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
1813
- if (declared > bodySizeLimit) {
1814
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1815
- status: 413
1816
- });
1817
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1818
- }
1819
- if (!(declared > 0)) {
1820
- let bounded;
1821
- try {
1822
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1823
- } catch {
1824
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1825
- status: 400
1826
- });
1827
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1828
- }
1829
- if (bounded === null) {
1830
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1831
- status: 413
1832
- });
1833
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1834
- }
1835
- request = bounded;
1836
- }
1837
- }
1838
- let event;
1839
- try {
1840
- event = options.createEvent ? options.createEvent(request) : {
1841
- request,
1842
- locals: {}
1843
- };
1844
- const promised = nativePromise(event);
1845
- if (promised) event = await promised;
1846
- } catch (error) {
1847
- const safe = sanitizeServerError(error);
1848
- const message = safe instanceof Error ? safe.message : String(safe);
1849
- const headers = new Headers();
1850
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
1851
- const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
1852
- status: 500
1853
- });
1854
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1855
- }
1856
- const refuseCommitted = raw => {
1857
- const response = commitEventResponse(raw, event);
1858
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1859
- };
1860
- const provide = options.provideEvent || provideEvent;
1861
- const scope = run => provide(event, run);
1862
- const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1863
- const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1864
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
1865
- const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1866
- let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1867
- if (handleNoJS === undefined && !scripted && isFormPost(request)) {
1868
- const fetchMode = request.headers.get("Sec-Fetch-Mode");
1869
- if (fetchMode === null || fetchMode === "navigate") {
1870
- handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
1871
- } else {
1872
- 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, {
1873
- status: 400
1874
- });
1875
- return refuseCommitted(response);
1876
- }
1877
- }
1878
- const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1879
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
1880
- const hook = source === "true" ? flightHook : flightSources.get(source);
1881
- return hook ? [[source, hook]] : [];
1882
- }) : [];
1883
- const collectsFlight = flightHooks.length > 0;
1884
- let parsed;
1885
- try {
1886
- parsed = await parseArguments(request, url, scripted, codec);
1887
- } catch {
1888
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1889
- status: 400
1890
- });
1891
- return refuseCommitted(response);
1892
- }
1893
- const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
1894
- if (parsed.length > maxArguments) {
1895
- const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
1896
- status: 400
1897
- });
1898
- return refuseCommitted(response);
1899
- }
1900
- const flightContext = {
1901
- id: functionId,
1902
- args: parsed,
1903
- instance,
1904
- request,
1905
- collectsFlight,
1906
- codec,
1907
- transformFlightResult
1908
- };
1909
- const headers = new Headers();
1910
- const dispatch = async () => {
1911
- try {
1912
- let invocations = 0;
1913
- const invokeOnce = async () => {
1914
- INVOCATIONS.set(event, {
1915
- id: functionId
1916
- });
1917
- const run = () => serverFunction(...parsed);
1918
- return wrapInvocation ? wrapInvocation(run, {
1919
- id: functionId,
1920
- args: parsed,
1921
- event,
1922
- request,
1923
- direct: false
1924
- }) : run();
1925
- };
1926
- let result = await provide(event, () => {
1927
- if (++invocations > 1) {
1928
- throw new Error("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.");
1929
- }
1930
- return invokeOnce();
1931
- });
1932
- if (invocations !== 1) {
1933
- throw new Error(invocations === 0 ? "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." : "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.");
1934
- }
1935
- if (transformResult) {
1936
- result = await transformResult(event, result, flightContext);
1937
- }
1938
- let status = 200;
1939
- let metadata;
1940
- if (isResponseEnvelope(result)) {
1941
- const {
1942
- response,
1943
- value
1944
- } = result;
1945
- if (!scripted && !handleNoJS && response && response.body) {
1946
- return response;
1947
- }
1948
- if (response && response.headers) {
1949
- mergeResponseHeaders(headers, response.headers);
1950
- }
1951
- if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
1952
- status = response.status;
1953
- } else if (response && response.status) {
1954
- maskRedirect(headers, response, request.url);
1955
- }
1956
- metadata = response;
1957
- result = value;
1958
- } else if (result instanceof Response) {
1959
- if (result.headers && result.headers.has("X-Content-Raw")) return result;
1960
- if (scripted) {
1961
- if (result.headers) {
1962
- mergeResponseHeaders(headers, result.headers);
1963
- }
1964
- if (result.status && !validRedirectStatuses.has(result.status)) {
1965
- status = result.status;
1966
- } else if (result.status) {
1967
- maskRedirect(headers, result, request.url);
1968
- }
1969
- metadata = result;
1970
- if (result.body == null) {
1971
- result = null;
1972
- }
1973
- }
1974
- }
1975
- if (collectsFlight) {
1976
- result = await foldFlightData(flightHooks, event, headers, {
1977
- id: functionId,
1978
- value: result,
1979
- response: metadata,
1980
- request,
1981
- thrown: false
1982
- }, flightContext);
1983
- if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1984
- }
1985
- if (!scripted) {
1986
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
1987
- if (result instanceof Response) return result;
1988
- return encodeResult(result, headers, status, codec, request.signal, scope);
1989
- }
1990
- if (status === 304) warnScripted304(functionId);
1991
- return encodeResult(result, headers, status, codec, request.signal, scope);
1992
- } catch (x) {
1993
- const respondThrown = value => {
1994
- const safe = sanitizeServerError(value);
1995
- if (!scripted) {
1996
- if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1997
- const message = safe instanceof Error ? safe.message : String(safe);
1998
- return new Response(DEV ? message : null, {
1999
- status: 500
2000
- });
2001
- }
2002
- const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
2003
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2004
- return encodeResult(safe, headers, 500, codec, request.signal, scope);
2005
- };
2006
- if (x instanceof Response || isResponseEnvelope(x)) {
2007
- if (transformResult) {
2008
- try {
2009
- x = await transformResult(event, x, {
2010
- ...flightContext,
2011
- thrown: true
2012
- });
2013
- } catch (hookError) {
2014
- return respondThrown(hookError);
2015
- }
2016
- }
2017
- let status = 200;
2018
- let metadata;
2019
- if (isResponseEnvelope(x)) {
2020
- const {
2021
- response,
2022
- value
2023
- } = x;
2024
- if (response && response.headers) {
2025
- mergeResponseHeaders(headers, response.headers);
2026
- }
2027
- if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
2028
- status = response.status;
2029
- } else if (response && response.status) {
2030
- maskRedirect(headers, response, request.url);
2031
- }
2032
- metadata = response;
2033
- x = value;
2034
- } else if (x instanceof Response) {
2035
- if (x.headers) {
2036
- mergeResponseHeaders(headers, x.headers);
2037
- }
2038
- if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
2039
- status = x.status;
2040
- } else if (x.status) {
2041
- maskRedirect(headers, x, request.url);
2042
- }
2043
- metadata = x;
2044
- if (x.body == null) {
2045
- x = null;
2046
- }
2047
- }
2048
- if (collectsFlight) {
2049
- x = await foldFlightData(flightHooks, event, headers, {
2050
- id: functionId,
2051
- value: x,
2052
- response: metadata,
2053
- request,
2054
- thrown: true
2055
- }, flightContext);
2056
- if (x instanceof Response && x.headers.has("X-Content-Raw")) {
2057
- x = ownResponse(x);
2058
- x.headers.set(ERROR_HEADER, "true");
2059
- return x;
2060
- }
2061
- }
2062
- headers.set(ERROR_HEADER, "true");
2063
- if (!scripted) {
2064
- if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
2065
- if (x instanceof Response) return x;
2066
- }
2067
- if (scripted && status === 304) warnScripted304(functionId);
2068
- return encodeResult(x, headers, status, codec, request.signal, scope);
2069
- }
2070
- return respondThrown(x);
2071
- }
2072
- };
2073
- const response = commitEventResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())), event);
2074
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2075
- }
2076
- function ownResponse(response) {
2077
- try {
2078
- return new Response(response.body, response);
2079
- } catch {
2080
- return response;
2081
- }
2082
- }
2083
- function finalizeTransportResponse(response, method) {
2084
- const stripBody = method === "HEAD" && response.body !== null;
2085
- const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
2086
- if (stripBody || defaultsCache) {
2087
- try {
2088
- if (defaultsCache) {
2089
- response.headers.set("Cache-Control", "no-store");
2090
- }
2091
- if (!stripBody) return response;
2092
- response.body.cancel().catch(() => {});
2093
- return new Response(null, {
2094
- status: response.status,
2095
- statusText: response.statusText,
2096
- headers: response.headers
2097
- });
2098
- } catch {
2099
- const headers = new Headers(response.headers);
2100
- if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
2101
- if (stripBody) response.body.cancel().catch(() => {});
2102
- return new Response(stripBody ? null : response.body, {
2103
- status: response.status,
2104
- statusText: response.statusText,
2105
- headers
2106
- });
2107
- }
2108
- }
2109
- return response;
2110
- }
2111
-
2112
- exports.ERROR_HEADER = ERROR_HEADER;
2113
- exports.FLASH_COOKIE = FLASH_COOKIE;
2114
- exports.GENERIC_SERVER_ERROR_MESSAGE = GENERIC_SERVER_ERROR_MESSAGE;
2115
- exports.GET = GET;
2116
- exports.INSTANCE_HEADER = INSTANCE_HEADER;
2117
- exports.REDIRECT_HEADER = REDIRECT_HEADER;
2118
- exports.SERVER_FUNCTION_INVOKE = SERVER_FUNCTION_INVOKE;
2119
- exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
2120
- exports.UNKNOWN_HEADER = UNKNOWN_HEADER;
2121
- exports.clearFlashCookie = clearFlashCookie;
2122
- exports.configureServerFunctionsServer = configureServerFunctionsServer;
2123
- exports.createNoJSHandler = createNoJSHandler;
2124
- exports.createServerReference = createServerReference;
2125
- exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
2126
- exports.decodeFlashCookie = decodeFlashCookie;
2127
- exports.decodeRedirectHeaderValue = decodeRedirectHeaderValue;
2128
- exports.decodeResponse = decodeResponse;
2129
- exports.decodeResponsePayload = decodeResponsePayload;
2130
- exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
2131
- exports.encodeFlashCookie = encodeFlashCookie;
2132
- exports.foldSetCookies = foldSetCookies;
2133
- exports.getEventServerFunctionInvocation = getEventServerFunctionInvocation;
2134
- exports.getServerFunction = getServerFunction;
2135
- exports.getServerFunctionInvocation = getServerFunctionInvocation;
2136
- exports.getServerFunctionMetadata = getServerFunctionMetadata;
2137
- exports.guardFailures = guardFailures;
2138
- exports.handleServerFunctionRequest = handleServerFunctionRequest;
2139
- exports.hasFlashCookie = hasFlashCookie;
2140
- exports.invoke = invoke;
2141
- exports.isServerFunction = isServerFunction;
2142
- exports.live = live;
2143
- exports.observeServerFunctionCalls = observeServerFunctionCalls;
2144
- exports.parseServerFunctionUrl = parseServerFunctionUrl;
2145
- exports.registerFlightDataSource = registerFlightDataSource;
2146
- exports.registerServerFunction = registerServerFunction;
2147
- exports.registerServerReference = registerServerReference;
2148
- exports.sanitizeServerError = sanitizeServerError;
2149
- exports.serializeResponseStream = serializeResponseStream;
2150
- exports.serverFunctionUrl = serverFunctionUrl;
2151
- exports.setServerFunctionsDev = setServerFunctionsDev;
2152
- exports.subscribeFlightData = subscribeFlightData;
2153
- exports.withMeta = withMeta;