@solidjs/web 2.0.0-experimental.9 → 2.0.0-rc.0

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 (85) hide show
  1. package/README.md +22 -4
  2. package/dist/dev.cjs +1585 -225
  3. package/dist/dev.js +1510 -201
  4. package/dist/server.cjs +2642 -264
  5. package/dist/server.js +2542 -217
  6. package/dist/web.cjs +1523 -218
  7. package/dist/web.js +1448 -194
  8. package/frames/dist/client.cjs +1916 -0
  9. package/frames/dist/client.dev.cjs +1933 -0
  10. package/frames/dist/client.dev.js +1921 -0
  11. package/frames/dist/client.js +1904 -0
  12. package/frames/dist/server.cjs +3667 -0
  13. package/frames/dist/server.js +3654 -0
  14. package/frames/package.json +30 -0
  15. package/package.json +349 -37
  16. package/serialization/decode/package.json +20 -0
  17. package/serialization/dist/decode.cjs +110 -0
  18. package/serialization/dist/decode.js +104 -0
  19. package/serialization/dist/serialization.cjs +232 -0
  20. package/serialization/dist/serialization.js +215 -0
  21. package/serialization/package.json +20 -0
  22. package/serialization/types/index.d.ts +182 -0
  23. package/serialization/types/serializer-decode.d.ts +182 -0
  24. package/serialization/types-cjs/index.d.cts +182 -0
  25. package/serialization/types-cjs/package.json +3 -0
  26. package/serialization/types-cjs/serializer-decode.d.cts +182 -0
  27. package/server-functions/dist/client.cjs +646 -0
  28. package/server-functions/dist/client.js +617 -0
  29. package/server-functions/dist/rich-args.cjs +11 -0
  30. package/server-functions/dist/rich-args.js +9 -0
  31. package/server-functions/dist/server.cjs +1077 -0
  32. package/server-functions/dist/server.dev.cjs +1077 -0
  33. package/server-functions/dist/server.dev.js +1045 -0
  34. package/server-functions/dist/server.js +1045 -0
  35. package/server-functions/package.json +40 -0
  36. package/server-functions/rich-args/package.json +20 -0
  37. package/storage/package.json +8 -3
  38. package/storage/types/index.d.ts +26 -0
  39. package/storage/types-cjs/index.d.cts +28 -0
  40. package/storage/types-cjs/package.json +3 -0
  41. package/types/client.d.ts +290 -27
  42. package/types/cookies.d.ts +93 -0
  43. package/types/core.d.ts +6 -2
  44. package/types/frames/client.d.ts +36 -0
  45. package/types/frames/frame-client.d.ts +338 -0
  46. package/types/frames/frame-sink.d.ts +194 -0
  47. package/types/frames/frame-transport.d.ts +222 -0
  48. package/types/frames/serializer.d.ts +182 -0
  49. package/types/frames/server.d.ts +52 -0
  50. package/types/index.d.ts +209 -24
  51. package/types/jsx-properties.d.ts +93 -0
  52. package/types/jsx.d.ts +4150 -1
  53. package/types/response.d.ts +174 -0
  54. package/types/serializer-decode.d.ts +182 -0
  55. package/types/serializer.d.ts +182 -0
  56. package/types/server-functions/client.d.ts +201 -0
  57. package/types/server-functions/flash.d.ts +38 -0
  58. package/types/server-functions/rich-args.d.ts +10 -0
  59. package/types/server-functions/server.d.ts +588 -0
  60. package/types/server-functions/shared.d.ts +523 -0
  61. package/types/server-mock.d.ts +249 -12
  62. package/types/server.d.ts +424 -51
  63. package/types-cjs/client.d.cts +337 -0
  64. package/types-cjs/cookies.d.cts +93 -0
  65. package/types-cjs/core.d.cts +6 -0
  66. package/types-cjs/frames/client.d.cts +36 -0
  67. package/types-cjs/frames/frame-client.d.cts +338 -0
  68. package/types-cjs/frames/frame-sink.d.cts +194 -0
  69. package/types-cjs/frames/frame-transport.d.cts +222 -0
  70. package/types-cjs/frames/serializer.d.cts +182 -0
  71. package/types-cjs/frames/server.d.cts +52 -0
  72. package/types-cjs/index.d.cts +230 -0
  73. package/types-cjs/jsx-properties.d.cts +93 -0
  74. package/types-cjs/jsx.d.cts +4150 -0
  75. package/types-cjs/package.json +3 -0
  76. package/types-cjs/response.d.cts +174 -0
  77. package/types-cjs/serializer-decode.d.cts +182 -0
  78. package/types-cjs/serializer.d.cts +182 -0
  79. package/types-cjs/server-functions/client.d.cts +201 -0
  80. package/types-cjs/server-functions/flash.d.cts +38 -0
  81. package/types-cjs/server-functions/rich-args.d.cts +10 -0
  82. package/types-cjs/server-functions/server.d.cts +588 -0
  83. package/types-cjs/server-functions/shared.d.cts +523 -0
  84. package/types-cjs/server-mock.d.cts +277 -0
  85. package/types-cjs/server.d.cts +523 -0
