@solidjs/web 2.0.0-rc.1 → 2.0.0-rc.11

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 (107) hide show
  1. package/dist/server.dev.js +4472 -0
  2. package/dist/server.js +1301 -251
  3. package/dist/{server.cjs → server.observe.js} +1501 -452
  4. package/dist/{dev.cjs → web.dev.js} +699 -360
  5. package/dist/web.js +454 -139
  6. package/dist/{dev.js → web.observe.js} +505 -211
  7. package/frames/dist/client.dev.js +463 -71
  8. package/frames/dist/client.js +363 -70
  9. package/frames/dist/{client.dev.cjs → client.observe.js} +486 -133
  10. package/frames/dist/server.dev.js +1713 -0
  11. package/frames/dist/server.js +552 -2583
  12. package/frames/dist/server.observe.js +1713 -0
  13. package/frames/package.json +2 -25
  14. package/package.json +214 -255
  15. package/performance-tracks/dist/performance-tracks.dev.js +678 -0
  16. package/performance-tracks/dist/performance-tracks.js +6 -0
  17. package/performance-tracks/dist/performance-tracks.observe.js +666 -0
  18. package/performance-tracks/package.json +7 -0
  19. package/performance-tracks/types/index.d.ts +67 -0
  20. package/serialization/decode/package.json +2 -15
  21. package/serialization/dist/decode.js +92 -15
  22. package/serialization/dist/serialization.js +103 -23
  23. package/serialization/package.json +2 -15
  24. package/serialization/types/index.d.ts +76 -157
  25. package/serialization/types/serializer-decode.d.ts +149 -112
  26. package/serialization/types/serializer.d.ts +101 -0
  27. package/server-functions/dist/client.dev.js +1364 -0
  28. package/server-functions/dist/client.js +611 -97
  29. package/server-functions/dist/client.observe.js +1343 -0
  30. package/server-functions/dist/server.dev.js +2138 -202
  31. package/server-functions/dist/server.js +2042 -199
  32. package/server-functions/dist/server.observe.js +3043 -0
  33. package/server-functions/package.json +2 -35
  34. package/server-functions/rich-args/package.json +2 -15
  35. package/storage/package.json +2 -15
  36. package/types/client.d.ts +193 -288
  37. package/types/constants.d.ts +20 -0
  38. package/types/cookies.d.ts +32 -84
  39. package/types/diagnostics.d.ts +56 -0
  40. package/types/frames/client.d.ts +1 -1
  41. package/types/frames/frame-client.d.ts +323 -259
  42. package/types/frames/frame-container-plugin.d.ts +72 -0
  43. package/types/frames/frame-sink.d.ts +101 -158
  44. package/types/frames/frame-transport.d.ts +192 -190
  45. package/types/frames/serializer-decode.d.ts +219 -0
  46. package/types/frames/serializer.d.ts +76 -157
  47. package/types/frames/server.d.ts +1 -1
  48. package/types/head.d.ts +19 -0
  49. package/types/index.d.ts +52 -80
  50. package/types/index.server.d.ts +174 -0
  51. package/types/jsx.d.ts +33 -35
  52. package/types/observe.d.ts +358 -0
  53. package/types/reconcile.d.ts +1 -0
  54. package/types/render.d.ts +9 -0
  55. package/types/response.d.ts +75 -150
  56. package/types/serializer-decode.d.ts +149 -112
  57. package/types/serializer.d.ts +76 -157
  58. package/types/server-functions/client.d.ts +192 -194
  59. package/types/server-functions/flash.d.ts +28 -30
  60. package/types/server-functions/registry.d.ts +102 -0
  61. package/types/server-functions/rich-args.d.ts +1 -10
  62. package/types/server-functions/server.d.ts +511 -475
  63. package/types/server-functions/shared.d.ts +366 -425
  64. package/types/server-mock.d.ts +110 -13
  65. package/types/server-observe.d.ts +77 -0
  66. package/types/server.d.ts +425 -425
  67. package/types/trace.d.ts +127 -0
  68. package/LICENSE +0 -21
  69. package/dist/web.cjs +0 -2008
  70. package/frames/dist/client.cjs +0 -1916
  71. package/frames/dist/server.cjs +0 -3756
  72. package/serialization/dist/decode.cjs +0 -122
  73. package/serialization/dist/serialization.cjs +0 -244
  74. package/serialization/types-cjs/index.d.cts +0 -182
  75. package/serialization/types-cjs/package.json +0 -3
  76. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  77. package/server-functions/dist/client.cjs +0 -793
  78. package/server-functions/dist/rich-args.cjs +0 -11
  79. package/server-functions/dist/server.cjs +0 -1171
  80. package/server-functions/dist/server.dev.cjs +0 -1171
  81. package/storage/dist/storage.cjs +0 -12
  82. package/storage/types-cjs/index.d.cts +0 -28
  83. package/storage/types-cjs/package.json +0 -3
  84. package/types/core.d.ts +0 -6
  85. package/types-cjs/client.d.cts +0 -337
  86. package/types-cjs/cookies.d.cts +0 -93
  87. package/types-cjs/core.d.cts +0 -6
  88. package/types-cjs/frames/client.d.cts +0 -36
  89. package/types-cjs/frames/frame-client.d.cts +0 -338
  90. package/types-cjs/frames/frame-sink.d.cts +0 -194
  91. package/types-cjs/frames/frame-transport.d.cts +0 -222
  92. package/types-cjs/frames/serializer.d.cts +0 -182
  93. package/types-cjs/frames/server.d.cts +0 -52
  94. package/types-cjs/index.d.cts +0 -244
  95. package/types-cjs/jsx-properties.d.cts +0 -93
  96. package/types-cjs/jsx.d.cts +0 -4159
  97. package/types-cjs/package.json +0 -3
  98. package/types-cjs/response.d.cts +0 -174
  99. package/types-cjs/serializer-decode.d.cts +0 -182
  100. package/types-cjs/serializer.d.cts +0 -182
  101. package/types-cjs/server-functions/client.d.cts +0 -231
  102. package/types-cjs/server-functions/flash.d.cts +0 -38
  103. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  104. package/types-cjs/server-functions/server.d.cts +0 -616
  105. package/types-cjs/server-functions/shared.d.cts +0 -523
  106. package/types-cjs/server-mock.d.cts +0 -277
  107. package/types-cjs/server.d.cts +0 -523
@@ -1,4 +1,15 @@
1
1
  import { sharedConfig } from 'solid-js';
