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

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