@@ -0,0 +1,1077 @@
1
+ 'use strict';
2
+
3
+ var solidJs = require('solid-js');
4
+
5
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
6
+ function isResponseEnvelope(value) {
7
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
8
+ }
9
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
10
+ function isSafeError(value) {
11
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
12
+ }
13
+ const REVALIDATE_HEADER = "X-Revalidate";
14
+
15
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
16
+ function getServerFunctionMetadata(fn) {
17
+ if (typeof fn !== "function") return undefined;
18
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
19
+ }
20
+ function isServerFunction(fn) {
21
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
22
+ }
23
+ function withMeta(fn, meta) {
24
+ const metadata = getServerFunctionMetadata(fn);
25
+ if (!metadata) {
26
+ throw new Error("withMeta expects a server function reference");
27
+ }
28
+ Object.assign(metadata, meta);
29
+ return fn;
30
+ }
31
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
32
+ function provideServerFunctionRPC(rpc) {
33
+ globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
34
+ }
35
+
36
+ function parseCookieHeader(header) {
37
+ const cookies = {};
38
+ if (!header) return cookies;
39
+ for (const part of header.split(";")) {
40
+ const eq = part.indexOf("=");
41
+ if (eq < 0) continue;
42
+ const name = decodeSafe(part.slice(0, eq).trim());
43
+ let value = part.slice(eq + 1).trim();
44
+ if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
45
+ value = value.slice(1, -1);
46
+ }
47
+ cookies[name] = decodeSafe(value);
48
+ }
49
+ return cookies;
50
+ }
51
+ function decodeSafe(text) {
52
+ try {
53
+ return decodeURIComponent(text);
54
+ } catch {
55
+ return text;
56
+ }
57
+ }
58
+ function serializeCookie(name, value, options = {}) {
59
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
60
+ cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
61
+ if (options.domain) cookie += `; Domain=${options.domain}`;
62
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
63
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
64
+ if (options.httpOnly) cookie += "; HttpOnly";
65
+ if (options.secure) cookie += "; Secure";
66
+ if (options.sameSite) {
67
+ const sameSite = options.sameSite.toLowerCase();
68
+ cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
69
+ }
70
+ return cookie;
71
+ }
72
+ const FLASH_COOKIE = "flash";
73
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
74
+ function hasFlashCookie(cookieHeader) {
75
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
76
+ }
77
+ function clearFlashCookie() {
78
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
79
+ }
80
+
81
+ const codecConfig = {
82
+ codec: undefined
83
+ };
84
+ function configureServerFunctionsCodec(codec) {
85
+ codecConfig.codec = codec;
86
+ }
87
+ function getServerFunctionsCodec() {
88
+ return codecConfig.codec;
89
+ }
90
+ function subscribeFlightData(consumer) {
91
+ return () => {
92
+ };
93
+ }
94
+ const FUNCTION_HEADER = "X-Server-Function-Id";
95
+ const ERROR_HEADER = "X-Server-Function-Error";
96
+ const ERROR_HEADER_MARKER = "=?1?";
97
+ const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
98
+ function encodeErrorHeaderValue(value) {
99
+ let stripped = String(value).replace(/[\r\n]+/g, "");
100
+ if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
101
+ return stripped;
102
+ }
103
+ if (typeof stripped.toWellFormed === "function") {
104
+ stripped = stripped.toWellFormed();
105
+ } else {
106
+ stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
107
+ }
108
+ return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
109
+ }
110
+ function decodeErrorHeaderValue(value) {
111
+ if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
112
+ return value;
113
+ }
114
+ try {
115
+ return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
116
+ } catch {
117
+ return value;
118
+ }
119
+ }
120
+ const INSTANCE_HEADER = "X-Server-Function-Instance";
121
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
122
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
123
+ const FILE_FORM_KEY = "__server_function_file__";
124
+ const BodyFormat = {
125
+ Serialized: "0",
126
+ String: "1",
127
+ FormData: "2",
128
+ URLSearchParams: "3",
129
+ Blob: "4",
130
+ File: "5",
131
+ ArrayBuffer: "6",
132
+ Uint8Array: "7",
133
+ Json: "8"
134
+ };
135
+ const JSON_SAFE_DEPTH_LIMIT = 10000;
136
+ const EXIT = {};
137
+ function isJSONSafe(value) {
138
+ const stack = [value];
139
+ const ancestors = new Set();
140
+ while (stack.length) {
141
+ const v = stack.pop();
142
+ if (v === EXIT) {
143
+ ancestors.delete(stack.pop());
144
+ continue;
145
+ }
146
+ if (v === null) continue;
147
+ const t = typeof v;
148
+ if (t === "string" || t === "boolean") continue;
149
+ if (t === "number") {
150
+ if (!Number.isFinite(v)) return false;
151
+ continue;
152
+ }
153
+ if (t !== "object") return false;
154
+ if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
155
+ ancestors.add(v);
156
+ stack.push(v, EXIT);
157
+ if (Array.isArray(v)) {
158
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
159
+ } else {
160
+ const proto = Object.getPrototypeOf(v);
161
+ if (proto !== Object.prototype && proto !== null) return false;
162
+ for (const k in v) stack.push(v[k]);
163
+ }
164
+ }
165
+ return true;
166
+ }
167
+ function getHeadersAndBody(body) {
168
+ switch (true) {
169
+ case typeof body === "string":
170
+ return {
171
+ headers: {
172
+ "Content-Type": "text/plain",
173
+ [BODY_FORMAT_HEADER]: BodyFormat.String
174
+ },
175
+ body
176
+ };
177
+ case body instanceof FormData:
178
+ return {
179
+ headers: {
180
+ [BODY_FORMAT_HEADER]: BodyFormat.FormData
181
+ },
182
+ body
183
+ };
184
+ case body instanceof URLSearchParams:
185
+ return {
186
+ headers: {
187
+ "Content-Type": "application/x-www-form-urlencoded",
188
+ [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
189
+ },
190
+ body
191
+ };
192
+ case typeof File !== "undefined" && body instanceof File:
193
+ {
194
+ const formData = new FormData();
195
+ formData.append(FILE_FORM_KEY, body, body.name);
196
+ return {
197
+ headers: {
198
+ [BODY_FORMAT_HEADER]: BodyFormat.File
199
+ },
200
+ body: formData
201
+ };
202
+ }
203
+ case body instanceof Blob:
204
+ return {
205
+ headers: {
206
+ [BODY_FORMAT_HEADER]: BodyFormat.Blob
207
+ },
208
+ body
209
+ };
210
+ case body instanceof ArrayBuffer:
211
+ return {
212
+ headers: {
213
+ [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
214
+ },
215
+ body
216
+ };
217
+ case body instanceof Uint8Array:
218
+ return {
219
+ headers: {
220
+ [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
221
+ },
222
+ body: new Uint8Array(body)
223
+ };
224
+ default:
225
+ return undefined;
226
+ }
227
+ }
228
+ async function extractBody(source, codecOptions) {
229
+ const contentType = source.headers.get("content-type");
230
+ const format = source.headers.get(BODY_FORMAT_HEADER);
231
+ const clone = source.clone();
232
+ switch (true) {
233
+ case format === BodyFormat.Serialized:
234
+ return await deserializeStream(clone, codecOptions);
235
+ case format === BodyFormat.Json:
236
+ return JSON.parse(await clone.text());
237
+ case format === BodyFormat.String:
238
+ return await clone.text();
239
+ case format === BodyFormat.File:
240
+ {
241
+ const formData = await clone.formData();
242
+ return formData.get(FILE_FORM_KEY);
243
+ }
244
+ case format === BodyFormat.FormData:
245
+ case contentType && contentType.startsWith("multipart/form-data"):
246
+ return await clone.formData();
247
+ case format === BodyFormat.URLSearchParams:
248
+ case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
249
+ return new URLSearchParams(await clone.text());
250
+ case format === BodyFormat.Blob:
251
+ return await clone.blob();
252
+ case format === BodyFormat.ArrayBuffer:
253
+ return await clone.arrayBuffer();
254
+ case format === BodyFormat.Uint8Array:
255
+ return new Uint8Array(await clone.arrayBuffer());
256
+ }
257
+ return undefined;
258
+ }
259
+ function createChunk(data) {
260
+ const encoder = new TextEncoder();
261
+ const encodeData = encoder.encode(data);
262
+ const bytes = encodeData.length;
263
+ const chunk = new Uint8Array(12 + bytes);
264
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
265
+ chunk.set(encodeData, 12);
266
+ return chunk;
267
+ }
268
+ class ChunkReader {
269
+ constructor(stream) {
270
+ this.reader = stream.getReader();
271
+ this.buffer = new Uint8Array(0);
272
+ this.done = false;
273
+ }
274
+ async readChunk() {
275
+ const chunk = await this.reader.read();
276
+ if (!chunk.done) {
277
+ const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
278
+ newBuffer.set(this.buffer);
279
+ newBuffer.set(chunk.value, this.buffer.length);
280
+ this.buffer = newBuffer;
281
+ } else {
282
+ this.done = true;
283
+ }
284
+ }
285
+ async next() {
286
+ while (this.buffer.length < 12) {
287
+ if (this.done) {
288
+ if (this.buffer.length === 0) return {
289
+ done: true,
290
+ value: undefined
291
+ };
292
+ throw new Error("Malformed server function stream.");
293
+ }
294
+ await this.readChunk();
295
+ }
296
+ const decoder = new TextDecoder();
297
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
298
+ if (Number.isNaN(bytes)) {
299
+ throw new Error("Malformed server function stream.");
300
+ }
301
+ while (bytes > this.buffer.length - 12) {
302
+ if (this.done) {
303
+ throw new Error("Malformed server function stream.");
304
+ }
305
+ await this.readChunk();
306
+ }
307
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
308
+ this.buffer = this.buffer.subarray(12 + bytes);
309
+ return {
310
+ done: false,
311
+ value: partial
312
+ };
313
+ }
314
+ async drain(interpret) {
315
+ while (true) {
316
+ const result = await this.next();
317
+ if (result.done) {
318
+ break;
319
+ }
320
+ interpret(result.value);
321
+ }
322
+ }
323
+ }
324
+ function serializeStream(value, codecOptions) {
325
+ return new ReadableStream({
326
+ async start(controller) {
327
+ const {
328
+ serializeJSON
329
+ } = await import('@solidjs/web/serialization');
330
+ serializeJSON(value, {
331
+ ...codecOptions,
332
+ onParse(node) {
333
+ controller.enqueue(createChunk(JSON.stringify(node)));
334
+ },
335
+ onDone() {
336
+ controller.close();
337
+ },
338
+ onError(error) {
339
+ controller.error(error);
340
+ }
341
+ });
342
+ }
343
+ });
344
+ }
345
+ async function deserializeStream(source, codecOptions) {
346
+ if (!source.body) {
347
+ throw new Error("missing body");
348
+ }
349
+ const reader = new ChunkReader(source.body);
350
+ const result = await reader.next();
351
+ if (!result.done) {
352
+ const {
353
+ createJSONDeserializer
354
+ } = await import('@solidjs/web/serialization/decode');
355
+ const deserializeChunk = createJSONDeserializer(codecOptions);
356
+ function interpretChunk(chunk) {
357
+ return deserializeChunk(JSON.parse(chunk));
358
+ }
359
+ void reader.drain(interpretChunk);
360
+ return interpretChunk(result.value);
361
+ }
362
+ return undefined;
363
+ }
364
+ async function deserializeString(text, codecOptions) {
365
+ return await deserializeStream(new Response(text), codecOptions);
366
+ }
367
+ async function decodeResponse(response, codecOptions) {
368
+ if (!response.body) return undefined;
369
+ return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
370
+ }
371
+ async function decodeResponsePayload(response, codecOptions) {
372
+ const decoded = await decodeResponse(response, codecOptions);
373
+ if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
374
+ return {
375
+ value: decoded.value,
376
+ flightData: decoded.data
377
+ };
378
+ }
379
+ return {
380
+ value: decoded
381
+ };
382
+ }
383
+
384
+ const RequestContext = Symbol.for("solid.RequestContext");
385
+ function getRequestEvent() {
386
+ return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || solidJs.sharedConfig.context && solidJs.sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
387
+ }
388
+ function reportLostHeaderWrite(method, name) {
389
+ const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
390
+ console.error(message);
391
+ }
392
+ function commitResponseStub(stub, {
393
+ allowLateLocation = false
394
+ } = {}) {
395
+ if (!stub || stub.committed) return stub;
396
+ stub.committed = true;
397
+ const headers = stub.headers;
398
+ if (!headers || typeof headers.set !== "function") return stub;
399
+ for (const method of ["set", "append", "delete"]) {
400
+ const original = headers[method].bind(headers);
401
+ headers[method] = function (name, ...rest) {
402
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
403
+ return original(name, ...rest);
404
+ }
405
+ reportLostHeaderWrite(method, name);
406
+ };
407
+ }
408
+ return stub;
409
+ }
410
+ function copyInitHeaders(init) {
411
+ if (!init || !init.getSetCookie) return new Headers(init);
412
+ const headers = new Headers();
413
+ init.forEach((value, key) => {
414
+ if (key !== "set-cookie") headers.append(key, value);
415
+ });
416
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
417
+ return headers;
418
+ }
419
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
420
+ function fillsStubGap(key, headers, response) {
421
+ if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
422
+ if (response.body === null && (key === "content-type" || key === "content-length")) return false;
423
+ return !headers.has(key);
424
+ }
425
+ function commitEventResponse(response, event = getRequestEvent()) {
426
+ const stub = event && event.response;
427
+ if (!stub || !stub.headers || stub.committed) return response;
428
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
429
+ commitResponseStub(stub);
430
+ let hasGaps = false;
431
+ stub.headers.forEach((value, key) => {
432
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
433
+ });
434
+ if (!cookies.length && !hasGaps) return response;
435
+ try {
436
+ for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
437
+ stub.headers.forEach((value, key) => {
438
+ if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
439
+ });
440
+ return response;
441
+ } catch {
442
+ const headers = copyInitHeaders(response.headers);
443
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
444
+ stub.headers.forEach((value, key) => {
445
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
446
+ });
447
+ return new Response(response.body, {
448
+ status: response.status,
449
+ statusText: response.statusText,
450
+ headers
451
+ });
452
+ }
453
+ }
454
+
455
+ function encodeInputValue(value) {
456
+ if (value instanceof FormData) return {
457
+ $f: [...value.entries()].filter(([, v]) => typeof v === "string")
458
+ };
459
+ if (value instanceof URLSearchParams) return {
460
+ $u: [...value.entries()]
461
+ };
462
+ return value;
463
+ }
464
+ function decodeInputValue(value) {
465
+ if (value && typeof value === "object") {
466
+ if (Array.isArray(value.$f)) {
467
+ const form = new FormData();
468
+ for (const [k, v] of value.$f) form.append(k, v);
469
+ return form;
470
+ }
471
+ if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
472
+ }
473
+ return value;
474
+ }
475
+ function encodeFlashCookie(url, result, input, thrown) {
476
+ const isError = result instanceof Error;
477
+ const payload = {
478
+ url,
479
+ result: isError ? result.message : result,
480
+ error: isError,
481
+ thrown: !!thrown,
482
+ input: input.map(encodeInputValue)
483
+ };
484
+ return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
485
+ secure: true,
486
+ httpOnly: true
487
+ });
488
+ }
489
+ function decodeFlashCookie(cookieHeader) {
490
+ const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
491
+ if (!match) return;
492
+ try {
493
+ const payload = JSON.parse(match);
494
+ if (!payload || !payload.result) return;
495
+ const result = payload.error ? new Error(payload.result) : payload.result;
496
+ return {
497
+ input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
498
+ url: payload.url,
499
+ result: payload.thrown ? undefined : result,
500
+ error: payload.thrown ? result : undefined
501
+ };
502
+ } catch (error) {
503
+ console.error(error);
504
+ }
505
+ }
506
+
507
+ const config = {
508
+ provideEvent: undefined,
509
+ wrapInvocation: undefined,
510
+ collectFlightData: undefined,
511
+ transformResult: undefined,
512
+ transformFlightResult: undefined,
513
+ transformDirectResult: undefined,
514
+ handleNoJS: undefined,
515
+ endpoint: "/_server"
516
+ };
517
+ function configureServerFunctionsServer({
518
+ provideEvent,
519
+ wrapInvocation,
520
+ collectFlightData,
521
+ transformResult,
522
+ transformFlightResult,
523
+ transformDirectResult,
524
+ handleNoJS,
525
+ endpoint,
526
+ codec
527
+ } = {}) {
528
+ if (provideEvent !== undefined) config.provideEvent = provideEvent;
529
+ if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
530
+ if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
531
+ if (transformResult !== undefined) config.transformResult = transformResult;
532
+ if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
533
+ if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
534
+ if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
535
+ if (endpoint !== undefined) config.endpoint = endpoint;
536
+ if (codec !== undefined) configureServerFunctionsCodec(codec);
537
+ }
538
+ function provideEvent(event, fn) {
539
+ if (config.provideEvent) return config.provideEvent(event, fn);
540
+ const ctx = globalThis[RequestContext];
541
+ if (ctx) return ctx.run(event, fn);
542
+ throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
543
+ }
544
+ const REGISTRATIONS = new Map();
545
+ const METHODS = new Map();
546
+ const INVOCATIONS = new WeakMap();
547
+ let rpcProvided = false;
548
+ function provideRPC() {
549
+ if (rpcProvided) return;
550
+ rpcProvided = true;
551
+ provideServerFunctionRPC({
552
+ GET,
553
+ decodeResponse
554
+ });
555
+ }
556
+ function registerServerFunction(id, callback) {
557
+ provideRPC();
558
+ REGISTRATIONS.set(id, callback);
559
+ return callback;
560
+ }
561
+ function getServerFunction(id) {
562
+ const fn = REGISTRATIONS.get(id);
563
+ if (fn) {
564
+ return fn;
565
+ }
566
+ throw new Error("invalid server function: " + id);
567
+ }
568
+ function registerServerReference(id, fn, name) {
569
+ registerServerFunction(id, fn);
570
+ return {
571
+ id,
572
+ fn,
573
+ name
574
+ };
575
+ }
576
+ function createServerReference({
577
+ id,
578
+ fn,
579
+ name
580
+ }) {
581
+ if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
582
+ provideRPC();
583
+ const metadata = name === undefined ? {} : {
584
+ name
585
+ };
586
+ return new Proxy(fn, {
587
+ get(target, prop) {
588
+ if (prop === "id") return id;
589
+ if (prop === "url") {
590
+ return `${config.endpoint}?id=${encodeURIComponent(id)}`;
591
+ }
592
+ if (prop === SERVER_FUNCTION_METADATA) return metadata;
593
+ return target[prop];
594
+ },
595
+ apply(target, thisArg, args) {
596
+ const ogEvt = getRequestEvent();
597
+ if (!ogEvt) throw new Error("Cannot call server function outside of a request");
598
+ const evt = {
599
+ ...ogEvt
600
+ };
601
+ INVOCATIONS.set(evt, {
602
+ id
603
+ });
604
+ evt.serverOnly = true;
605
+ const result = provideEvent(evt, () => {
606
+ const run = () => fn.apply(thisArg, args);
607
+ return config.wrapInvocation ? config.wrapInvocation(run, {
608
+ id,
609
+ args,
610
+ event: evt,
611
+ direct: true
612
+ }) : run();
613
+ });
614
+ const transform = config.transformDirectResult;
615
+ if (transform && result && typeof result.then === "function") {
616
+ return result.then(value => transform(value, {
617
+ id,
618
+ args,
619
+ event: evt
620
+ }));
621
+ }
622
+ return transform ? transform(result, {
623
+ id,
624
+ args,
625
+ event: evt
626
+ }) : result;
627
+ }
628
+ });
629
+ }
630
+ function GET(fn) {
631
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
632
+ throw new Error("GET expects a server function reference");
633
+ }
634
+ METHODS.set(fn.id, "GET");
635
+ return withMeta(fn, {
636
+ method: "GET"
637
+ });
638
+ }
639
+ function getServerFunctionInvocation() {
640
+ return getEventServerFunctionInvocation(getRequestEvent());
641
+ }
642
+ function getEventServerFunctionInvocation(event) {
643
+ return event && INVOCATIONS.get(event);
644
+ }
645
+ function resolveFunctionId(request, url) {
646
+ const reference = request.headers.get(FUNCTION_HEADER);
647
+ if (reference) {
648
+ return reference.split("#")[0];
649
+ }
650
+ return url.searchParams.get("id");
651
+ }
652
+ async function parseArguments(request, url, instance, codec) {
653
+ const parsed = [];
654
+ const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
655
+ if (!instance || request.method === "GET" || bodyFormat !== BodyFormat.Serialized) {
656
+ const args = url.searchParams.get("args");
657
+ if (args) {
658
+ const result = args.startsWith(";0x") ? await deserializeString(args, codec) : JSON.parse(args);
659
+ for (const arg of result) {
660
+ parsed.push(arg);
661
+ }
662
+ }
663
+ }
664
+ if (request.method === "POST" && request.body !== null) {
665
+ const decoded = await extractBody(request.clone(), codec);
666
+ if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
667
+ return decoded;
668
+ }
669
+ parsed.push(decoded);
670
+ }
671
+ return parsed;
672
+ }
673
+ async function foldFlightData(hook, event, headers, outcome, context = {}) {
674
+ if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
675
+ digestOutcome(event, outcome);
676
+ const data = await hook(event, outcome);
677
+ if (data === undefined) return outcome.value;
678
+ headers.set(SINGLE_FLIGHT_HEADER, "true");
679
+ if (context.transformFlightResult) {
680
+ const transformed = await context.transformFlightResult(event, {
681
+ value: outcome.value,
682
+ data
683
+ }, context);
684
+ if (transformed !== undefined) {
685
+ for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
686
+ headers.forEach((value, key) => {
687
+ if (key !== "set-cookie" && !transformed.headers.has(key)) {
688
+ transformed.headers.set(key, value);
689
+ }
690
+ });
691
+ return transformed;
692
+ }
693
+ }
694
+ return outcome.value === undefined ? {
695
+ data
696
+ } : {
697
+ value: outcome.value,
698
+ data
699
+ };
700
+ }
701
+ function digestOutcome(event, outcome) {
702
+ const {
703
+ request,
704
+ response
705
+ } = outcome;
706
+ outcome.revalidateKeys = response?.headers.get(REVALIDATE_HEADER)?.split(",");
707
+ outcome.foldedHeaders = foldSetCookies(request.headers, [...(event.response?.headers?.getSetCookie() ?? []), ...(response?.headers?.getSetCookie() ?? [])]);
708
+ try {
709
+ const referrer = request.headers.get("referer");
710
+ if (referrer) {
711
+ const location = response?.headers.get("Location");
712
+ const target = location ? new URL(location, request.url) : new URL(referrer);
713
+ if (target.origin === new URL(request.url).origin) outcome.targetUrl = target.toString();
714
+ }
715
+ } catch {
716
+ }
717
+ }
718
+ function parseSetCookie(setCookie) {
719
+ const [pair, ...attributes] = setCookie.split(";");
720
+ const eq = pair.indexOf("=");
721
+ if (eq < 0) return undefined;
722
+ const parsed = {
723
+ name: pair.slice(0, eq).trim(),
724
+ value: pair.slice(eq + 1).trim()
725
+ };
726
+ for (const attribute of attributes) {
727
+ const attrEq = attribute.indexOf("=");
728
+ const key = (attrEq < 0 ? attribute : attribute.slice(0, attrEq)).trim().toLowerCase();
729
+ const value = attrEq < 0 ? "" : attribute.slice(attrEq + 1).trim();
730
+ if (key === "max-age") parsed.maxAge = Number(value);else if (key === "expires") parsed.expires = new Date(value);
731
+ }
732
+ return parsed;
733
+ }
734
+ function foldSetCookies(headers, setCookies) {
735
+ const folded = new Headers(headers);
736
+ if (!setCookies.length) return folded;
737
+ const cookies = {};
738
+ for (const pair of folded.get("cookie")?.split(";") ?? []) {
739
+ const eq = pair.indexOf("=");
740
+ if (eq > -1) cookies[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
741
+ }
742
+ for (const setCookie of setCookies) {
743
+ const parsed = parseSetCookie(setCookie);
744
+ if (!parsed) continue;
745
+ if (parsed.maxAge != null && parsed.maxAge <= 0 || parsed.expires != null && parsed.expires.getTime() <= Date.now()) {
746
+ delete cookies[parsed.name];
747
+ } else {
748
+ cookies[parsed.name] = parsed.value;
749
+ }
750
+ }
751
+ folded.delete("cookie");
752
+ const serialized = Object.entries(cookies).map(([name, value]) => `${name}=${value}`).join("; ");
753
+ if (serialized) folded.set("cookie", serialized);
754
+ return folded;
755
+ }
756
+ function mergeResponseHeaders(target, source) {
757
+ source.forEach((value, key) => {
758
+ if (key !== "set-cookie") target.append(key, value);
759
+ });
760
+ if (source.getSetCookie) {
761
+ for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
762
+ } else if (source.has("set-cookie")) {
763
+ target.append("Set-Cookie", source.get("set-cookie"));
764
+ }
765
+ }
766
+ const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
767
+ function createNoJSHandler({
768
+ base = ""
769
+ } = {}) {
770
+ return function handleNoJS(result, request, args, thrown) {
771
+ const url = new URL(request.url);
772
+ let back = new URL(base || "/", url.origin).toString();
773
+ try {
774
+ const referer = request.headers.get("referer");
775
+ if (referer) back = new URL(referer).toString();
776
+ } catch {}
777
+ let status = 303;
778
+ let headers;
779
+ if (result instanceof Response) {
780
+ headers = new Headers();
781
+ mergeResponseHeaders(headers, result.headers);
782
+ if (result.headers.has("Location")) {
783
+ headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
784
+ if (validRedirectStatuses.has(result.status)) status = result.status;
785
+ } else {
786
+ headers.set("Location", back);
787
+ }
788
+ headers.delete("Content-Type");
789
+ headers.delete("Content-Length");
790
+ } else {
791
+ headers = new Headers({
792
+ Location: back
793
+ });
794
+ }
795
+ if (result && !(result instanceof Response)) {
796
+ headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
797
+ }
798
+ return new Response(null, {
799
+ status,
800
+ headers
801
+ });
802
+ };
803
+ }
804
+ let defaultNoJSHandler;
805
+ function isFormPost(request) {
806
+ if (request.method !== "POST" || request.headers.has(BODY_FORMAT_HEADER)) return false;
807
+ const type = request.headers.get("content-type") || "";
808
+ return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
809
+ }
810
+ function serializedResponse(value, headers, codec) {
811
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
812
+ headers.set("Content-Type", "text/plain");
813
+ return new Response(serializeStream(value, codec), {
814
+ headers
815
+ });
816
+ }
817
+ function encodeResult(value, headers, status, codec) {
818
+ const direct = getHeadersAndBody(value);
819
+ if (direct) {
820
+ for (const [key, val] of Object.entries(direct.headers || {})) {
821
+ headers.set(key, val);
822
+ }
823
+ return new Response(direct.body, {
824
+ status,
825
+ headers
826
+ });
827
+ }
828
+ if (value === undefined) {
829
+ return new Response(null, {
830
+ status,
831
+ headers
832
+ });
833
+ }
834
+ try {
835
+ if (isJSONSafe(value)) {
836
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
837
+ headers.set("Content-Type", "application/json");
838
+ return new Response(JSON.stringify(value), {
839
+ status,
840
+ headers
841
+ });
842
+ }
843
+ } catch {
844
+ }
845
+ const response = serializedResponse(value, headers, codec);
846
+ return status === 200 ? response : new Response(response.body, {
847
+ status,
848
+ headers
849
+ });
850
+ }
851
+ const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
852
+ let DEV = false === true;
853
+ function setServerFunctionsDev(dev) {
854
+ DEV = !!dev;
855
+ }
856
+ function sanitizeServerError(value) {
857
+ if (DEV) return value;
858
+ if (isSafeError(value)) return value;
859
+ return new Error(GENERIC_SERVER_ERROR_MESSAGE);
860
+ }
861
+ async function handleServerFunctionRequest(request, options = {}) {
862
+ const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
863
+ const url = new URL(request.url);
864
+ const instance = request.headers.get(INSTANCE_HEADER);
865
+ const functionId = resolveFunctionId(request, url);
866
+ if (!functionId) {
867
+ return new Response(DEV ? "Server function not found" : null, {
868
+ status: 404
869
+ });
870
+ }
871
+ let serverFunction;
872
+ try {
873
+ serverFunction = getServerFunction(functionId);
874
+ } catch {
875
+ return new Response(DEV ? `Unknown server function: ${functionId}` : null, {
876
+ status: 404
877
+ });
878
+ }
879
+ if (request.method === "GET" && METHODS.get(functionId) !== "GET") {
880
+ return new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
881
+ status: 405,
882
+ headers: {
883
+ Allow: "POST"
884
+ }
885
+ });
886
+ }
887
+ const event = options.createEvent ? options.createEvent(request) : {
888
+ request,
889
+ locals: {}
890
+ };
891
+ const provide = options.provideEvent || provideEvent;
892
+ const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
893
+ const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
894
+ const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
895
+ const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
896
+ const handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS !== undefined ? config.handleNoJS : isFormPost(request) ? defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler()) : undefined;
897
+ const collectsFlight = !!(flightHook && instance && request.headers.has(SINGLE_FLIGHT_HEADER));
898
+ const parsed = await parseArguments(request, url, instance, codec);
899
+ const flightContext = {
900
+ id: functionId,
901
+ args: parsed,
902
+ instance,
903
+ request,
904
+ collectsFlight,
905
+ codec,
906
+ transformFlightResult
907
+ };
908
+ const headers = new Headers();
909
+ const dispatch = async () => {
910
+ try {
911
+ let result = await provide(event, async () => {
912
+ INVOCATIONS.set(event, {
913
+ id: functionId
914
+ });
915
+ const run = () => serverFunction(...parsed);
916
+ return wrapInvocation ? wrapInvocation(run, {
917
+ id: functionId,
918
+ args: parsed,
919
+ event,
920
+ request,
921
+ direct: false
922
+ }) : run();
923
+ });
924
+ if (transformResult) {
925
+ result = await transformResult(event, result, flightContext);
926
+ }
927
+ let status = 200;
928
+ let metadata;
929
+ if (isResponseEnvelope(result)) {
930
+ const {
931
+ response,
932
+ value
933
+ } = result;
934
+ if (!instance && !handleNoJS && response && response.body) {
935
+ return response;
936
+ }
937
+ if (response && response.headers) {
938
+ mergeResponseHeaders(headers, response.headers);
939
+ }
940
+ if (response && response.status && (response.status < 300 || response.status >= 400)) {
941
+ status = response.status;
942
+ }
943
+ metadata = response;
944
+ result = value;
945
+ } else if (result instanceof Response) {
946
+ if (result.headers && result.headers.has("X-Content-Raw")) return result;
947
+ if (instance) {
948
+ if (result.headers) {
949
+ mergeResponseHeaders(headers, result.headers);
950
+ }
951
+ if (result.status && (result.status < 300 || result.status >= 400)) {
952
+ status = result.status;
953
+ }
954
+ metadata = result;
955
+ if (result.body == null) {
956
+ result = null;
957
+ }
958
+ }
959
+ }
960
+ if (collectsFlight) {
961
+ result = await foldFlightData(flightHook, event, headers, {
962
+ id: functionId,
963
+ value: result,
964
+ response: metadata,
965
+ request,
966
+ thrown: false
967
+ }, flightContext);
968
+ if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
969
+ }
970
+ if (!instance) {
971
+ if (handleNoJS) return handleNoJS(result, request, parsed);
972
+ if (result instanceof Response) return result;
973
+ return encodeResult(result, headers, 200, codec);
974
+ }
975
+ return encodeResult(result, headers, status, codec);
976
+ } catch (x) {
977
+ if (x instanceof Response || isResponseEnvelope(x)) {
978
+ if (transformResult) {
979
+ x = await transformResult(event, x, {
980
+ ...flightContext,
981
+ thrown: true
982
+ });
983
+ }
984
+ let status = 200;
985
+ let metadata;
986
+ if (isResponseEnvelope(x)) {
987
+ const {
988
+ response,
989
+ value
990
+ } = x;
991
+ if (response && response.headers) {
992
+ mergeResponseHeaders(headers, response.headers);
993
+ }
994
+ if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
995
+ status = response.status;
996
+ }
997
+ metadata = response;
998
+ x = value;
999
+ } else if (x instanceof Response) {
1000
+ if (x.headers) {
1001
+ mergeResponseHeaders(headers, x.headers);
1002
+ }
1003
+ if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
1004
+ status = x.status;
1005
+ }
1006
+ metadata = x;
1007
+ if (x.body == null) {
1008
+ x = null;
1009
+ }
1010
+ }
1011
+ if (collectsFlight) {
1012
+ x = await foldFlightData(flightHook, event, headers, {
1013
+ id: functionId,
1014
+ value: x,
1015
+ response: metadata,
1016
+ request,
1017
+ thrown: true
1018
+ }, flightContext);
1019
+ if (x instanceof Response && x.headers.has("X-Content-Raw")) {
1020
+ x.headers.set(ERROR_HEADER, "true");
1021
+ return x;
1022
+ }
1023
+ }
1024
+ headers.set(ERROR_HEADER, "true");
1025
+ if (!instance) {
1026
+ if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
1027
+ if (x instanceof Response) return x;
1028
+ }
1029
+ return encodeResult(x, headers, status, codec);
1030
+ }
1031
+ const safe = sanitizeServerError(x);
1032
+ if (!instance) {
1033
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1034
+ const message = safe instanceof Error ? safe.message : String(safe);
1035
+ return new Response(DEV ? message : null, {
1036
+ status: 500
1037
+ });
1038
+ }
1039
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1040
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
1041
+ return encodeResult(safe, headers, 200, codec);
1042
+ }
1043
+ };
1044
+ return commitEventResponse(await dispatch(), event);
1045
+ }
1046
+
1047
+ exports.ERROR_HEADER = ERROR_HEADER;
1048
+ exports.FLASH_COOKIE = FLASH_COOKIE;
1049
+ exports.FUNCTION_HEADER = FUNCTION_HEADER;
1050
+ exports.GENERIC_SERVER_ERROR_MESSAGE = GENERIC_SERVER_ERROR_MESSAGE;
1051
+ exports.GET = GET;
1052
+ exports.INSTANCE_HEADER = INSTANCE_HEADER;
1053
+ exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
1054
+ exports.clearFlashCookie = clearFlashCookie;
1055
+ exports.configureServerFunctionsServer = configureServerFunctionsServer;
1056
+ exports.createNoJSHandler = createNoJSHandler;
1057
+ exports.createServerReference = createServerReference;
1058
+ exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
1059
+ exports.decodeFlashCookie = decodeFlashCookie;
1060
+ exports.decodeResponse = decodeResponse;
1061
+ exports.decodeResponsePayload = decodeResponsePayload;
1062
+ exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
1063
+ exports.encodeFlashCookie = encodeFlashCookie;
1064
+ exports.foldSetCookies = foldSetCookies;
1065
+ exports.getEventServerFunctionInvocation = getEventServerFunctionInvocation;
1066
+ exports.getServerFunction = getServerFunction;
1067
+ exports.getServerFunctionInvocation = getServerFunctionInvocation;
1068
+ exports.getServerFunctionMetadata = getServerFunctionMetadata;
1069
+ exports.handleServerFunctionRequest = handleServerFunctionRequest;
1070
+ exports.hasFlashCookie = hasFlashCookie;
1071
+ exports.isServerFunction = isServerFunction;
1072
+ exports.registerServerFunction = registerServerFunction;
1073
+ exports.registerServerReference = registerServerReference;
1074
+ exports.sanitizeServerError = sanitizeServerError;
1075
+ exports.setServerFunctionsDev = setServerFunctionsDev;
1076
+ exports.subscribeFlightData = subscribeFlightData;
1077
+ exports.withMeta = withMeta;