2
+ import { 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,232 @@ 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 TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
27
+ const ZERO_TRACE = "00000000000000000000000000000000";
28
+ const ZERO_SPAN = "0000000000000000";
29
+ function parseTraceparent(value) {
30
+ if (!value) return undefined;
31
+ const m = TRACEPARENT.exec(value.trim());
32
+ if (!m) return undefined;
33
+ const [, version, traceId, parentId, flags, rest] = m;
34
+ if (version === "ff") return undefined;
35
+ if (version === "00" && rest !== undefined) return undefined;
36
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
37
+ return {
38
+ traceId,
39
+ parentId,
40
+ sampled: (parseInt(flags, 16) & 1) === 1
41
+ };
42
+ }
43
+ function randomHex(bytes) {
44
+ const buffer = new Uint8Array(bytes);
45
+ crypto.getRandomValues(buffer);
46
+ let out = "";
47
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
48
+ return out;
49
+ }
50
+ function randomTraceId() {
51
+ let id = randomHex(16);
52
+ while (id === ZERO_TRACE) id = randomHex(16);
53
+ return id;
54
+ }
55
+ function randomSpanId() {
56
+ let id = randomHex(8);
57
+ while (id === ZERO_SPAN) id = randomHex(8);
58
+ return id;
59
+ }
60
+ function formatTraceparent(context) {
61
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
62
+ }
63
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
64
+ function records$1() {
65
+ const g = globalThis;
66
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
67
+ }
68
+ function traceFor(key, request) {
69
+ const store = records$1();
70
+ let record = store.get(key);
71
+ if (record) return record;
72
+ const headers = request ? request.headers : undefined;
73
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
74
+ const context = {
75
+ traceId: incoming ? incoming.traceId : randomTraceId(),
76
+ spanId: randomSpanId(),
77
+ entries: {}
78
+ };
79
+ if (incoming) {
80
+ context.parentId = incoming.parentId;
81
+ context.sampled = incoming.sampled;
82
+ }
83
+ if (headers) {
84
+ const state = headers.get("tracestate");
85
+ if (state) context.state = state;
86
+ const baggage = headers.get("baggage");
87
+ if (baggage) context.baggage = baggage;
88
+ }
89
+ let answered = false;
90
+ context.entries.traceparent = formatTraceparent(context);
91
+ record = {
92
+ context,
93
+ emit: incoming !== undefined && incoming.sampled || answered,
94
+ timing: []
95
+ };
96
+ store.set(key, record);
97
+ return record;
98
+ }
99
+ function traceForEvent(event) {
100
+ return traceFor(event.request || event, event.request);
101
+ }
102
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
103
+ function splitServerTiming(value) {
104
+ const entries = [];
105
+ let start = 0;
106
+ let quoted = false;
107
+ for (let i = 0; i < value.length; i++) {
108
+ const c = value[i];
109
+ if (quoted) {
110
+ if (c === "\\") i++;else if (c === '"') quoted = false;
111
+ } else if (c === '"') quoted = true;else if (c === ",") {
112
+ entries.push(value.slice(start, i));
113
+ start = i + 1;
114
+ }
115
+ }
116
+ entries.push(value.slice(start));
117
+ return entries;
118
+ }
119
+ function metricName(entry) {
120
+ return entry.split(";")[0].trim().toLowerCase();
121
+ }
122
+ function namesOnServerTiming(headers) {
123
+ const names = new Set();
124
+ const existing = headers.get("server-timing");
125
+ if (existing) {
126
+ for (const entry of splitServerTiming(existing)) {
127
+ const name = metricName(entry);
128
+ if (name) names.add(name);
129
+ }
130
+ }
131
+ return names;
132
+ }
133
+ function quoteDesc(value) {
134
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
135
+ }
136
+ function shellMs(record) {
137
+ return record.render !== undefined ? record.render.shellMs : undefined;
138
+ }
139
+ function hasServerTiming(record) {
140
+ return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
141
+ }
142
+ function appendTraceServerTiming(headers, record) {
143
+ if (record.emit) {
144
+ const entries = record.context.entries;
145
+ let present;
146
+ for (const name in entries) {
147
+ if (!TOKEN.test(name)) continue;
148
+ if (!present) present = namesOnServerTiming(headers);
149
+ if (present.has(name.toLowerCase())) continue;
150
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
151
+ present.add(name.toLowerCase());
152
+ }
153
+ }
154
+ const shell = shellMs(record);
155
+ if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
156
+ for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
157
+ }
158
+ function metricOf(work) {
159
+ if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
160
+ const boundary = work.event;
161
+ return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
162
+ }
163
+ function formatMetric(name, dur, desc) {
164
+ let out = `${name};dur=${Math.round(dur * 10) / 10}`;
165
+ if (desc) out += `;desc="${quoteDesc(desc)}"`;
166
+ return out;
167
+ }
168
+ function mergeServerTiming(target, value) {
169
+ const present = namesOnServerTiming(target);
170
+ for (const entry of splitServerTiming(value)) {
171
+ const trimmed = entry.trim();
172
+ const name = metricName(trimmed);
173
+ if (!name || present.has(name)) continue;
174
+ target.append("Server-Timing", trimmed);
175
+ }
176
+ }
177
+
178
+ function records() {
179
+ return undefined;
180
+ }
181
+ function settledPromise(value) {
182
+ if (value instanceof Promise) return value;
183
+ try {
184
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
185
+ } catch {}
186
+ return undefined;
187
+ }
188
+ function isDeferredBody(value) {
189
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
190
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
191
+ const v = value;
192
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
193
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
194
+ }
195
+
196
+ function timesServerWork(type) {
197
+ const channel = records();
198
+ if (channel === undefined) return false;
199
+ return channel.observed(type);
200
+ }
201
+ function deliver(context, at, boundary, outcome, value) {
202
+ const record = {
203
+ id: context.id,
204
+ direct: context.direct,
205
+ at,
206
+ durationMs: performance.now() - at,
207
+ outcome
208
+ };
209
+ if (boundary !== undefined) record.boundary = boundary;
210
+ if (outcome === "ok" && isDeferredBody(value)) record.deferred = true;
211
+ traceForEvent(context.event).timing.push({
212
+ type: "invocation",
213
+ event: record
214
+ });
215
+ const channel = records();
216
+ if (!channel.observed("invocation")) return;
217
+ const live = {
218
+ event: context.event,
219
+ args: context.args
220
+ };
221
+ if (context.request !== undefined) live.request = context.request;
222
+ if (outcome === "ok") live.result = value;else live.error = value;
223
+ channel.emit("invocation", record, live);
224
+ }
225
+ function observeInvocation(context, execute) {
226
+ if (!timesServerWork("invocation")) return execute();
227
+ const at = performance.now();
228
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
229
+ let result;
230
+ try {
231
+ result = execute();
232
+ } catch (error) {
233
+ deliver(context, at, boundary, "error", error);
234
+ throw error;
235
+ }
236
+ const promised = settledPromise(result);
237
+ if (promised !== undefined) {
238
+ return promised.then(value => {
239
+ deliver(context, at, boundary, "ok", value);
240
+ return value;
241
+ }, error => {
242
+ deliver(context, at, boundary, "error", error);
243
+ throw error;
244
+ });
245
+ }
246
+ deliver(context, at, boundary, "ok", result);
247
+ return result;
248
+ }
12
249
 
13
250
  const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
14
251
  function getServerFunctionMetadata(fn) {
@@ -26,6 +263,32 @@ function withMeta(fn, meta) {
26
263
  Object.assign(metadata, meta);
27
264
  return fn;
28
265
  }
266
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
267
+ const INVOKE_OPTION_REDIRECTS = {
268
+ 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.",
269
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
270
+ body: "The arguments are the body: pass them in the args array.",
271
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
272
+ };
273
+ function invoke(fn, options, ...args) {
274
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
275
+ if (!channel) {
276
+ 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.");
277
+ }
278
+ if (options === null || typeof options !== "object") {
279
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
280
+ }
281
+ const picked = {};
282
+ for (const key in options) {
283
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
284
+ 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."));
285
+ }
286
+ }
287
+ if (options.signal !== undefined) picked.signal = options.signal;
288
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
289
+ if (options.priority !== undefined) picked.priority = options.priority;
290
+ return channel(args, picked);
291
+ }
29
292
  const LIVE_SOURCE = Symbol.for("solid.LiveSource");
30
293
  const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
31
294
  function provideServerFunctionRPC(rpc) {
@@ -62,6 +325,7 @@ function serializeCookie(name, value, options = {}) {
62
325
  if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
63
326
  if (options.httpOnly) cookie += "; HttpOnly";
64
327
  if (options.secure) cookie += "; Secure";
328
+ if (options.partitioned) cookie += "; Partitioned";
65
329
  if (options.sameSite) {
66
330
  const sameSite = options.sameSite.toLowerCase();
67
331
  cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
@@ -86,11 +350,141 @@ function configureServerFunctionsCodec(codec) {
86
350
  function getServerFunctionsCodec() {
87
351
  return codecConfig.codec;
88
352
  }
89
- function subscribeFlightData(consumer) {
353
+ const UNNAMED_FLIGHT_SOURCE = "true";
354
+ const flightConfig = {
355
+ consumers: new Map()
356
+ };
357
+ function assertFlightSource(source) {
358
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
359
+ 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).`);
360
+ }
361
+ }
362
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
363
+ const named = typeof sourceOrConsumer === "string";
364
+ if (named) assertFlightSource(sourceOrConsumer);
365
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
366
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
367
+ flightConfig.consumers.set(source, consumer);
90
368
  return () => {
369
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
91
370
  };
92
371
  }
93
- const FUNCTION_HEADER = "X-Server-Function-Id";
372
+ function frameAddress(id, args) {
373
+ return args && args.length ? id + ":" + hashArguments(args) : id;
374
+ }
375
+ function hashArguments(args) {
376
+ let hash = 0;
377
+ const text = stableString(args);
378
+ for (let i = 0; i < text.length; i++) {
379
+ hash = (hash << 5) - hash + text.charCodeAt(i);
380
+ hash |= 0;
381
+ }
382
+ return (hash >>> 0).toString(36);
383
+ }
384
+ function stableString(value, seen) {
385
+ if (value === null || typeof value !== "object") {
386
+ return typeof value === "bigint" ? value + "n" : String(value);
387
+ }
388
+ if (value instanceof Date) return "Date:" + value.getTime();
389
+ seen || (seen = new Set());
390
+ if (seen.has(value)) return "~";
391
+ seen.add(value);
392
+ if (value instanceof Map) {
393
+ const entries = [];
394
+ for (const [k, v] of value) {
395
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
396
+ }
397
+ return "Map{" + entries.sort().join(",") + "}";
398
+ }
399
+ if (value instanceof Set) {
400
+ const members = [];
401
+ for (const v of value) members.push(stableString(v, seen));
402
+ return "Set{" + members.sort().join(",") + "}";
403
+ }
404
+ if (Array.isArray(value)) {
405
+ let out = "[";
406
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
407
+ return out + "]";
408
+ }
409
+ const keys = Object.keys(value).sort();
410
+ let out = "{";
411
+ for (let i = 0; i < keys.length; i++) {
412
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
413
+ }
414
+ return out + "}";
415
+ }
416
+ function serverFunctionAddress(endpoint, id) {
417
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
418
+ return `${mount}/${encodeURIComponent(id)}`;
419
+ }
420
+ function serverFunctionDataAddress(endpoint, id) {
421
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
422
+ return `${mount}/data/${encodeURIComponent(id)}`;
423
+ }
424
+ function serverFunctionLiveAddress(endpoint, id) {
425
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
426
+ return `${mount}/live/${encodeURIComponent(id)}`;
427
+ }
428
+ function parseServerFunctionAddress(pathname, endpoint) {
429
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
430
+ if (!pathname.startsWith(mount)) return null;
431
+ const rest = pathname.slice(mount.length);
432
+ if (!rest.startsWith("/")) return null;
433
+ let segment = rest.slice(1);
434
+ let data = false;
435
+ let live = false;
436
+ if (segment.startsWith("data/")) {
437
+ segment = segment.slice(5);
438
+ data = true;
439
+ } else if (segment.startsWith("live/")) {
440
+ segment = segment.slice(5);
441
+ live = true;
442
+ }
443
+ if (!segment || segment.includes("/")) return null;
444
+ try {
445
+ return {
446
+ id: decodeURIComponent(segment),
447
+ data,
448
+ live
449
+ };
450
+ } catch {
451
+ return null;
452
+ }
453
+ }
454
+ const MAX_GET_URL_LENGTH = 2000;
455
+ function urlTargetId(target, helper) {
456
+ if (typeof target === "string") return target;
457
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
458
+ throw new Error(`${helper} expects a server function reference (or its id).`);
459
+ }
460
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
461
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
462
+ if (!boundArgs.length) return address;
463
+ if (!isJSONSafe(boundArgs)) {
464
+ 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.");
465
+ }
466
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
467
+ }
468
+ function serverFunctionUrlFor(endpoint, fn, args) {
469
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
470
+ throw new Error("serverFunctionUrl expects a server function reference.");
471
+ }
472
+ const metadata = getServerFunctionMetadata(fn);
473
+ if (!metadata || metadata.method !== "GET") {
474
+ 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).');
475
+ }
476
+ const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
477
+ if (!args.length) return address;
478
+ if (!isJSONSafe(args)) {
479
+ 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.");
480
+ }
481
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
482
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
483
+ if (length > MAX_GET_URL_LENGTH) {
484
+ 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.");
485
+ }
486
+ return url;
487
+ }
94
488
  const ERROR_HEADER = "X-Server-Function-Error";
95
489
  const ERROR_HEADER_MARKER = "=?1?";
96
490
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -116,8 +510,30 @@ function decodeErrorHeaderValue(value) {
116
510
  return value;
117
511
  }
118
512
  }
119
- const INSTANCE_HEADER = "X-Server-Function-Instance";
120
513
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
514
+ const LAST_EVENT_ID_HEADER = "Last-Event-ID";
515
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
516
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
517
+ function decodeRedirectHeaderValue(value) {
518
+ if (typeof value !== "string") return undefined;
519
+ const at = value.indexOf(" ");
520
+ if (at < 0) return undefined;
521
+ const status = Number(value.slice(0, at));
522
+ const url = value.slice(at + 1);
523
+ if (!Number.isInteger(status) || !url) return undefined;
524
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
525
+ let parsed;
526
+ try {
527
+ parsed = new URL(url);
528
+ } catch {
529
+ return undefined;
530
+ }
531
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
532
+ return {
533
+ status,
534
+ url
535
+ };
536
+ }
121
537
  const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
122
538
  const FILE_FORM_KEY = "__server_function_file__";
123
539
  const BodyFormat = {
@@ -129,7 +545,8 @@ const BodyFormat = {
129
545
  File: "5",
130
546
  ArrayBuffer: "6",
131
547
  Uint8Array: "7",
132
- Json: "8"
548
+ Json: "8",
549
+ Void: "9"
133
550
  };
134
551
  const JSON_SAFE_DEPTH_LIMIT = 4096;
135
552
  const EXIT = {};
@@ -146,7 +563,7 @@ function isJSONSafe(value) {
146
563
  const t = typeof v;
147
564
  if (t === "string" || t === "boolean") continue;
148
565
  if (t === "number") {
149
- if (!Number.isFinite(v)) return false;
566
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
150
567
  continue;
151
568
  }
152
569
  if (t !== "object") return false;
@@ -159,7 +576,11 @@ function isJSONSafe(value) {
159
576
  const proto = Object.getPrototypeOf(v);
160
577
  if (proto !== Object.prototype && proto !== null) return false;
161
578
  if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
162
- for (const k in v) stack.push(v[k]);
579
+ for (const k in v) {
580
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
581
+ if (descriptor === undefined || !("value" in descriptor)) return false;
582
+ stack.push(descriptor.value);
583
+ }
163
584
  }
164
585
  }
165
586
  return true;
@@ -225,34 +646,33 @@ function getHeadersAndBody(body) {
225
646
  return undefined;
226
647
  }
227
648
  }
228
- async function extractBody(source, codecOptions) {
649
+ async function extractBody(source, codecOptions, wire) {
229
650
  const contentType = source.headers.get("content-type");
230
651
  const format = source.headers.get(BODY_FORMAT_HEADER);
231
- const clone = source.clone();
232
652
  switch (true) {
233
653
  case format === BodyFormat.Serialized:
234
- return await deserializeStream(clone, codecOptions);
654
+ return await deserializeStream(source, codecOptions);
235
655
  case format === BodyFormat.Json:
236
- return JSON.parse(await clone.text());
656
+ return JSON.parse(await source.text());
237
657
  case format === BodyFormat.String:
238
- return await clone.text();
658
+ return await source.text();
239
659
  case format === BodyFormat.File:
240
660
  {
241
- const formData = await clone.formData();
661
+ const formData = await source.formData();
242
662
  return formData.get(FILE_FORM_KEY);
243
663
  }
244
664
  case format === BodyFormat.FormData:
245
665
  case contentType && contentType.startsWith("multipart/form-data"):
246
- return await clone.formData();
666
+ return await source.formData();
247
667
  case format === BodyFormat.URLSearchParams:
248
668
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
249
- return new URLSearchParams(await clone.text());
669
+ return new URLSearchParams(await source.text());
250
670
  case format === BodyFormat.Blob:
251
- return await clone.blob();
671
+ return await source.blob();
252
672
  case format === BodyFormat.ArrayBuffer:
253
- return await clone.arrayBuffer();
673
+ return await source.arrayBuffer();
254
674
  case format === BodyFormat.Uint8Array:
255
- return new Uint8Array(await clone.arrayBuffer());
675
+ return new Uint8Array(await source.arrayBuffer());
256
676
  }
257
677
  return undefined;
258
678
  }
@@ -268,18 +688,34 @@ function createChunk(data) {
268
688
  class ChunkReader {
269
689
  constructor(stream) {
270
690
  this.reader = stream.getReader();
271
- this.buffer = new Uint8Array(0);
691
+ this.store = new Uint8Array(0);
692
+ this.buffer = this.store;
272
693
  this.done = false;
273
694
  }
274
695
  async readChunk() {
275
696
  const chunk = await this.reader.read();
276
- if (!chunk.done) {
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 {
697
+ if (chunk.done) {
282
698
  this.done = true;
699
+ return;
700
+ }
701
+ const incoming = chunk.value;
702
+ const store = this.store;
703
+ const start = this.buffer.byteOffset;
704
+ const end = start + this.buffer.length;
705
+ const needed = this.buffer.length + incoming.length;
706
+ if (end + incoming.length <= store.length) {
707
+ store.set(incoming, end);
708
+ this.buffer = store.subarray(start, end + incoming.length);
709
+ } else if (needed <= store.length) {
710
+ store.copyWithin(0, start, end);
711
+ store.set(incoming, this.buffer.length);
712
+ this.buffer = store.subarray(0, needed);
713
+ } else {
714
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
715
+ grown.set(this.buffer);
716
+ grown.set(incoming, this.buffer.length);
717
+ this.store = grown;
718
+ this.buffer = grown.subarray(0, needed);
283
719
  }
284
720
  }
285
721
  async next() {
@@ -320,22 +756,99 @@ class ChunkReader {
320
756
  interpret(result.value);
321
757
  }
322
758
  }
759
+ cancel(reason) {
760
+ return this.reader.cancel(reason);
761
+ }
762
+ }
763
+ function createEventChunk(data, id) {
764
+ let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
765
+ for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
766
+ return new TextEncoder().encode(event + "\n");
767
+ }
768
+ const EVENT_STREAM_HEARTBEAT = new TextEncoder().encode(":\n\n");
769
+ function positionDigest(value) {
770
+ if (value === undefined || !isJSONSafe(value)) return undefined;
771
+ const text = JSON.stringify(value);
772
+ if (typeof text !== "string") return undefined;
773
+ return textDigest(text);
774
+ }
775
+ function textDigest(text) {
776
+ let a = 0x811c9dc5;
777
+ let b = 0x050c5d1f;
778
+ for (let i = 0; i < text.length; i++) {
779
+ const code = text.charCodeAt(i);
780
+ a = Math.imul(a ^ code, 0x01000193);
781
+ b = Math.imul(b ^ code, 0x01000193);
782
+ }
783
+ return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
784
+ }
785
+ const ERROR_TRAILER_PREFIX = "!";
786
+ function encodeErrorTrailer(error) {
787
+ const shaped = error instanceof Error ? error : new Error(String(error));
788
+ return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
789
+ name: shaped.name,
790
+ message: shaped.message
791
+ } : {
792
+ message: shaped.message
793
+ });
794
+ }
795
+ function errorFromTrailer(payload) {
796
+ let shape;
797
+ try {
798
+ shape = JSON.parse(payload.slice(1));
799
+ } catch {
800
+ shape = null;
801
+ }
802
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
803
+ if (shape && typeof shape.name === "string") error.name = shape.name;
804
+ return error;
805
+ }
806
+ function serializeStream(value, codecOptions) {
807
+ return new ReadableStream({
808
+ async start(controller) {
809
+ const {
810
+ serializeJSON
811
+ } = await import('@solidjs/web/serialization');
812
+ serializeJSON(value, {
813
+ ...codecOptions,
814
+ onParse(node) {
815
+ controller.enqueue(createChunk(JSON.stringify(node)));
816
+ },
817
+ onDone() {
818
+ controller.close();
819
+ },
820
+ onError(error) {
821
+ controller.error(error);
822
+ }
823
+ });
824
+ }
825
+ });
323
826
  }
324
- async function deserializeStream(source, codecOptions) {
827
+ async function deserializeStream(source, codecOptions, wire) {
325
828
  if (!source.body) {
326
829
  throw new Error("missing body");
327
830
  }
328
831
  const reader = new ChunkReader(source.body);
329
832
  const result = await reader.next();
330
833
  if (!result.done) {
834
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
835
+ throw errorFromTrailer(result.value);
836
+ }
331
837
  const {
332
838
  createJSONDeserializer
333
839
  } = await import('@solidjs/web/serialization/decode');
334
840
  const deserializeChunk = createJSONDeserializer(codecOptions);
335
841
  function interpretChunk(chunk) {
842
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
843
+ throw errorFromTrailer(chunk);
844
+ }
336
845
  return deserializeChunk(JSON.parse(chunk));
337
846
  }
338
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
847
+ const end = error => {
848
+ const sweep = () => deserializeChunk.abort(error);
849
+ sweep();
850
+ };
851
+ reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
339
852
  return interpretChunk(result.value);
340
853
  }
341
854
  return undefined;
@@ -345,7 +858,7 @@ async function deserializeString(text, codecOptions) {
345
858
  }
346
859
  async function decodeResponse(response, codecOptions) {
347
860
  if (!response.body) return undefined;
348
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
861
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
349
862
  }
350
863
  async function decodeResponsePayload(response, codecOptions) {
351
864
  const decoded = await decodeResponse(response, codecOptions);
@@ -360,20 +873,37 @@ async function decodeResponsePayload(response, codecOptions) {
360
873
  };
361
874
  }
362
875
 
876
+ typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
363
877
  const RequestContext = Symbol.for("solid.RequestContext");
364
878
  function getRequestEvent() {
365
879
  return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && 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;
366
880
  }
881
+ function peekRequestEvent() {
882
+ const store = globalThis[RequestContext];
883
+ return store ? store.getStore() : undefined;
884
+ }
885
+ function traceForStub(stub, event) {
886
+ if (!event) {
887
+ event = peekRequestEvent();
888
+ if (!event || event.response !== stub) return undefined;
889
+ }
890
+ return traceForEvent(event);
891
+ }
367
892
  function reportLostHeaderWrite(method, name) {
368
- 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).";
893
+ 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).";
369
894
  console.error(message);
370
895
  }
371
896
  function commitResponseStub(stub, {
372
- allowLateLocation = false
897
+ allowLateLocation = false,
898
+ event
373
899
  } = {}) {
374
900
  if (!stub || stub.committed) return stub;
375
- stub.committed = true;
376
901
  const headers = stub.headers;
902
+ if (headers && typeof headers.append === "function") {
903
+ const trace = traceForStub(stub, event);
904
+ if (trace) appendTraceServerTiming(headers, trace);
905
+ }
906
+ stub.committed = true;
377
907
  if (!headers || typeof headers.set !== "function") return stub;
378
908
  for (const method of ["set", "append", "delete"]) {
379
909
  const original = headers[method].bind(headers);
@@ -395,7 +925,8 @@ function copyInitHeaders(init) {
395
925
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
396
926
  return headers;
397
927
  }
398
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
928
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
929
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
399
930
  function fillsStubGap(key, headers, response) {
400
931
  if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
401
932
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
@@ -403,34 +934,106 @@ function fillsStubGap(key, headers, response) {
403
934
  }
404
935
  function commitEventResponse(response, event = getRequestEvent()) {
405
936
  const stub = event && event.response;
406
- if (!stub || !stub.headers || stub.committed) return response;
407
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
408
- commitResponseStub(stub);
409
- let hasGaps = false;
410
- stub.headers.forEach((value, key) => {
411
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
412
- });
413
- if (!cookies.length && !hasGaps) return response;
414
- try {
415
- for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
416
- stub.headers.forEach((value, key) => {
417
- if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
418
- });
419
- return response;
420
- } catch {
937
+ if (!stub || !stub.headers || stub.committed) {
938
+ if (!event || stub) return response;
939
+ const trace = traceForEvent(event);
940
+ if (!hasServerTiming(trace)) return response;
421
941
  const headers = copyInitHeaders(response.headers);
422
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
423
- stub.headers.forEach((value, key) => {
424
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
425
- });
942
+ appendTraceServerTiming(headers, trace);
426
943
  return new Response(response.body, {
427
944
  status: response.status,
428
945
  statusText: response.statusText,
429
946
  headers
430
947
  });
431
948
  }
949
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
950
+ commitResponseStub(stub, {
951
+ event
952
+ });
953
+ let hasGaps = false;
954
+ stub.headers.forEach((value, key) => {
955
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
956
+ });
957
+ const timing = stub.headers.get("server-timing");
958
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
959
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
960
+ const headers = copyInitHeaders(response.headers);
961
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
962
+ stub.headers.forEach((value, key) => {
963
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
964
+ });
965
+ if (mergesTiming) mergeServerTiming(headers, timing);
966
+ return new Response(response.body, {
967
+ status: response.status,
968
+ statusText: response.statusText,
969
+ headers
970
+ });
432
971
  }
433
972
 
973
+ let configuredSecret;
974
+ function setFlashSecret(secret) {
975
+ configuredSecret = secret;
976
+ }
977
+ function resolveSecret() {
978
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
979
+ }
980
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
981
+ const FLASH_KEY_ITERATIONS = 100_000;
982
+ let cachedSecret;
983
+ let cachedKey;
984
+ function resolveFlashKey() {
985
+ const secret = resolveSecret();
986
+ if (typeof secret !== "string" || secret.length === 0) return null;
987
+ if (secret !== cachedSecret) {
988
+ cachedSecret = secret;
989
+ const encoder = new TextEncoder();
990
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
991
+ name: "PBKDF2",
992
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
993
+ iterations: FLASH_KEY_ITERATIONS,
994
+ hash: "SHA-256"
995
+ }, material, {
996
+ name: "AES-GCM",
997
+ length: 256
998
+ }, false, ["encrypt", "decrypt"]));
999
+ }
1000
+ return cachedKey;
1001
+ }
1002
+ const FLASH_FORMAT_VERSION = "1.";
1003
+ const IV_BYTES = 12;
1004
+ const GCM_TAG_BYTES = 16;
1005
+ function toBase64url(bytes) {
1006
+ let binary = "";
1007
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1008
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1009
+ }
1010
+ function fromBase64url(text) {
1011
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
1012
+ const bytes = new Uint8Array(binary.length);
1013
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1014
+ return bytes;
1015
+ }
1016
+ async function encryptFlashValue(key, json) {
1017
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
1018
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
1019
+ name: "AES-GCM",
1020
+ iv
1021
+ }, key, new TextEncoder().encode(json)));
1022
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
1023
+ packed.set(iv);
1024
+ packed.set(ciphertext, IV_BYTES);
1025
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
1026
+ }
1027
+ async function decryptFlashValue(key, value) {
1028
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
1029
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
1030
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
1031
+ const plain = await crypto.subtle.decrypt({
1032
+ name: "AES-GCM",
1033
+ iv: packed.subarray(0, IV_BYTES)
1034
+ }, key, packed.subarray(IV_BYTES));
1035
+ return new TextDecoder().decode(plain);
1036
+ }
434
1037
  function encodeInputValue(value) {
435
1038
  if (value instanceof FormData) return {
436
1039
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -451,7 +1054,11 @@ function decodeInputValue(value) {
451
1054
  }
452
1055
  return value;
453
1056
  }
454
- function encodeFlashCookie(url, result, input, thrown) {
1057
+ async function encodeFlashCookie(url, result, input, thrown) {
1058
+ const key = resolveFlashKey();
1059
+ if (!key) {
1060
+ return null;
1061
+ }
455
1062
  const isError = result instanceof Error;
456
1063
  const payload = {
457
1064
  url,
@@ -460,26 +1067,62 @@ function encodeFlashCookie(url, result, input, thrown) {
460
1067
  thrown: !!thrown,
461
1068
  input: input.map(encodeInputValue)
462
1069
  };
463
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
1070
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
1071
+ payload.truncated = true;
1072
+ payload.input = [];
1073
+ if (!fitsCookie(payload)) {
1074
+ if (typeof payload.result === "string") {
1075
+ let prefix = payload.result;
1076
+ while (prefix.length > 0 && !fitsCookie({
1077
+ ...payload,
1078
+ result: prefix
1079
+ })) {
1080
+ prefix = prefix.slice(0, prefix.length >> 1);
1081
+ }
1082
+ payload.result = prefix.length > 0 ? prefix : true;
1083
+ } else {
1084
+ payload.result = true;
1085
+ }
1086
+ }
1087
+ if (!fitsCookie(payload)) return null;
1088
+ return flashCookie(payload, await key);
1089
+ }
1090
+ const FLASH_MAX_AGE_SECONDS = 60;
1091
+ async function flashCookie(payload, key) {
1092
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
464
1093
  secure: true,
465
- httpOnly: true
1094
+ httpOnly: true,
1095
+ sameSite: "lax",
1096
+ maxAge: FLASH_MAX_AGE_SECONDS
466
1097
  });
467
1098
  }
468
- function decodeFlashCookie(cookieHeader) {
1099
+ const COOKIE_PAIR_BUDGET = 4000;
1100
+ function fitsCookie(payload) {
1101
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
1102
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
1103
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
1104
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
1105
+ }
1106
+ async function decodeFlashCookie(cookieHeader) {
469
1107
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
470
1108
  if (!match) return;
471
1109
  try {
472
- const payload = JSON.parse(match);
473
- if (!payload || !payload.result) return;
1110
+ const key = resolveFlashKey();
1111
+ if (!key) return;
1112
+ const json = await decryptFlashValue(await key, match);
1113
+ if (json === undefined) return;
1114
+ const payload = JSON.parse(json);
1115
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
474
1116
  const result = payload.error ? new Error(payload.result) : payload.result;
475
- return {
1117
+ const submission = {
476
1118
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
477
1119
  url: payload.url,
478
1120
  result: payload.thrown ? undefined : result,
479
1121
  error: payload.thrown ? result : undefined
480
1122
  };
1123
+ if (payload.truncated) submission.truncated = true;
1124
+ return submission;
481
1125
  } catch (error) {
482
- console.error(error);
483
1126
  }
484
1127
  }
485
1128
 
@@ -491,7 +1134,11 @@ const config = {
491
1134
  transformFlightResult: undefined,
492
1135
  transformDirectResult: undefined,
493
1136
  handleNoJS: undefined,
494
- endpoint: "/_server"
1137
+ endpoint: "/_server",
1138
+ csrf: true,
1139
+ bodySizeLimit: 1_048_576,
1140
+ maxArguments: 1000,
1141
+ chaosReconnectEvery: 0
495
1142
  };
496
1143
  function configureServerFunctionsServer({
497
1144
  provideEvent,
@@ -502,7 +1149,12 @@ function configureServerFunctionsServer({
502
1149
  transformDirectResult,
503
1150
  handleNoJS,
504
1151
  endpoint,
505
- codec
1152
+ csrf,
1153
+ codec,
1154
+ bodySizeLimit,
1155
+ maxArguments,
1156
+ secret,
1157
+ chaosReconnectEvery
506
1158
  } = {}) {
507
1159
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
508
1160
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -512,7 +1164,24 @@ function configureServerFunctionsServer({
512
1164
  if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
513
1165
  if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
514
1166
  if (endpoint !== undefined) config.endpoint = endpoint;
1167
+ if (csrf !== undefined) config.csrf = csrf;
515
1168
  if (codec !== undefined) configureServerFunctionsCodec(codec);
1169
+ if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
1170
+ if (maxArguments !== undefined) config.maxArguments = maxArguments;
1171
+ if (secret !== undefined) setFlashSecret(secret);
1172
+ if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
1173
+ }
1174
+ const flightSources = new Map();
1175
+ function registerFlightDataSource(source, hook) {
1176
+ assertFlightSource(source);
1177
+ flightSources.set(source, hook);
1178
+ return () => {
1179
+ if (flightSources.get(source) === hook) flightSources.delete(source);
1180
+ };
1181
+ }
1182
+ function resolveWrapInvocation(hook) {
1183
+ if (hook === undefined || typeof hook === "function") return hook;
1184
+ 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.`);
516
1185
  }
517
1186
  function provideEvent(event, fn) {
518
1187
  if (config.provideEvent) return config.provideEvent(event, fn);
@@ -520,8 +1189,193 @@ function provideEvent(event, fn) {
520
1189
  if (ctx) return ctx.run(event, fn);
521
1190
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
522
1191
  }
523
- const REGISTRATIONS = new Map();
524
- const METHODS = new Map();
1192
+ 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.";
1193
+ 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.";
1194
+ function provideEventOnce(provide, event, run) {
1195
+ let invocations = 0;
1196
+ const settle = () => {
1197
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
1198
+ };
1199
+ const result = provide(event, () => {
1200
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
1201
+ return run();
1202
+ });
1203
+ const promised = nativePromise(result);
1204
+ if (promised) {
1205
+ return promised.then(value => {
1206
+ settle();
1207
+ return value;
1208
+ });
1209
+ }
1210
+ settle();
1211
+ return result;
1212
+ }
1213
+ function scopeDeferredResult(value, scope) {
1214
+ const bound = bindDeferredBody(value, scope);
1215
+ if (bound !== value || value === null || typeof value !== "object") return bound;
1216
+ return scopeDeferredContents(value, scope);
1217
+ }
1218
+ class ScopeFrame {
1219
+ constructor(value, next, keys, descriptors) {
1220
+ this.value = value;
1221
+ this.next = next;
1222
+ this.keys = keys;
1223
+ this.descriptors = descriptors;
1224
+ this.i = 0;
1225
+ this.changed = false;
1226
+ }
1227
+ }
1228
+ function enterScopeCarrier(value, state) {
1229
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
1230
+ if (state.seen.has(value)) {
1231
+ state.cyclic.add(value);
1232
+ return state.seen.get(value);
1233
+ }
1234
+ const bound = bindDeferredBody(value, state.scope);
1235
+ if (bound !== value) {
1236
+ state.seen.set(value, bound);
1237
+ return bound;
1238
+ }
1239
+ if (typeof value !== "object") return value;
1240
+ if (Array.isArray(value)) {
1241
+ if (Object.isFrozen(value)) {
1242
+ state.seen.set(value, value);
1243
+ return value;
1244
+ }
1245
+ const next = value.slice();
1246
+ state.seen.set(value, next);
1247
+ return new ScopeFrame(value, next, null, null);
1248
+ }
1249
+ const prototype = Object.getPrototypeOf(value);
1250
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
1251
+ state.seen.set(value, value);
1252
+ return value;
1253
+ }
1254
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1255
+ const next = Object.create(prototype, descriptors);
1256
+ state.seen.set(value, next);
1257
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
1258
+ }
1259
+ function scopeDeferredContents(root, scope) {
1260
+ const state = {
1261
+ seen: new Map(),
1262
+ cyclic: new Set(),
1263
+ scope
1264
+ };
1265
+ const entered = enterScopeCarrier(root, state);
1266
+ if (!(entered instanceof ScopeFrame)) return entered;
1267
+ const stack = [entered];
1268
+ let delivered = NOTHING;
1269
+ for (;;) {
1270
+ const top = stack[stack.length - 1];
1271
+ const length = top.keys ? top.keys.length : top.value.length;
1272
+ let pushed = null;
1273
+ while (top.i < length) {
1274
+ const i = top.i;
1275
+ let original;
1276
+ let writable = true;
1277
+ if (top.keys) {
1278
+ const descriptor = top.descriptors[top.keys[i]];
1279
+ writable = "value" in descriptor && descriptor.writable === true;
1280
+ original = writable ? descriptor.value : undefined;
1281
+ } else {
1282
+ original = top.value[i];
1283
+ }
1284
+ if (!writable) {
1285
+ top.i++;
1286
+ continue;
1287
+ }
1288
+ let bound;
1289
+ if (delivered !== NOTHING) {
1290
+ bound = delivered;
1291
+ delivered = NOTHING;
1292
+ } else {
1293
+ bound = enterScopeCarrier(original, state);
1294
+ if (bound instanceof ScopeFrame) {
1295
+ pushed = bound;
1296
+ break;
1297
+ }
1298
+ }
1299
+ if (bound !== original) {
1300
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
1301
+ top.changed = true;
1302
+ }
1303
+ top.i++;
1304
+ }
1305
+ if (pushed !== null) {
1306
+ stack.push(pushed);
1307
+ continue;
1308
+ }
1309
+ stack.pop();
1310
+ let out;
1311
+ if (top.changed || state.cyclic.has(top.value)) {
1312
+ out = top.next;
1313
+ } else {
1314
+ state.seen.set(top.value, top.value);
1315
+ out = top.value;
1316
+ }
1317
+ if (stack.length === 0) return out;
1318
+ delivered = out;
1319
+ }
1320
+ }
1321
+ function bindDeferredBody(value, scope) {
1322
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
1323
+ const promised = scope(() => nativePromise(value));
1324
+ if (promised) {
1325
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
1326
+ }
1327
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1328
+ let reader;
1329
+ return new ReadableStream({
1330
+ async pull(controller) {
1331
+ try {
1332
+ const step = await scope(() => {
1333
+ if (!reader) reader = value.getReader();
1334
+ return reader.read();
1335
+ });
1336
+ if (step.done) controller.close();else controller.enqueue(step.value);
1337
+ } catch (error) {
1338
+ controller.error(error);
1339
+ }
1340
+ },
1341
+ cancel(reason) {
1342
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
1343
+ }
1344
+ }, {
1345
+ highWaterMark: 0
1346
+ });
1347
+ }
1348
+ const scopedIterator = symbol => ({
1349
+ [symbol]() {
1350
+ const iterator = scope(() => value[symbol]());
1351
+ return new Proxy(iterator, {
1352
+ get(target, property) {
1353
+ const member = Reflect.get(target, property, target);
1354
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
1355
+ }
1356
+ });
1357
+ }
1358
+ });
1359
+ if (typeof value[Symbol.asyncIterator] === "function") {
1360
+ return scopedIterator(Symbol.asyncIterator);
1361
+ }
1362
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1363
+ return scopedIterator(Symbol.iterator);
1364
+ }
1365
+ return value;
1366
+ }
1367
+ function processState(key, create) {
1368
+ const slot = Symbol.for(key);
1369
+ return globalThis[slot] || (globalThis[slot] = create());
1370
+ }
1371
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
1372
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1373
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
1374
+ const CARRIED = processState("solid.ServerFunctionCarriedGrants", () => new Set());
1375
+ function declaresRead(id) {
1376
+ const granted = METHODS.get(id);
1377
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
1378
+ }
525
1379
  const INVOCATIONS = new WeakMap();
526
1380
  let rpcProvided = false;
527
1381
  function provideRPC() {
@@ -534,6 +1388,15 @@ function provideRPC() {
534
1388
  }
535
1389
  function registerServerFunction(id, callback) {
536
1390
  provideRPC();
1391
+ if (REGISTRATIONS.get(id) !== callback) {
1392
+ if (DEV && declaresRead(id)) {
1393
+ METHODS.set(id, callback);
1394
+ CARRIED.add(id);
1395
+ } else {
1396
+ METHODS.delete(id);
1397
+ CARRIED.delete(id);
1398
+ }
1399
+ }
537
1400
  REGISTRATIONS.set(id, callback);
538
1401
  return callback;
539
1402
  }
@@ -545,6 +1408,9 @@ function getServerFunction(id) {
545
1408
  throw new Error("invalid server function: " + id);
546
1409
  }
547
1410
  function registerServerReference(id, fn, name) {
1411
+ if (typeof fn !== "function") {
1412
+ 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.`);
1413
+ }
548
1414
  registerServerFunction(id, fn);
549
1415
  return {
550
1416
  id,
@@ -552,6 +1418,33 @@ function registerServerReference(id, fn, name) {
552
1418
  name
553
1419
  };
554
1420
  }
1421
+ function inProcessInvoker(call) {
1422
+ return (args, options) => {
1423
+ const signal = options && options.signal;
1424
+ if (!signal) return call(...args);
1425
+ if (signal.aborted) return Promise.reject(signal.reason);
1426
+ return new Promise((resolve, reject) => {
1427
+ const onAbort = () => reject(signal.reason);
1428
+ signal.addEventListener("abort", onAbort, {
1429
+ once: true
1430
+ });
1431
+ let result;
1432
+ try {
1433
+ result = call(...args);
1434
+ } catch (error) {
1435
+ signal.removeEventListener("abort", onAbort);
1436
+ return reject(error);
1437
+ }
1438
+ Promise.resolve(result).then(value => {
1439
+ signal.removeEventListener("abort", onAbort);
1440
+ resolve(value);
1441
+ }, error => {
1442
+ signal.removeEventListener("abort", onAbort);
1443
+ reject(error);
1444
+ });
1445
+ });
1446
+ };
1447
+ }
555
1448
  function createServerReference({
556
1449
  id,
557
1450
  fn,
@@ -562,58 +1455,104 @@ function createServerReference({
562
1455
  const metadata = name === undefined ? {} : {
563
1456
  name
564
1457
  };
565
- return new Proxy(fn, {
1458
+ const invokeChannel = inProcessInvoker((...args) => proxy(...args));
1459
+ const proxy = new Proxy(fn, {
566
1460
  get(target, prop) {
567
1461
  if (prop === "id") return id;
568
1462
  if (prop === "url") {
569
- return `${config.endpoint}?id=${encodeURIComponent(id)}`;
1463
+ return serverFunctionAddress(config.endpoint, id);
570
1464
  }
571
1465
  if (prop === SERVER_FUNCTION_METADATA) return metadata;
1466
+ if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
572
1467
  return target[prop];
573
1468
  },
574
1469
  apply(target, thisArg, args) {
575
1470
  const ogEvt = getRequestEvent();
576
1471
  if (!ogEvt) throw new Error("Cannot call server function outside of a request");
577
1472
  const evt = {
578
- ...ogEvt
1473
+ ...ogEvt,
1474
+ locals: {
1475
+ ...ogEvt.locals
1476
+ }
579
1477
  };
580
1478
  INVOCATIONS.set(evt, {
581
- id
1479
+ id,
1480
+ live: false
582
1481
  });
583
1482
  evt.serverOnly = true;
584
- const result = provideEvent(evt, () => {
1483
+ const scope = run => provideEvent(evt, run);
1484
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1485
+ let result = provideEventOnce(provideEvent, evt, () => {
585
1486
  const run = () => fn.apply(thisArg, args);
586
- return config.wrapInvocation ? config.wrapInvocation(run, {
1487
+ return observeInvocation({
1488
+ id,
1489
+ direct: true,
1490
+ event: evt,
1491
+ args
1492
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
587
1493
  id,
588
1494
  args,
589
1495
  event: evt,
590
1496
  direct: true
591
- }) : run();
1497
+ }) : run(), id));
592
1498
  });
1499
+ result = scopeDeferredResult(result, scope);
593
1500
  const transform = config.transformDirectResult;
594
1501
  if (transform && result && typeof result.then === "function") {
595
- return result.then(value => transform(value, {
1502
+ return result.then(value => scopeDeferredResult(transform(value, {
596
1503
  id,
597
1504
  args,
598
1505
  event: evt
599
- }));
1506
+ }), scope));
600
1507
  }
601
- return transform ? transform(result, {
1508
+ return transform ? scopeDeferredResult(transform(result, {
602
1509
  id,
603
1510
  args,
604
1511
  event: evt
605
- }) : result;
1512
+ }), scope) : result;
606
1513
  }
607
1514
  });
1515
+ REFERENCE_BINDINGS.set(proxy, fn);
1516
+ return proxy;
608
1517
  }
609
1518
  function GET(fn) {
610
1519
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
611
1520
  throw new Error("GET expects a server function reference");
612
1521
  }
613
- METHODS.set(fn.id, "GET");
614
- return withMeta(fn, {
1522
+ const id = fn.id;
1523
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1524
+ const existing = METHODS.get(id);
1525
+ if (existing !== undefined && existing !== binding) {
1526
+ if (CARRIED.has(id)) return fn;
1527
+ if (DEV) {
1528
+ 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.`);
1529
+ }
1530
+ METHODS.delete(id);
1531
+ return fn;
1532
+ }
1533
+ METHODS.set(id, binding);
1534
+ CARRIED.delete(id);
1535
+ const reference = withMeta(fn, {
615
1536
  method: "GET"
616
1537
  });
1538
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1539
+ return reference;
1540
+ }
1541
+ function guardDeclaredMethod(metadata, id) {
1542
+ let declared = metadata.method;
1543
+ Object.defineProperty(metadata, "method", {
1544
+ configurable: true,
1545
+ enumerable: true,
1546
+ get: () => declared,
1547
+ set(next) {
1548
+ if (next === declared) return;
1549
+ if (DEV) {
1550
+ 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.`);
1551
+ }
1552
+ METHODS.delete(id);
1553
+ declared = next;
1554
+ }
1555
+ });
617
1556
  }
618
1557
  function live(fn) {
619
1558
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -623,14 +1562,9 @@ function live(fn) {
623
1562
  ...getServerFunctionMetadata(fn),
624
1563
  live: true
625
1564
  };
626
- const wrapped = async (...args) => {
627
- const result = await fn(...args);
628
- if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
629
- result[LIVE_SOURCE] = true;
630
- }
631
- return result;
632
- };
1565
+ const wrapped = async (...args) => brandLive(await fn(...args));
633
1566
  wrapped[SERVER_FUNCTION_METADATA] = metadata;
1567
+ wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
634
1568
  wrapped.id = fn.id;
635
1569
  Object.defineProperty(wrapped, "url", {
636
1570
  get: () => fn.url,
@@ -638,59 +1572,191 @@ function live(fn) {
638
1572
  });
639
1573
  return wrapped;
640
1574
  }
1575
+ function brandLive(answer) {
1576
+ if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
1577
+ answer[LIVE_SOURCE] = true;
1578
+ }
1579
+ return answer;
1580
+ }
641
1581
  function getServerFunctionInvocation() {
642
1582
  return getEventServerFunctionInvocation(getRequestEvent());
643
1583
  }
644
1584
  function getEventServerFunctionInvocation(event) {
645
1585
  return event && INVOCATIONS.get(event);
646
1586
  }
647
- function resolveFunctionId(request, url) {
648
- const reference = request.headers.get(FUNCTION_HEADER);
649
- if (reference) {
650
- return reference.split("#")[0];
1587
+ function resolveAddress(url) {
1588
+ return parseServerFunctionAddress(url.pathname, config.endpoint);
1589
+ }
1590
+ const DECODE_DEPTH_LIMIT = 64;
1591
+ function assertDecodeDepth(value) {
1592
+ let level = [value];
1593
+ for (let depth = 0; level.length > 0; depth++) {
1594
+ if (depth > DECODE_DEPTH_LIMIT) {
1595
+ throw new TypeError("Server function arguments exceed the decode depth limit");
1596
+ }
1597
+ const next = [];
1598
+ for (const node of level) {
1599
+ if (node === null || typeof node !== "object") continue;
1600
+ if (Array.isArray(node)) {
1601
+ for (const child of node) next.push(child);
1602
+ } else {
1603
+ for (const key of Object.keys(node)) next.push(node[key]);
1604
+ }
1605
+ }
1606
+ level = next;
1607
+ }
1608
+ }
1609
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1610
+ function stripUnsafeArgumentKeys(value) {
1611
+ const stack = [value];
1612
+ const seen = new Set();
1613
+ while (stack.length) {
1614
+ const v = stack.pop();
1615
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1616
+ seen.add(v);
1617
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1618
+ delete v[key];
1619
+ }
1620
+ for (const key of Object.keys(v)) stack.push(v[key]);
1621
+ if (v instanceof Map) {
1622
+ for (const [k, entry] of v) stack.push(k, entry);
1623
+ } else if (v instanceof Set) {
1624
+ for (const member of v) stack.push(member);
1625
+ }
1626
+ }
1627
+ return value;
1628
+ }
1629
+ async function bufferBodyWithin(request, limit) {
1630
+ const reader = request.body.getReader();
1631
+ const signal = request.signal;
1632
+ const chunks = [];
1633
+ let total = 0;
1634
+ const onAbort = () => {
1635
+ reader.cancel(signal.reason).catch(() => {});
1636
+ };
1637
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1638
+ once: true
1639
+ });
1640
+ try {
1641
+ for (;;) {
1642
+ const {
1643
+ done,
1644
+ value
1645
+ } = await reader.read();
1646
+ if (signal.aborted) throw signal.reason;
1647
+ if (done) break;
1648
+ total += value.byteLength;
1649
+ if (total > limit) {
1650
+ reader.cancel().catch(() => {});
1651
+ return null;
1652
+ }
1653
+ chunks.push(value);
1654
+ }
1655
+ } catch (error) {
1656
+ reader.cancel(error).catch(() => {});
1657
+ throw error;
1658
+ } finally {
1659
+ signal.removeEventListener("abort", onAbort);
1660
+ reader.releaseLock();
1661
+ }
1662
+ const body = new Uint8Array(total);
1663
+ let offset = 0;
1664
+ for (const chunk of chunks) {
1665
+ body.set(chunk, offset);
1666
+ offset += chunk.byteLength;
651
1667
  }
652
- return url.searchParams.get("id");
1668
+ return body;
1669
+ }
1670
+ function withBufferedBody(request, body) {
1671
+ return new Request(request.url, {
1672
+ method: request.method,
1673
+ headers: request.headers,
1674
+ signal: request.signal,
1675
+ body
1676
+ });
653
1677
  }
654
- async function parseArguments(request, url, instance, codec) {
1678
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1679
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1680
+ function unknownFormatError(tag) {
1681
+ 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.");
1682
+ error[FORMAT_SKEW] = true;
1683
+ return error;
1684
+ }
1685
+ async function parseArguments(request, url, scripted, codec) {
655
1686
  const parsed = [];
656
1687
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
657
- if (!instance || request.method === "GET" || bodyFormat !== BodyFormat.Serialized) {
658
- const args = url.searchParams.get("args");
659
- if (args) {
660
- const result = args.startsWith(";0x") ? await deserializeString(args, codec) : JSON.parse(args);
661
- for (const arg of result) {
662
- parsed.push(arg);
663
- }
1688
+ const args = url.searchParams.get("args");
1689
+ if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1690
+ let result;
1691
+ if (args.startsWith(";0x")) {
1692
+ result = await deserializeString(args, codec);
1693
+ } else {
1694
+ result = JSON.parse(args);
1695
+ assertDecodeDepth(result);
1696
+ }
1697
+ if (!Array.isArray(result)) {
1698
+ throw new TypeError("Server function arguments must encode an array");
1699
+ }
1700
+ stripUnsafeArgumentKeys(result);
1701
+ for (const arg of result) {
1702
+ parsed.push(arg);
664
1703
  }
1704
+ } else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
1705
+ parsed.push(url.searchParams);
665
1706
  }
666
1707
  if (request.method === "POST" && request.body !== null) {
667
- const decoded = await extractBody(request.clone(), codec);
1708
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1709
+ throw unknownFormatError(bodyFormat);
1710
+ }
1711
+ const body = request.clone();
1712
+ const decoded = await extractBody(body, codec);
668
1713
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
669
- return decoded;
1714
+ if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1715
+ if (!Array.isArray(decoded)) {
1716
+ throw new TypeError("Server function arguments must encode an array");
1717
+ }
1718
+ return stripUnsafeArgumentKeys(decoded);
1719
+ }
1720
+ if (decoded === undefined) {
1721
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1722
+ return parsed;
1723
+ }
1724
+ throw new TypeError("Server function body carries no usable encoding");
670
1725
  }
671
1726
  parsed.push(decoded);
672
1727
  }
673
1728
  return parsed;
674
1729
  }
675
- async function foldFlightData(hook, event, headers, outcome, context = {}) {
1730
+ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
676
1731
  if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
677
1732
  digestOutcome(event, outcome);
678
- const data = await hook(event, outcome);
679
- if (data === undefined) return outcome.value;
680
- headers.set(SINGLE_FLIGHT_HEADER, "true");
1733
+ const folded = [];
1734
+ for (const [source, hook] of hooks) {
1735
+ try {
1736
+ const slice = await hook(event, outcome);
1737
+ if (slice !== undefined) folded.push([source, slice]);
1738
+ } catch (error) {
1739
+ console.error(`Error collecting flight data for source "${source}"`, error);
1740
+ }
1741
+ }
1742
+ if (folded.length === 0) return outcome.value;
1743
+ const data = Object.fromEntries(folded);
1744
+ headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
681
1745
  if (context.transformFlightResult) {
682
1746
  const transformed = await context.transformFlightResult(event, {
683
1747
  value: outcome.value,
684
1748
  data
685
1749
  }, context);
686
1750
  if (transformed !== undefined) {
687
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1751
+ const owned = ownResponse(transformed);
1752
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
688
1753
  headers.forEach((value, key) => {
689
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
690
- transformed.headers.set(key, value);
1754
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1755
+ owned.headers.set(key, value);
691
1756
  }
692
1757
  });
693
- return transformed;
1758
+ owned.headers.set(SINGLE_FLIGHT_HEADER, headers.get(SINGLE_FLIGHT_HEADER));
1759
+ return owned;
694
1760
  }
695
1761
  }
696
1762
  return outcome.value === undefined ? {
@@ -757,7 +1823,7 @@ function foldSetCookies(headers, setCookies) {
757
1823
  }
758
1824
  function mergeResponseHeaders(target, source) {
759
1825
  source.forEach((value, key) => {
760
- if (key !== "set-cookie") target.append(key, value);
1826
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
761
1827
  });
762
1828
  if (source.getSetCookie) {
763
1829
  for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
@@ -766,10 +1832,52 @@ function mergeResponseHeaders(target, source) {
766
1832
  }
767
1833
  }
768
1834
  const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
1835
+ function maskRedirect(headers, response, requestUrl) {
1836
+ const target = response.headers && response.headers.get("Location");
1837
+ if (target) {
1838
+ headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
1839
+ }
1840
+ headers.delete("Location");
1841
+ }
1842
+ const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1843
+ function enforceComposedHeaderInvariants(response) {
1844
+ for (const name of BOUNDED_COMPOSED_HEADERS) {
1845
+ const value = response.headers.get(name);
1846
+ if (value === null) continue;
1847
+ if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
1848
+ 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);
1849
+ }
1850
+ if (name === REVALIDATE_HEADER) continue;
1851
+ const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1852
+ if (!isHttpNavigationTarget(target)) {
1853
+ 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);
1854
+ }
1855
+ }
1856
+ return response;
1857
+ }
1858
+ function refuseComposedHeader(response, name, headerMessage, body) {
1859
+ if (response.body) {
1860
+ try {
1861
+ const cancelled = response.body.cancel();
1862
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1863
+ } catch {}
1864
+ }
1865
+ const headers = new Headers();
1866
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
1867
+ return new Response(body, {
1868
+ status: 500,
1869
+ headers
1870
+ });
1871
+ }
1872
+ function warnScripted304(functionId) {
1873
+ if (DEV) {
1874
+ 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.`);
1875
+ }
1876
+ }
769
1877
  function createNoJSHandler({
770
1878
  base = ""
771
1879
  } = {}) {
772
- return function handleNoJS(result, request, args, thrown) {
1880
+ return async function handleNoJS(result, request, args, thrown) {
773
1881
  const url = new URL(request.url);
774
1882
  let back = new URL(base || "/", url.origin).toString();
775
1883
  try {
@@ -794,8 +1902,9 @@ function createNoJSHandler({
794
1902
  Location: back
795
1903
  });
796
1904
  }
797
- if (result && !(result instanceof Response)) {
798
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1905
+ if (result !== undefined && !(result instanceof Response)) {
1906
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1907
+ if (flash !== null) headers.append("Set-Cookie", flash);
799
1908
  }
800
1909
  return new Response(null, {
801
1910
  status,
@@ -809,44 +1918,309 @@ function isFormPost(request) {
809
1918
  const type = request.headers.get("content-type") || "";
810
1919
  return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
811
1920
  }
812
- function serializeResponseStream(value, codecOptions, signal) {
813
- let closeIterator = null;
814
- let closed = false;
815
- let cancelSerialize = null;
816
- let onAbort = null;
817
- const teardown = () => {
818
- if (closed) return;
819
- closed = true;
820
- if (onAbort) signal.removeEventListener("abort", onAbort);
821
- if (cancelSerialize) cancelSerialize();
822
- if (closeIterator) closeIterator();
1921
+ function guardFailures(value, state) {
1922
+ if (!state) state = {
1923
+ seen: new WeakMap(),
1924
+ cyclic: new WeakSet()
823
1925
  };
824
- if (value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
1926
+ const entered = enterGuard(value, state);
1927
+ if (!(entered instanceof Frame)) return entered;
1928
+ const stack = [entered];
1929
+ let delivered = NOTHING;
1930
+ for (;;) {
1931
+ const top = stack[stack.length - 1];
1932
+ const items = top.items;
1933
+ let pushed = null;
1934
+ while (top.i < items.length) {
1935
+ const i = top.i;
1936
+ let original;
1937
+ if (top.kind === OBJECT) {
1938
+ const descriptor = top.descriptors[items[i]];
1939
+ if ("value" in descriptor) {
1940
+ original = descriptor.value;
1941
+ } else if (typeof descriptor.get === "function") {
1942
+ if (top.accessorRead !== i) {
1943
+ try {
1944
+ top.accessorValue = descriptor.get.call(top.value);
1945
+ } catch (error) {
1946
+ throw wireServerFunctionError(error, "channel");
1947
+ }
1948
+ top.accessorRead = i;
1949
+ }
1950
+ original = top.accessorValue;
1951
+ } else {
1952
+ top.i++;
1953
+ continue;
1954
+ }
1955
+ } else {
1956
+ original = items[i];
1957
+ }
1958
+ let guarded;
1959
+ if (delivered !== NOTHING) {
1960
+ guarded = delivered;
1961
+ delivered = NOTHING;
1962
+ } else {
1963
+ guarded = enterGuard(original, state);
1964
+ if (guarded instanceof Frame) {
1965
+ pushed = guarded;
1966
+ break;
1967
+ }
1968
+ }
1969
+ if (top.kind === ARRAY) {
1970
+ if (guarded !== original) {
1971
+ top.next[i] = guarded;
1972
+ top.changed = true;
1973
+ }
1974
+ } else if (top.kind === MAP) {
1975
+ if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
1976
+ if (guarded !== original) top.changed = true;
1977
+ } else if (top.kind === SET) {
1978
+ top.next.add(guarded);
1979
+ if (guarded !== original) top.changed = true;
1980
+ } else if (guarded !== original || top.accessorRead === i) {
1981
+ Object.defineProperty(top.next, items[i], {
1982
+ value: guarded,
1983
+ writable: true,
1984
+ configurable: true,
1985
+ enumerable: top.descriptors[items[i]].enumerable
1986
+ });
1987
+ top.changed = true;
1988
+ }
1989
+ top.i++;
1990
+ }
1991
+ if (pushed !== null) {
1992
+ stack.push(pushed);
1993
+ continue;
1994
+ }
1995
+ stack.pop();
1996
+ const out = keepGuarded(top.value, top.next, top.changed, state);
1997
+ if (stack.length === 0) return out;
1998
+ delivered = out;
1999
+ }
2000
+ }
2001
+ const NOTHING = Symbol();
2002
+ const ARRAY = 0;
2003
+ const MAP = 1;
2004
+ const SET = 2;
2005
+ const OBJECT = 3;
2006
+ class Frame {
2007
+ constructor(kind, value, next, items, descriptors) {
2008
+ this.kind = kind;
2009
+ this.value = value;
2010
+ this.next = next;
2011
+ this.items = items;
2012
+ this.descriptors = descriptors;
2013
+ this.i = 0;
2014
+ this.changed = false;
2015
+ this.accessorRead = -1;
2016
+ this.accessorValue = undefined;
2017
+ this.pendingKey = undefined;
2018
+ }
2019
+ }
2020
+ function guardOperation(state, run) {
2021
+ return state.scope ? state.scope(run) : run();
2022
+ }
2023
+ function enterGuard(value, state) {
2024
+ if (value === null || typeof value !== "object") return value;
2025
+ if (state.seen.has(value)) {
2026
+ state.cyclic.add(value);
2027
+ return state.seen.get(value);
2028
+ }
2029
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
2030
+ let reader;
2031
+ const gate = state.gate;
2032
+ let finished = false;
2033
+ const close = () => {
2034
+ if (finished) return;
2035
+ finished = true;
2036
+ try {
2037
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
2038
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
2039
+ } catch {}
2040
+ };
2041
+ const guardedStream = new ReadableStream({
2042
+ async pull(controller) {
2043
+ try {
2044
+ if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
2045
+ if (finished) {
2046
+ controller.close();
2047
+ return;
2048
+ }
2049
+ if (!reader) reader = guardOperation(state, () => value.getReader());
2050
+ const {
2051
+ done,
2052
+ value: chunk
2053
+ } = await guardOperation(state, () => reader.read());
2054
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
2055
+ } catch (error) {
2056
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
2057
+ }
2058
+ },
2059
+ cancel(reason) {
2060
+ finished = true;
2061
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
2062
+ }
2063
+ });
2064
+ if (gate) gate.onOpen(close);
2065
+ state.seen.set(value, guardedStream);
2066
+ return guardedStream;
2067
+ }
2068
+ if (typeof value.then === "function") {
2069
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
2070
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
2071
+ });
2072
+ guardedPromise.catch(() => {});
2073
+ state.seen.set(value, guardedPromise);
2074
+ return guardedPromise;
2075
+ }
2076
+ if (typeof value[Symbol.asyncIterator] === "function") {
825
2077
  const source = value;
826
- value = {
2078
+ const gate = state.gate;
2079
+ const guardedIterable = {
827
2080
  [Symbol.asyncIterator]() {
828
- const it = source[Symbol.asyncIterator]();
2081
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
829
2082
  let finished = false;
830
- closeIterator = () => {
2083
+ const close = () => {
831
2084
  if (finished) return;
832
2085
  finished = true;
833
2086
  try {
834
- const returned = it.return && it.return();
2087
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
835
2088
  if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
836
2089
  } catch {}
837
2090
  };
838
- if (closed) closeIterator();
2091
+ if (gate) gate.onOpen(close);
2092
+ const step = () => finished ? Promise.resolve({
2093
+ done: true,
2094
+ value: undefined
2095
+ }) : guardOperation(state, () => iterator.next()).then(step => {
2096
+ if (step.done) {
2097
+ finished = true;
2098
+ return step;
2099
+ }
2100
+ return {
2101
+ done: false,
2102
+ value: guardOperation(state, () => guardFailures(step.value, state))
2103
+ };
2104
+ }, error => {
2105
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
2106
+ });
839
2107
  return {
840
- next: () => finished ? Promise.resolve({
841
- done: true,
842
- value: undefined
843
- }) : it.next()
2108
+ next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
2109
+ return: () => {
2110
+ close();
2111
+ return Promise.resolve({
2112
+ done: true,
2113
+ value: undefined
2114
+ });
2115
+ }
844
2116
  };
845
2117
  }
846
2118
  };
2119
+ state.seen.set(value, guardedIterable);
2120
+ return guardedIterable;
2121
+ }
2122
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
2123
+ const scopedIterable = scopeDeferredResult(value, state.scope);
2124
+ state.seen.set(value, scopedIterable);
2125
+ return scopedIterable;
2126
+ }
2127
+ if (Array.isArray(value)) {
2128
+ const next = value.slice();
2129
+ state.seen.set(value, next);
2130
+ return new Frame(ARRAY, value, next, value, null);
847
2131
  }
2132
+ if (value instanceof Map) {
2133
+ const next = new Map();
2134
+ state.seen.set(value, next);
2135
+ const items = [];
2136
+ for (const entry of value) items.push(entry[0], entry[1]);
2137
+ return new Frame(MAP, value, next, items, null);
2138
+ }
2139
+ if (value instanceof Set) {
2140
+ const next = new Set();
2141
+ state.seen.set(value, next);
2142
+ return new Frame(SET, value, next, [...value], null);
2143
+ }
2144
+ const prototype = Object.getPrototypeOf(value);
2145
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
2146
+ state.seen.set(value, value);
2147
+ return value;
2148
+ }
2149
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2150
+ for (const key of Object.keys(descriptors)) {
2151
+ descriptors[key].configurable = true;
2152
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
2153
+ }
2154
+ const next = Object.create(prototype, descriptors);
2155
+ state.seen.set(value, next);
2156
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
2157
+ const descriptor = descriptors[key];
2158
+ return descriptor.enumerable || "value" in descriptor;
2159
+ });
2160
+ return new Frame(OBJECT, value, next, children, descriptors);
2161
+ }
2162
+ function keepGuarded(value, next, changed, state) {
2163
+ if (changed || state.cyclic.has(value)) return next;
2164
+ state.seen.set(value, value);
2165
+ return value;
2166
+ }
2167
+ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2168
+ let closed = false;
2169
+ const frame = live ? payload => {
2170
+ const id = live.pending;
2171
+ live.pending = undefined;
2172
+ return createEventChunk(payload, id);
2173
+ } : createChunk;
2174
+ let stopLive = null;
2175
+ const stopHeartbeat = () => {
2176
+ if (stopLive !== null) {
2177
+ stopLive();
2178
+ stopLive = null;
2179
+ }
2180
+ };
2181
+ let streamController = null;
2182
+ let demandWaiters = null;
2183
+ const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
2184
+ const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
2185
+ const supplyDemand = () => {
2186
+ const resolvers = demandWaiters;
2187
+ demandWaiters = null;
2188
+ if (resolvers) for (const resolve of resolvers) resolve();
2189
+ };
2190
+ const sourceClosers = new Set();
2191
+ const gate = {
2192
+ wantsMore,
2193
+ awaitDemand,
2194
+ onOpen(close) {
2195
+ if (closed) close();else sourceClosers.add(close);
2196
+ }
2197
+ };
2198
+ const guardState = {
2199
+ seen: new WeakMap(),
2200
+ cyclic: new WeakSet(),
2201
+ gate,
2202
+ scope
2203
+ };
2204
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
2205
+ let cancelSerialize = null;
2206
+ let onAbort = null;
2207
+ const finishSource = () => {
2208
+ for (const close of sourceClosers) close();
2209
+ sourceClosers.clear();
2210
+ supplyDemand();
2211
+ };
2212
+ const teardown = () => {
2213
+ if (closed) return;
2214
+ closed = true;
2215
+ stopHeartbeat();
2216
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2217
+ if (cancelSerialize) cancelSerialize();
2218
+ finishSource();
2219
+ };
848
2220
  return new ReadableStream({
849
2221
  async start(controller) {
2222
+ streamController = controller;
2223
+ if (live) stopLive = armLiveBody(controller, teardown);
850
2224
  if (signal) {
851
2225
  if (signal.aborted) {
852
2226
  teardown();
@@ -876,35 +2250,145 @@ function serializeResponseStream(value, codecOptions, signal) {
876
2250
  cancelSerialize = serializeJSON(value, {
877
2251
  ...codecOptions,
878
2252
  onParse(node) {
879
- if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
2253
+ if (!closed) controller.enqueue(frame(JSON.stringify(node)));
880
2254
  },
881
2255
  onDone() {
882
2256
  if (closed) return;
883
2257
  closed = true;
2258
+ stopHeartbeat();
884
2259
  if (onAbort) signal.removeEventListener("abort", onAbort);
2260
+ finishSource();
885
2261
  controller.close();
886
2262
  },
887
2263
  onError(error) {
888
2264
  if (closed) return;
889
2265
  closed = true;
2266
+ stopHeartbeat();
890
2267
  if (onAbort) signal.removeEventListener("abort", onAbort);
891
- controller.error(error);
2268
+ finishSource();
2269
+ try {
2270
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
2271
+ controller.enqueue(frame(encodeErrorTrailer(delivered)));
2272
+ controller.close();
2273
+ } catch {
2274
+ try {
2275
+ controller.error(error);
2276
+ } catch {}
2277
+ }
892
2278
  }
893
2279
  });
894
2280
  },
2281
+ pull() {
2282
+ supplyDemand();
2283
+ },
895
2284
  cancel() {
896
2285
  teardown();
897
2286
  }
898
2287
  });
899
2288
  }
900
- function serializedResponse(value, headers, codec, signal) {
2289
+ function serializedResponse(value, headers, codec, signal, scope) {
901
2290
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
902
2291
  headers.set("Content-Type", "text/plain");
903
- return new Response(serializeResponseStream(value, codec, signal), {
2292
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
904
2293
  headers
905
2294
  });
906
2295
  }
907
- function encodeResult(value, headers, status, codec, signal) {
2296
+ const LIVE_HEARTBEAT_INTERVAL = 20000;
2297
+ function armLiveBody(controller, teardown) {
2298
+ let stopped = false;
2299
+ const heartbeat = setInterval(() => {
2300
+ if (stopped) return;
2301
+ try {
2302
+ controller.enqueue(EVENT_STREAM_HEARTBEAT);
2303
+ } catch {}
2304
+ }, LIVE_HEARTBEAT_INTERVAL);
2305
+ if (typeof heartbeat === "object" && heartbeat && typeof heartbeat.unref === "function") heartbeat.unref();
2306
+ let chaos = null;
2307
+ if (DEV && config.chaosReconnectEvery > 0) {
2308
+ chaos = setTimeout(() => {
2309
+ if (stopped) return;
2310
+ teardown();
2311
+ try {
2312
+ controller.error(new Error("Live response ended by the chaos knob."));
2313
+ } catch {}
2314
+ }, config.chaosReconnectEvery);
2315
+ if (typeof chaos === "object" && chaos && typeof chaos.unref === "function") chaos.unref();
2316
+ }
2317
+ return () => {
2318
+ if (stopped) return;
2319
+ stopped = true;
2320
+ clearInterval(heartbeat);
2321
+ if (chaos !== null) clearTimeout(chaos);
2322
+ };
2323
+ }
2324
+ function liveSource(value, lastEventId, position, scope) {
2325
+ const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
2326
+ if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
2327
+ const digest = digestOf(value);
2328
+ if (digest !== undefined && digest === lastEventId) return async function* () {}();
2329
+ position.pending = digest;
2330
+ return value;
2331
+ }
2332
+ const source = value;
2333
+ return {
2334
+ [Symbol.asyncIterator]() {
2335
+ const iterator = source[Symbol.asyncIterator]();
2336
+ let first = true;
2337
+ const step = () => iterator.next().then(result => {
2338
+ if (result.done) return result;
2339
+ const digest = digestOf(result.value);
2340
+ if (first) {
2341
+ first = false;
2342
+ if (digest !== undefined && digest === lastEventId) return step();
2343
+ }
2344
+ position.pending = digest;
2345
+ return result;
2346
+ });
2347
+ return {
2348
+ next: step,
2349
+ return: v => iterator.return ? iterator.return(v) : Promise.resolve({
2350
+ done: true,
2351
+ value: v
2352
+ }),
2353
+ throw: e => iterator.throw ? iterator.throw(e) : Promise.reject(e)
2354
+ };
2355
+ }
2356
+ };
2357
+ }
2358
+ function encodeLiveResult(value, headers, status, codec, request, scope) {
2359
+ if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
2360
+ return encodeResult(value, headers, status, codec, request.signal, scope);
2361
+ }
2362
+ const position = {
2363
+ pending: undefined
2364
+ };
2365
+ const source = liveSource(value, request.headers.get(LAST_EVENT_ID_HEADER), position, scope);
2366
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2367
+ headers.set("Content-Type", "text/event-stream");
2368
+ headers.set("Cache-Control", "no-store");
2369
+ headers.set("X-Accel-Buffering", "no");
2370
+ try {
2371
+ return new Response(serializeResponseStream(source, codec, request.signal, scope, position), {
2372
+ status,
2373
+ headers
2374
+ });
2375
+ } catch (error) {
2376
+ throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2377
+ }
2378
+ }
2379
+ function encodeResult(value, headers, status, codec, signal, scope) {
2380
+ if (NULL_BODY_STATUSES.has(status)) {
2381
+ if (value === undefined || value === null) {
2382
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
2383
+ return new Response(null, {
2384
+ status,
2385
+ headers
2386
+ });
2387
+ }
2388
+ 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.`);
2389
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
2390
+ return encodeResult(error, headers, 500, codec, signal, scope);
2391
+ }
908
2392
  const direct = getHeadersAndBody(value);
909
2393
  if (direct) {
910
2394
  for (const [key, val] of Object.entries(direct.headers || {})) {
@@ -916,80 +2400,374 @@ function encodeResult(value, headers, status, codec, signal) {
916
2400
  });
917
2401
  }
918
2402
  if (value === undefined) {
2403
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
919
2404
  return new Response(null, {
920
2405
  status,
921
2406
  headers
922
2407
  });
923
2408
  }
924
2409
  try {
925
- if (isJSONSafe(value)) {
2410
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
2411
+ if (jsonSafe) {
926
2412
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
927
2413
  headers.set("Content-Type", "application/json");
928
- return new Response(JSON.stringify(value), {
2414
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
2415
+ return new Response(body, {
929
2416
  status,
930
2417
  headers
931
2418
  });
932
2419
  }
933
2420
  } catch {
934
2421
  }
935
- const response = serializedResponse(value, headers, codec, signal);
936
- return status === 200 ? response : new Response(response.body, {
937
- status,
938
- headers
939
- });
2422
+ try {
2423
+ const response = serializedResponse(value, headers, codec, signal, scope);
2424
+ return status === 200 ? response : new Response(response.body, {
2425
+ status,
2426
+ headers
2427
+ });
2428
+ } catch (error) {
2429
+ throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2430
+ }
2431
+ }
2432
+ const ERROR_HEADER_VALUE_LIMIT = 1024;
2433
+ function boundedErrorHeaderValue(message) {
2434
+ let label = message.length > 256 ? message.slice(0, 256) : message;
2435
+ let encoded = encodeErrorHeaderValue(label);
2436
+ while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
2437
+ label = label.slice(0, Math.ceil(label.length / 2));
2438
+ encoded = encodeErrorHeaderValue(label);
2439
+ }
2440
+ return encoded;
940
2441
  }
941
2442
  const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
942
2443
  let DEV = false === true;
943
2444
  function setServerFunctionsDev(dev) {
944
2445
  DEV = !!dev;
945
2446
  }
2447
+ const REQUEST_ERROR_HOOKS = new WeakMap();
2448
+ function siteFor(handling, event, direct) {
2449
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
2450
+ const site = {
2451
+ kind: "server-function",
2452
+ handling,
2453
+ direct
2454
+ };
2455
+ if (invocation) site.functionId = invocation.id;
2456
+ if (event) site.event = event;
2457
+ return site;
2458
+ }
2459
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
2460
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
2461
+ return report.mapped ? report.value : sanitizeServerError(value);
2462
+ }
2463
+ function currentEvent() {
2464
+ const store = globalThis[RequestContext];
2465
+ return store ? store.getStore() : undefined;
2466
+ }
2467
+ function reportDirectFailure(run, id) {
2468
+ const report = error => {
2469
+ reportServerError(error, {
2470
+ kind: "server-function",
2471
+ handling: "thrown",
2472
+ functionId: id,
2473
+ direct: true
2474
+ }, null);
2475
+ throw error;
2476
+ };
2477
+ let result;
2478
+ try {
2479
+ result = run();
2480
+ } catch (error) {
2481
+ report(error);
2482
+ }
2483
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
2484
+ }
946
2485
  function sanitizeServerError(value) {
947
2486
  if (DEV) return value;
948
2487
  if (isSafeError(value)) return value;
949
- return new Error(GENERIC_SERVER_ERROR_MESSAGE);
2488
+ const wire = new Error(GENERIC_SERVER_ERROR_MESSAGE);
2489
+ return wire;
2490
+ }
2491
+ function serverFunctionUrl(fn, ...args) {
2492
+ return serverFunctionUrlFor(config.endpoint, fn, args);
2493
+ }
2494
+ function serverFunctionActionUrl(fn, ...boundArgs) {
2495
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
2496
+ }
2497
+ function parseServerFunctionActionUrl(url) {
2498
+ const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
2499
+ return parsed && parsed.id;
2500
+ }
2501
+ async function matchesOrigin(origin, request, matcher) {
2502
+ if (matcher === undefined) return origin === new URL(request.url).origin;
2503
+ if (typeof matcher === "function") return (await matcher(origin, request)) === true;
2504
+ return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
2505
+ }
2506
+ async function allowsServerFunctionRequest(request, options) {
2507
+ const fetchSite = request.headers.get("Sec-Fetch-Site");
2508
+ if (fetchSite === "same-origin") return true;
2509
+ if (fetchSite === "none") return false;
2510
+ const origin = request.headers.get("Origin");
2511
+ if (fetchSite === "same-site" || fetchSite === "cross-site") {
2512
+ if (origin === null || options.origin === undefined) return false;
2513
+ return (await matchesOrigin(origin, request, options.origin)) ? origin : false;
2514
+ }
2515
+ if (origin !== null) {
2516
+ if (!(await matchesOrigin(origin, request, options.origin))) return false;
2517
+ return origin === new URL(request.url).origin ? true : origin;
2518
+ }
2519
+ const referer = request.headers.get("Referer");
2520
+ if (referer !== null) {
2521
+ try {
2522
+ return matchesOrigin(new URL(referer).origin, request, options.origin);
2523
+ } catch {
2524
+ return false;
2525
+ }
2526
+ }
2527
+ return options.allowRequestsWithoutOriginCheck === true;
2528
+ }
2529
+ const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
2530
+ function appendVary(headers, names) {
2531
+ const current = headers.get("Vary");
2532
+ if (current === "*") return;
2533
+ const values = current ? current.split(",").map(value => value.trim()) : [];
2534
+ const seen = new Set(values.map(value => value.toLowerCase()));
2535
+ for (const name of names) {
2536
+ if (!seen.has(name.toLowerCase())) values.push(name);
2537
+ }
2538
+ headers.set("Vary", values.join(", "));
2539
+ }
2540
+ function withHeaders(response, write) {
2541
+ try {
2542
+ write(response.headers);
2543
+ return response;
2544
+ } catch {
2545
+ const headers = new Headers(response.headers);
2546
+ write(headers);
2547
+ return new Response(response.body, {
2548
+ status: response.status,
2549
+ statusText: response.statusText,
2550
+ headers
2551
+ });
2552
+ }
2553
+ }
2554
+ function withCSRFVary(response) {
2555
+ return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
2556
+ }
2557
+ const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER].join(", ");
2558
+ const PREFLIGHT_MAX_AGE = "600";
2559
+ const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
2560
+ function withCORS(response, cors) {
2561
+ if (cors === null) return response;
2562
+ return withHeaders(response, headers => {
2563
+ headers.set("Access-Control-Allow-Origin", cors.origin);
2564
+ if (cors.credentials) headers.set("Access-Control-Allow-Credentials", "true");
2565
+ const exposed = [];
2566
+ for (const name of headers.keys()) {
2567
+ if (CORS_SAFELISTED_RESPONSE_HEADERS.has(name) || name === "set-cookie" || name === "vary" || name.startsWith("access-control-")) {
2568
+ continue;
2569
+ }
2570
+ exposed.push(name);
2571
+ }
2572
+ if (exposed.length > 0) headers.set("Access-Control-Expose-Headers", exposed.join(", "));
2573
+ appendVary(headers, ["Origin"]);
2574
+ });
2575
+ }
2576
+ function preflightResponse(request) {
2577
+ const requested = request.headers.get("Access-Control-Request-Headers");
2578
+ const response = new Response(null, {
2579
+ status: 204,
2580
+ headers: {
2581
+ "Access-Control-Allow-Methods": "POST, GET, HEAD",
2582
+ "Access-Control-Allow-Headers": requested !== null && requested.trim() !== "" ? requested : TRANSPORT_REQUEST_HEADERS,
2583
+ "Access-Control-Max-Age": PREFLIGHT_MAX_AGE,
2584
+ "Cache-Control": "no-store"
2585
+ }
2586
+ });
2587
+ appendVary(response.headers, ["Access-Control-Request-Method", "Access-Control-Request-Headers"]);
2588
+ return response;
2589
+ }
2590
+ function forbiddenResponse() {
2591
+ return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
2592
+ status: 403,
2593
+ headers: {
2594
+ "Cache-Control": "no-store"
2595
+ }
2596
+ }));
2597
+ }
2598
+ function nativePromise(value) {
2599
+ if (value instanceof Promise) return value;
2600
+ try {
2601
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
2602
+ } catch {}
950
2603
  }
951
2604
  async function handleServerFunctionRequest(request, options = {}) {
952
- const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
2605
+ const codec = {
2606
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
2607
+ };
2608
+ codec.serializeErrorStacks ??= DEV;
953
2609
  const url = new URL(request.url);
954
- const instance = request.headers.get(INSTANCE_HEADER);
955
- const functionId = resolveFunctionId(request, url);
956
- if (!functionId) {
957
- return new Response(DEV ? "Server function not found" : null, {
958
- status: 404
959
- });
2610
+ const method = request.method;
2611
+ const address = resolveAddress(url);
2612
+ const functionId = address && address.id;
2613
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
2614
+ const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
2615
+ const protectsRequest = csrf !== false && (!declaredRead || CARRIED.has(functionId) || typeof csrf === "object" && csrf.protectDeclaredReads === true);
2616
+ const csrfOptions = csrf === true ? {} : csrf;
2617
+ let verdict = true;
2618
+ let readVariesByOrigin = false;
2619
+ if (protectsRequest) {
2620
+ verdict = await allowsServerFunctionRequest(request, csrfOptions);
2621
+ } else if (csrfOptions !== false && csrfOptions.origin !== undefined) {
2622
+ readVariesByOrigin = true;
2623
+ const admitted = await allowsServerFunctionRequest(request, csrfOptions);
2624
+ if (typeof admitted === "string") verdict = admitted;
2625
+ }
2626
+ const cors = typeof verdict === "string" ? {
2627
+ origin: verdict,
2628
+ credentials: csrfOptions.allowCredentials === true
2629
+ } : null;
2630
+ const finish = response => {
2631
+ const finalized = withCORS(finalizeTransportResponse(response, method), cors);
2632
+ return readVariesByOrigin && cors === null ? withHeaders(finalized, headers => appendVary(headers, ["Origin"])) : finalized;
2633
+ };
2634
+ if (cors !== null && method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
2635
+ return finish(preflightResponse(request));
960
2636
  }
961
2637
  let serverFunction;
962
- try {
963
- serverFunction = getServerFunction(functionId);
964
- } catch {
965
- return new Response(DEV ? `Unknown server function: ${functionId}` : null, {
2638
+ if (functionId) {
2639
+ try {
2640
+ serverFunction = getServerFunction(functionId);
2641
+ } catch {
2642
+ return finish(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
2643
+ status: 404,
2644
+ headers: {
2645
+ [UNKNOWN_HEADER]: "true"
2646
+ }
2647
+ }));
2648
+ }
2649
+ }
2650
+ if (verdict === false) {
2651
+ return finish(forbiddenResponse());
2652
+ }
2653
+ if (!functionId) {
2654
+ const response = new Response(DEV ? "Server function not found" : null, {
966
2655
  status: 404
967
2656
  });
2657
+ return finish(protectsRequest ? withCSRFVary(response) : response);
968
2658
  }
969
- if (request.method === "GET" && METHODS.get(functionId) !== "GET") {
970
- return new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
2659
+ const scripted = address.data || address.live;
2660
+ const live = address.live;
2661
+ if (method !== "POST" && !declaredRead) {
2662
+ const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
971
2663
  status: 405,
972
2664
  headers: {
973
- Allow: "POST"
2665
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
974
2666
  }
975
2667
  });
2668
+ return finish(protectsRequest ? withCSRFVary(response) : response);
976
2669
  }
977
- const event = options.createEvent ? options.createEvent(request) : {
978
- request,
979
- locals: {}
2670
+ const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
2671
+ const argsEncoding = url.searchParams.get("args");
2672
+ if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
2673
+ const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
2674
+ status: 413
2675
+ });
2676
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2677
+ }
2678
+ if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
2679
+ const raw = request.headers.get("content-length");
2680
+ const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
2681
+ if (declared > bodySizeLimit) {
2682
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2683
+ status: 413
2684
+ });
2685
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2686
+ }
2687
+ let buffered;
2688
+ try {
2689
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2690
+ } catch {
2691
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2692
+ status: 400
2693
+ });
2694
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2695
+ }
2696
+ if (buffered === null) {
2697
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2698
+ status: 413
2699
+ });
2700
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2701
+ }
2702
+ request = withBufferedBody(request, buffered);
2703
+ }
2704
+ let event;
2705
+ try {
2706
+ event = options.createEvent ? options.createEvent(request) : {
2707
+ request,
2708
+ locals: {}
2709
+ };
2710
+ const promised = nativePromise(event);
2711
+ if (promised) event = await promised;
2712
+ } catch (error) {
2713
+ const safe = sanitizeServerError(error);
2714
+ const message = safe instanceof Error ? safe.message : String(safe);
2715
+ const headers = new Headers();
2716
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2717
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2718
+ status: 500
2719
+ });
2720
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2721
+ }
2722
+ const refuseCommitted = raw => {
2723
+ const response = commitEventResponse(raw, event);
2724
+ return finish(protectsRequest ? withCSRFVary(response) : response);
980
2725
  };
981
2726
  const provide = options.provideEvent || provideEvent;
2727
+ const scope = run => provide(event, run);
2728
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
982
2729
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
983
2730
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
984
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2731
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
985
2732
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
986
- const handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS !== undefined ? config.handleNoJS : isFormPost(request) ? defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler()) : undefined;
987
- const collectsFlight = !!(flightHook && instance && request.headers.has(SINGLE_FLIGHT_HEADER));
988
- const parsed = await parseArguments(request, url, instance, codec);
2733
+ let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
2734
+ if (handleNoJS === undefined && !scripted && isFormPost(request)) {
2735
+ const fetchMode = request.headers.get("Sec-Fetch-Mode");
2736
+ if (fetchMode === null || fetchMode === "navigate") {
2737
+ handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
2738
+ } else {
2739
+ 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, {
2740
+ status: 400
2741
+ });
2742
+ return refuseCommitted(response);
2743
+ }
2744
+ }
2745
+ const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
2746
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
2747
+ const hook = source === "true" ? flightHook : flightSources.get(source);
2748
+ return hook ? [[source, hook]] : [];
2749
+ }) : [];
2750
+ const collectsFlight = flightHooks.length > 0;
2751
+ let parsed;
2752
+ try {
2753
+ parsed = await parseArguments(request, url, scripted, codec);
2754
+ } catch (error) {
2755
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2756
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
2757
+ status: 400
2758
+ });
2759
+ return refuseCommitted(response);
2760
+ }
2761
+ const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
2762
+ if (parsed.length > maxArguments) {
2763
+ const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
2764
+ status: 400
2765
+ });
2766
+ return refuseCommitted(response);
2767
+ }
989
2768
  const flightContext = {
990
2769
  id: functionId,
991
2770
  args: parsed,
992
- instance,
993
2771
  request,
994
2772
  collectsFlight,
995
2773
  codec,
@@ -998,19 +2776,27 @@ async function handleServerFunctionRequest(request, options = {}) {
998
2776
  const headers = new Headers();
999
2777
  const dispatch = async () => {
1000
2778
  try {
1001
- let result = await provide(event, async () => {
2779
+ const invokeOnce = async () => {
1002
2780
  INVOCATIONS.set(event, {
1003
- id: functionId
2781
+ id: functionId,
2782
+ live: !!live
1004
2783
  });
1005
2784
  const run = () => serverFunction(...parsed);
1006
- return wrapInvocation ? wrapInvocation(run, {
2785
+ return observeInvocation({
2786
+ id: functionId,
2787
+ direct: false,
2788
+ event,
2789
+ request,
2790
+ args: parsed
2791
+ }, () => wrapInvocation ? wrapInvocation(run, {
1007
2792
  id: functionId,
1008
2793
  args: parsed,
1009
2794
  event,
1010
2795
  request,
1011
2796
  direct: false
1012
- }) : run();
1013
- });
2797
+ }) : run());
2798
+ };
2799
+ let result = await provideEventOnce(provide, event, invokeOnce);
1014
2800
  if (transformResult) {
1015
2801
  result = await transformResult(event, result, flightContext);
1016
2802
  }
@@ -1021,25 +2807,29 @@ async function handleServerFunctionRequest(request, options = {}) {
1021
2807
  response,
1022
2808
  value
1023
2809
  } = result;
1024
- if (!instance && !handleNoJS && response && response.body) {
2810
+ if (!scripted && !handleNoJS && response && response.body) {
1025
2811
  return response;
1026
2812
  }
1027
2813
  if (response && response.headers) {
1028
2814
  mergeResponseHeaders(headers, response.headers);
1029
2815
  }
1030
- if (response && response.status && (response.status < 300 || response.status >= 400)) {
2816
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
1031
2817
  status = response.status;
2818
+ } else if (response && response.status) {
2819
+ maskRedirect(headers, response, request.url);
1032
2820
  }
1033
2821
  metadata = response;
1034
2822
  result = value;
1035
2823
  } else if (result instanceof Response) {
1036
2824
  if (result.headers && result.headers.has("X-Content-Raw")) return result;
1037
- if (instance) {
2825
+ if (scripted) {
1038
2826
  if (result.headers) {
1039
2827
  mergeResponseHeaders(headers, result.headers);
1040
2828
  }
1041
- if (result.status && (result.status < 300 || result.status >= 400)) {
2829
+ if (result.status && !validRedirectStatuses.has(result.status)) {
1042
2830
  status = result.status;
2831
+ } else if (result.status) {
2832
+ maskRedirect(headers, result, request.url);
1043
2833
  }
1044
2834
  metadata = result;
1045
2835
  if (result.body == null) {
@@ -1048,7 +2838,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1048
2838
  }
1049
2839
  }
1050
2840
  if (collectsFlight) {
1051
- result = await foldFlightData(flightHook, event, headers, {
2841
+ result = await foldFlightData(flightHooks, event, headers, {
1052
2842
  id: functionId,
1053
2843
  value: result,
1054
2844
  response: metadata,
@@ -1057,20 +2847,41 @@ async function handleServerFunctionRequest(request, options = {}) {
1057
2847
  }, flightContext);
1058
2848
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1059
2849
  }
1060
- if (!instance) {
1061
- if (handleNoJS) return handleNoJS(result, request, parsed);
2850
+ if (!scripted) {
2851
+ if (handleNoJS) {
2852
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2853
+ }
1062
2854
  if (result instanceof Response) return result;
1063
- return encodeResult(result, headers, 200, codec, request.signal);
2855
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1064
2856
  }
1065
- return encodeResult(result, headers, status, codec, request.signal);
2857
+ if (status === 304) warnScripted304(functionId);
2858
+ if (live) return encodeLiveResult(result, headers, status, codec, request, scope);
2859
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1066
2860
  } catch (x) {
1067
- if (x instanceof Response || isResponseEnvelope(x)) {
1068
- if (transformResult) {
2861
+ const respondThrown = value => {
2862
+ const safe = wireServerFunctionError(value, "thrown", event);
2863
+ if (!scripted) {
2864
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2865
+ const message = safe instanceof Error ? safe.message : String(safe);
2866
+ return new Response(DEV ? message : null, {
2867
+ status: 500
2868
+ });
2869
+ }
2870
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
2871
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2872
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
2873
+ };
2874
+ if (transformResult) {
2875
+ try {
1069
2876
  x = await transformResult(event, x, {
1070
2877
  ...flightContext,
1071
2878
  thrown: true
1072
2879
  });
2880
+ } catch (hookError) {
2881
+ return respondThrown(hookError);
1073
2882
  }
2883
+ }
2884
+ if (x instanceof Response || isResponseEnvelope(x)) {
1074
2885
  let status = 200;
1075
2886
  let metadata;
1076
2887
  if (isResponseEnvelope(x)) {
@@ -1081,8 +2892,10 @@ async function handleServerFunctionRequest(request, options = {}) {
1081
2892
  if (response && response.headers) {
1082
2893
  mergeResponseHeaders(headers, response.headers);
1083
2894
  }
1084
- if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
2895
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
1085
2896
  status = response.status;
2897
+ } else if (response && response.status) {
2898
+ maskRedirect(headers, response, request.url);
1086
2899
  }
1087
2900
  metadata = response;
1088
2901
  x = value;
@@ -1090,8 +2903,10 @@ async function handleServerFunctionRequest(request, options = {}) {
1090
2903
  if (x.headers) {
1091
2904
  mergeResponseHeaders(headers, x.headers);
1092
2905
  }
1093
- if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
2906
+ if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
1094
2907
  status = x.status;
2908
+ } else if (x.status) {
2909
+ maskRedirect(headers, x, request.url);
1095
2910
  }
1096
2911
  metadata = x;
1097
2912
  if (x.body == null) {
@@ -1099,7 +2914,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1099
2914
  }
1100
2915
  }
1101
2916
  if (collectsFlight) {
1102
- x = await foldFlightData(flightHook, event, headers, {
2917
+ x = await foldFlightData(flightHooks, event, headers, {
1103
2918
  id: functionId,
1104
2919
  value: x,
1105
2920
  response: metadata,
@@ -1107,31 +2922,59 @@ async function handleServerFunctionRequest(request, options = {}) {
1107
2922
  thrown: true
1108
2923
  }, flightContext);
1109
2924
  if (x instanceof Response && x.headers.has("X-Content-Raw")) {
2925
+ x = ownResponse(x);
1110
2926
  x.headers.set(ERROR_HEADER, "true");
1111
2927
  return x;
1112
2928
  }
1113
2929
  }
1114
2930
  headers.set(ERROR_HEADER, "true");
1115
- if (!instance) {
2931
+ if (!scripted) {
1116
2932
  if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
1117
2933
  if (x instanceof Response) return x;
1118
2934
  }
1119
- return encodeResult(x, headers, status, codec, request.signal);
1120
- }
1121
- const safe = sanitizeServerError(x);
1122
- if (!instance) {
1123
- if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1124
- const message = safe instanceof Error ? safe.message : String(safe);
1125
- return new Response(DEV ? message : null, {
1126
- status: 500
1127
- });
2935
+ if (scripted && status === 304) warnScripted304(functionId);
2936
+ return encodeResult(x, headers, status, codec, request.signal, scope);
1128
2937
  }
1129
- const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1130
- headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
1131
- return encodeResult(safe, headers, 200, codec, request.signal);
2938
+ return respondThrown(x);
1132
2939
  }
1133
2940
  };
1134
- return commitEventResponse(await dispatch(), event);
2941
+ const response = commitEventResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())), event);
2942
+ return finish(protectsRequest ? withCSRFVary(response) : response);
2943
+ }
2944
+ function ownResponse(response) {
2945
+ try {
2946
+ return new Response(response.body, response);
2947
+ } catch {
2948
+ return response;
2949
+ }
2950
+ }
2951
+ function finalizeTransportResponse(response, method) {
2952
+ const stripBody = method === "HEAD" && response.body !== null;
2953
+ const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
2954
+ if (stripBody || defaultsCache) {
2955
+ try {
2956
+ if (defaultsCache) {
2957
+ response.headers.set("Cache-Control", "no-store");
2958
+ }
2959
+ if (!stripBody) return response;
2960
+ response.body.cancel().catch(() => {});
2961
+ return new Response(null, {
2962
+ status: response.status,
2963
+ statusText: response.statusText,
2964
+ headers: response.headers
2965
+ });
2966
+ } catch {
2967
+ const headers = new Headers(response.headers);
2968
+ if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
2969
+ if (stripBody) response.body.cancel().catch(() => {});
2970
+ return new Response(stripBody ? null : response.body, {
2971
+ status: response.status,
2972
+ statusText: response.statusText,
2973
+ headers
2974
+ });
2975
+ }
2976
+ }
2977
+ return response;
1135
2978
  }
1136
2979
 
1137
- export { ERROR_HEADER, FLASH_COOKIE, FUNCTION_HEADER, GENERIC_SERVER_ERROR_MESSAGE, GET, INSTANCE_HEADER, SINGLE_FLIGHT_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, handleServerFunctionRequest, hasFlashCookie, isServerFunction, live, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, setServerFunctionsDev, subscribeFlightData, withMeta };
2980
+ export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, 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 };