@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.21

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