@solidjs/web 2.0.0-beta.31 → 2.0.0-beta.32

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 (64) hide show
  1. package/README.md +1 -6
  2. package/dist/dev.cjs +234 -45
  3. package/dist/dev.js +221 -42
  4. package/dist/server.cjs +456 -123
  5. package/dist/server.js +445 -120
  6. package/dist/web.cjs +234 -45
  7. package/dist/web.js +221 -42
  8. package/frames/dist/client.cjs +217 -112
  9. package/frames/dist/client.dev.cjs +217 -112
  10. package/frames/dist/client.dev.js +218 -113
  11. package/frames/dist/client.js +218 -113
  12. package/frames/dist/server.cjs +488 -177
  13. package/frames/dist/server.js +489 -179
  14. package/package.json +55 -4
  15. package/serialization/dist/serialization.cjs +8 -0
  16. package/serialization/dist/serialization.js +1 -0
  17. package/serialization/types/index.d.ts +173 -6
  18. package/serialization/types-cjs/index.d.cts +173 -6
  19. package/server-functions/dist/client.cjs +46 -9
  20. package/server-functions/dist/client.js +47 -11
  21. package/server-functions/dist/rich-args.cjs +11 -0
  22. package/server-functions/dist/rich-args.js +9 -0
  23. package/server-functions/dist/server.cjs +275 -126
  24. package/server-functions/dist/server.dev.cjs +1053 -0
  25. package/server-functions/dist/server.dev.js +1021 -0
  26. package/server-functions/dist/server.js +273 -127
  27. package/server-functions/package.json +10 -0
  28. package/server-functions/rich-args/package.json +20 -0
  29. package/storage/types/index.d.ts +1 -1
  30. package/storage/types-cjs/index.d.cts +1 -1
  31. package/types/client.d.ts +127 -6
  32. package/types/core.d.ts +3 -1
  33. package/types/frames/client.d.ts +15 -1
  34. package/types/frames/frame-client.d.ts +37 -7
  35. package/types/frames/frame-sink.d.ts +26 -3
  36. package/types/frames/frame-transport.d.ts +39 -7
  37. package/types/frames/serializer.d.ts +173 -6
  38. package/types/frames/server.d.ts +22 -0
  39. package/types/index.d.ts +2 -3
  40. package/types/response.d.ts +45 -0
  41. package/types/serializer.d.ts +173 -6
  42. package/types/server-functions/client.d.ts +1 -0
  43. package/types/server-functions/rich-args.d.ts +10 -0
  44. package/types/server-functions/server.d.ts +98 -0
  45. package/types/server-functions/shared.d.ts +22 -0
  46. package/types/server-mock.d.ts +171 -59
  47. package/types/server.d.ts +188 -36
  48. package/types-cjs/client.d.cts +127 -6
  49. package/types-cjs/core.d.cts +3 -1
  50. package/types-cjs/frames/client.d.cts +15 -1
  51. package/types-cjs/frames/frame-client.d.cts +37 -7
  52. package/types-cjs/frames/frame-sink.d.cts +26 -3
  53. package/types-cjs/frames/frame-transport.d.cts +39 -7
  54. package/types-cjs/frames/serializer.d.cts +173 -6
  55. package/types-cjs/frames/server.d.cts +22 -0
  56. package/types-cjs/index.d.cts +2 -3
  57. package/types-cjs/response.d.cts +45 -0
  58. package/types-cjs/serializer.d.cts +173 -6
  59. package/types-cjs/server-functions/client.d.cts +1 -0
  60. package/types-cjs/server-functions/rich-args.d.cts +10 -0
  61. package/types-cjs/server-functions/server.d.cts +98 -0
  62. package/types-cjs/server-functions/shared.d.cts +22 -0
  63. package/types-cjs/server-mock.d.cts +171 -59
  64. package/types-cjs/server.d.cts +188 -36
@@ -1,13 +1,17 @@
1
1
  'use strict';
2
2
 
3
- var solidJs = require('solid-js');
4
3
  var seroval = require('seroval');
5
4
  var web = require('seroval-plugins/web');
5
+ var solidJs = require('solid-js');
6
6
 
7
7
  const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
8
8
  function isResponseEnvelope(value) {
9
9
  return !!(value && typeof value === "object" && value[ENVELOPE]);
10
10
  }
11
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
12
+ function isSafeError(value) {
13
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
14
+ }
11
15
  const REVALIDATE_HEADER = "X-Revalidate";
12
16
 
13
17
  seroval.Feature.AggregateError | seroval.Feature.BigIntTypedArray;
@@ -57,11 +61,6 @@ function createJSONDeserializer(options) {
57
61
  };
58
62
  }
59
63
 
60
- const RequestContext = Symbol.for("solid.RequestContext");
61
- function getRequestEvent() {
62
- 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;
63
- }
64
-
65
64
  const codecConfig = {
66
65
  codec: undefined
67
66
  };
@@ -126,10 +125,6 @@ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
126
125
  function hasFlashCookie(cookieHeader) {
127
126
  return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
128
127
  }
129
- function matchFlashCookie(cookieHeader) {
130
- const match = cookieHeader && cookieHeader.match(FLASH_MATCHER);
131
- return match ? match[1] : undefined;
132
- }
133
128
  function clearFlashCookie() {
134
129
  return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
135
130
  }
@@ -237,13 +232,11 @@ async function extractBody(source, codecOptions) {
237
232
  return undefined;
238
233
  }
239
234
  function createChunk(data) {
240
- const encodeData = new TextEncoder().encode(data);
235
+ const encoder = new TextEncoder();
236
+ const encodeData = encoder.encode(data);
241
237
  const bytes = encodeData.length;
242
- const baseHex = bytes.toString(16);
243
- const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex;
244
- const head = new TextEncoder().encode(`;0x${totalHex};`);
245
238
  const chunk = new Uint8Array(12 + bytes);
246
- chunk.set(head);
239
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
247
240
  chunk.set(encodeData, 12);
248
241
  return chunk;
249
242
  }
@@ -275,8 +268,8 @@ class ChunkReader {
275
268
  }
276
269
  await this.readChunk();
277
270
  }
278
- const head = new TextDecoder().decode(this.buffer.subarray(1, 11));
279
- const bytes = Number.parseInt(head, 16);
271
+ const decoder = new TextDecoder();
272
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
280
273
  if (Number.isNaN(bytes)) {
281
274
  throw new Error("Malformed server function stream.");
282
275
  }
@@ -286,7 +279,7 @@ class ChunkReader {
286
279
  }
287
280
  await this.readChunk();
288
281
  }
289
- const partial = new TextDecoder().decode(this.buffer.subarray(12, 12 + bytes));
282
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
290
283
  this.buffer = this.buffer.subarray(12 + bytes);
291
284
  return {
292
285
  done: false,
@@ -357,6 +350,114 @@ async function decodeResponsePayload(response, codecOptions) {
357
350
  };
358
351
  }
359
352
 
353
+ function parseCookieHeader(header) {
354
+ const cookies = {};
355
+ if (!header) return cookies;
356
+ for (const part of header.split(";")) {
357
+ const eq = part.indexOf("=");
358
+ if (eq < 0) continue;
359
+ const name = decodeSafe(part.slice(0, eq).trim());
360
+ let value = part.slice(eq + 1).trim();
361
+ if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
362
+ value = value.slice(1, -1);
363
+ }
364
+ cookies[name] = decodeSafe(value);
365
+ }
366
+ return cookies;
367
+ }
368
+ function decodeSafe(text) {
369
+ try {
370
+ return decodeURIComponent(text);
371
+ } catch {
372
+ return text;
373
+ }
374
+ }
375
+ function serializeCookie(name, value, options = {}) {
376
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
377
+ cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
378
+ if (options.domain) cookie += `; Domain=${options.domain}`;
379
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
380
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
381
+ if (options.httpOnly) cookie += "; HttpOnly";
382
+ if (options.secure) cookie += "; Secure";
383
+ if (options.sameSite) {
384
+ const sameSite = options.sameSite.toLowerCase();
385
+ cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
386
+ }
387
+ return cookie;
388
+ }
389
+
390
+ const RequestContext = Symbol.for("solid.RequestContext");
391
+ function getRequestEvent() {
392
+ 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;
393
+ }
394
+ function reportLostHeaderWrite(method, name) {
395
+ 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).";
396
+ console.error(message);
397
+ }
398
+ function commitResponseStub(stub, {
399
+ allowLateLocation = false
400
+ } = {}) {
401
+ if (!stub || stub.committed) return stub;
402
+ stub.committed = true;
403
+ const headers = stub.headers;
404
+ if (!headers || typeof headers.set !== "function") return stub;
405
+ for (const method of ["set", "append", "delete"]) {
406
+ const original = headers[method].bind(headers);
407
+ headers[method] = function (name, ...rest) {
408
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
409
+ return original(name, ...rest);
410
+ }
411
+ reportLostHeaderWrite(method, name);
412
+ };
413
+ }
414
+ return stub;
415
+ }
416
+ function copyInitHeaders(init) {
417
+ if (!init || !init.getSetCookie) return new Headers(init);
418
+ const headers = new Headers();
419
+ init.forEach((value, key) => {
420
+ if (key !== "set-cookie") headers.append(key, value);
421
+ });
422
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
423
+ return headers;
424
+ }
425
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
426
+ function fillsStubGap(key, headers, response) {
427
+ if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
428
+ if (response.body === null && (key === "content-type" || key === "content-length")) return false;
429
+ return !headers.has(key);
430
+ }
431
+ function commitEventResponse(response, event = getRequestEvent()) {
432
+ const stub = event && event.response;
433
+ if (!stub || !stub.headers || stub.committed) return response;
434
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
435
+ commitResponseStub(stub);
436
+ let hasGaps = false;
437
+ stub.headers.forEach((value, key) => {
438
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
439
+ });
440
+ if (!cookies.length && !hasGaps) return response;
441
+ try {
442
+ for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
443
+ stub.headers.forEach((value, key) => {
444
+ if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
445
+ });
446
+ return response;
447
+ } catch {
448
+ const headers = copyInitHeaders(response.headers);
449
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
450
+ stub.headers.forEach((value, key) => {
451
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
452
+ });
453
+ return new Response(response.body, {
454
+ status: response.status,
455
+ statusText: response.statusText,
456
+ headers
457
+ });
458
+ }
459
+ }
460
+
360
461
  function encodeInputValue(value) {
361
462
  if (value instanceof FormData) return {
362
463
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -386,13 +487,16 @@ function encodeFlashCookie(url, result, input, thrown) {
386
487
  thrown: !!thrown,
387
488
  input: input.map(encodeInputValue)
388
489
  };
389
- return `${FLASH_COOKIE}=${encodeURIComponent(JSON.stringify(payload))}; Secure; HttpOnly; Path=/`;
490
+ return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
491
+ secure: true,
492
+ httpOnly: true
493
+ });
390
494
  }
391
495
  function decodeFlashCookie(cookieHeader) {
392
- const match = matchFlashCookie(cookieHeader);
496
+ const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
393
497
  if (!match) return;
394
498
  try {
395
- const payload = JSON.parse(decodeURIComponent(match));
499
+ const payload = JSON.parse(match);
396
500
  if (!payload || !payload.result) return;
397
501
  const result = payload.error ? new Error(payload.result) : payload.result;
398
502
  return {
@@ -408,6 +512,7 @@ function decodeFlashCookie(cookieHeader) {
408
512
 
409
513
  const config = {
410
514
  provideEvent: undefined,
515
+ wrapInvocation: undefined,
411
516
  collectFlightData: undefined,
412
517
  transformResult: undefined,
413
518
  transformFlightResult: undefined,
@@ -417,6 +522,7 @@ const config = {
417
522
  };
418
523
  function configureServerFunctionsServer({
419
524
  provideEvent,
525
+ wrapInvocation,
420
526
  collectFlightData,
421
527
  transformResult,
422
528
  transformFlightResult,
@@ -426,6 +532,7 @@ function configureServerFunctionsServer({
426
532
  codec
427
533
  } = {}) {
428
534
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
535
+ if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
429
536
  if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
430
537
  if (transformResult !== undefined) config.transformResult = transformResult;
431
538
  if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
@@ -491,7 +598,13 @@ function createServerReference({
491
598
  });
492
599
  evt.serverOnly = true;
493
600
  const result = provideEvent(evt, () => {
494
- return fn.apply(thisArg, args);
601
+ const run = () => fn.apply(thisArg, args);
602
+ return config.wrapInvocation ? config.wrapInvocation(run, {
603
+ id,
604
+ args,
605
+ event: evt,
606
+ direct: true
607
+ }) : run();
495
608
  });
496
609
  const transform = config.transformDirectResult;
497
610
  if (transform && result && typeof result.then === "function") {
@@ -633,6 +746,16 @@ function foldSetCookies(headers, setCookies) {
633
746
  if (serialized) folded.set("cookie", serialized);
634
747
  return folded;
635
748
  }
749
+ function mergeResponseHeaders(target, source) {
750
+ source.forEach((value, key) => {
751
+ if (key !== "set-cookie") target.append(key, value);
752
+ });
753
+ if (source.getSetCookie) {
754
+ for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
755
+ } else if (source.has("set-cookie")) {
756
+ target.append("Set-Cookie", source.get("set-cookie"));
757
+ }
758
+ }
636
759
  const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
637
760
  function createNoJSHandler({
638
761
  base = ""
@@ -647,7 +770,8 @@ function createNoJSHandler({
647
770
  let status = 303;
648
771
  let headers;
649
772
  if (result instanceof Response) {
650
- headers = new Headers(result.headers);
773
+ headers = new Headers();
774
+ mergeResponseHeaders(headers, result.headers);
651
775
  if (result.headers.has("Location")) {
652
776
  headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
653
777
  if (validRedirectStatuses.has(result.status)) status = result.status;
@@ -700,13 +824,23 @@ function encodeResult(value, headers, status, codec) {
700
824
  headers
701
825
  });
702
826
  }
827
+ const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
828
+ let DEV = false === true;
829
+ function setServerFunctionsDev(dev) {
830
+ DEV = !!dev;
831
+ }
832
+ function sanitizeServerError(value) {
833
+ if (DEV) return value;
834
+ if (isSafeError(value)) return value;
835
+ return new Error(GENERIC_SERVER_ERROR_MESSAGE);
836
+ }
703
837
  async function handleServerFunctionRequest(request, options = {}) {
704
838
  const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
705
839
  const url = new URL(request.url);
706
840
  const instance = request.headers.get(INSTANCE_HEADER);
707
841
  const functionId = resolveFunctionId(request, url);
708
842
  if (!functionId) {
709
- return new Response(process.env.NODE_ENV === "development" ? "Server function not found" : null, {
843
+ return new Response(DEV ? "Server function not found" : null, {
710
844
  status: 404
711
845
  });
712
846
  }
@@ -714,12 +848,12 @@ async function handleServerFunctionRequest(request, options = {}) {
714
848
  try {
715
849
  serverFunction = getServerFunction(functionId);
716
850
  } catch {
717
- return new Response(process.env.NODE_ENV === "development" ? `Unknown server function: ${functionId}` : null, {
851
+ return new Response(DEV ? `Unknown server function: ${functionId}` : null, {
718
852
  status: 404
719
853
  });
720
854
  }
721
855
  if (request.method === "GET" && METHODS.get(functionId) !== "GET") {
722
- return new Response(process.env.NODE_ENV === "development" ? `Method not allowed for server function: ${functionId}` : null, {
856
+ return new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
723
857
  status: 405,
724
858
  headers: {
725
859
  Allow: "POST"
@@ -733,6 +867,7 @@ async function handleServerFunctionRequest(request, options = {}) {
733
867
  const provide = options.provideEvent || provideEvent;
734
868
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
735
869
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
870
+ const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
736
871
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
737
872
  const handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS !== undefined ? config.handleNoJS : isFormPost(request) ? defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler()) : undefined;
738
873
  const collectsFlight = !!(flightHook && instance && request.headers.has(SINGLE_FLIGHT_HEADER));
@@ -747,136 +882,148 @@ async function handleServerFunctionRequest(request, options = {}) {
747
882
  transformFlightResult
748
883
  };
749
884
  const headers = new Headers();
750
- try {
751
- let result = await provide(event, async () => {
752
- INVOCATIONS.set(event, {
753
- id: functionId
885
+ const dispatch = async () => {
886
+ try {
887
+ let result = await provide(event, async () => {
888
+ INVOCATIONS.set(event, {
889
+ id: functionId
890
+ });
891
+ const run = () => serverFunction(...parsed);
892
+ return wrapInvocation ? wrapInvocation(run, {
893
+ id: functionId,
894
+ args: parsed,
895
+ event,
896
+ request,
897
+ direct: false
898
+ }) : run();
754
899
  });
755
- return serverFunction(...parsed);
756
- });
757
- if (transformResult) {
758
- result = await transformResult(event, result, flightContext);
759
- }
760
- let status = 200;
761
- let metadata;
762
- if (isResponseEnvelope(result)) {
763
- const {
764
- response,
765
- value
766
- } = result;
767
- if (!instance && !handleNoJS && response && response.body) {
768
- return response;
769
- }
770
- if (response && response.headers) {
771
- response.headers.forEach((val, key) => headers.append(key, val));
772
- }
773
- if (response && response.status && (response.status < 300 || response.status >= 400)) {
774
- status = response.status;
775
- }
776
- metadata = response;
777
- result = value;
778
- } else if (result instanceof Response) {
779
- if (result.headers && result.headers.has("X-Content-Raw")) return result;
780
- if (instance) {
781
- if (result.headers) {
782
- result.headers.forEach((value, key) => headers.append(key, value));
783
- }
784
- if (result.status && (result.status < 300 || result.status >= 400)) {
785
- status = result.status;
786
- }
787
- metadata = result;
788
- if (result.body == null) {
789
- result = null;
790
- }
791
- }
792
- }
793
- if (collectsFlight) {
794
- result = await foldFlightData(flightHook, event, headers, {
795
- id: functionId,
796
- value: result,
797
- response: metadata,
798
- request,
799
- thrown: false
800
- }, flightContext);
801
- if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
802
- }
803
- if (!instance) {
804
- if (handleNoJS) return handleNoJS(result, request, parsed);
805
- if (result instanceof Response) return result;
806
- return encodeResult(result, headers, 200, codec);
807
- }
808
- return encodeResult(result, headers, status, codec);
809
- } catch (x) {
810
- if (x instanceof Response || isResponseEnvelope(x)) {
811
900
  if (transformResult) {
812
- x = await transformResult(event, x, {
813
- ...flightContext,
814
- thrown: true
815
- });
901
+ result = await transformResult(event, result, flightContext);
816
902
  }
817
903
  let status = 200;
818
904
  let metadata;
819
- if (isResponseEnvelope(x)) {
905
+ if (isResponseEnvelope(result)) {
820
906
  const {
821
907
  response,
822
908
  value
823
- } = x;
909
+ } = result;
910
+ if (!instance && !handleNoJS && response && response.body) {
911
+ return response;
912
+ }
824
913
  if (response && response.headers) {
825
- response.headers.forEach((val, key) => headers.append(key, val));
914
+ mergeResponseHeaders(headers, response.headers);
826
915
  }
827
- if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
916
+ if (response && response.status && (response.status < 300 || response.status >= 400)) {
828
917
  status = response.status;
829
918
  }
830
919
  metadata = response;
831
- x = value;
832
- } else if (x instanceof Response) {
833
- if (x.headers) {
834
- x.headers.forEach((value, key) => headers.append(key, value));
835
- }
836
- if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
837
- status = x.status;
838
- }
839
- metadata = x;
840
- if (x.body == null) {
841
- x = null;
920
+ result = value;
921
+ } else if (result instanceof Response) {
922
+ if (result.headers && result.headers.has("X-Content-Raw")) return result;
923
+ if (instance) {
924
+ if (result.headers) {
925
+ mergeResponseHeaders(headers, result.headers);
926
+ }
927
+ if (result.status && (result.status < 300 || result.status >= 400)) {
928
+ status = result.status;
929
+ }
930
+ metadata = result;
931
+ if (result.body == null) {
932
+ result = null;
933
+ }
842
934
  }
843
935
  }
844
936
  if (collectsFlight) {
845
- x = await foldFlightData(flightHook, event, headers, {
937
+ result = await foldFlightData(flightHook, event, headers, {
846
938
  id: functionId,
847
- value: x,
939
+ value: result,
848
940
  response: metadata,
849
941
  request,
850
- thrown: true
942
+ thrown: false
851
943
  }, flightContext);
852
- if (x instanceof Response && x.headers.has("X-Content-Raw")) {
853
- x.headers.set(ERROR_HEADER, "true");
854
- return x;
944
+ if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
945
+ }
946
+ if (!instance) {
947
+ if (handleNoJS) return handleNoJS(result, request, parsed);
948
+ if (result instanceof Response) return result;
949
+ return encodeResult(result, headers, 200, codec);
950
+ }
951
+ return encodeResult(result, headers, status, codec);
952
+ } catch (x) {
953
+ if (x instanceof Response || isResponseEnvelope(x)) {
954
+ if (transformResult) {
955
+ x = await transformResult(event, x, {
956
+ ...flightContext,
957
+ thrown: true
958
+ });
959
+ }
960
+ let status = 200;
961
+ let metadata;
962
+ if (isResponseEnvelope(x)) {
963
+ const {
964
+ response,
965
+ value
966
+ } = x;
967
+ if (response && response.headers) {
968
+ mergeResponseHeaders(headers, response.headers);
969
+ }
970
+ if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
971
+ status = response.status;
972
+ }
973
+ metadata = response;
974
+ x = value;
975
+ } else if (x instanceof Response) {
976
+ if (x.headers) {
977
+ mergeResponseHeaders(headers, x.headers);
978
+ }
979
+ if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
980
+ status = x.status;
981
+ }
982
+ metadata = x;
983
+ if (x.body == null) {
984
+ x = null;
985
+ }
986
+ }
987
+ if (collectsFlight) {
988
+ x = await foldFlightData(flightHook, event, headers, {
989
+ id: functionId,
990
+ value: x,
991
+ response: metadata,
992
+ request,
993
+ thrown: true
994
+ }, flightContext);
995
+ if (x instanceof Response && x.headers.has("X-Content-Raw")) {
996
+ x.headers.set(ERROR_HEADER, "true");
997
+ return x;
998
+ }
999
+ }
1000
+ headers.set(ERROR_HEADER, "true");
1001
+ if (!instance) {
1002
+ if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
1003
+ if (x instanceof Response) return x;
855
1004
  }
1005
+ return encodeResult(x, headers, status, codec);
856
1006
  }
857
- headers.set(ERROR_HEADER, "true");
1007
+ const safe = sanitizeServerError(x);
858
1008
  if (!instance) {
859
- if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
860
- if (x instanceof Response) return x;
1009
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1010
+ const message = safe instanceof Error ? safe.message : String(safe);
1011
+ return new Response(DEV ? message : null, {
1012
+ status: 500
1013
+ });
861
1014
  }
862
- return encodeResult(x, headers, status, codec);
863
- }
864
- if (!instance) {
865
- if (handleNoJS) return handleNoJS(x, request, parsed, true);
866
- const message = x instanceof Error ? x.message : String(x);
867
- return new Response(process.env.NODE_ENV === "development" ? message : null, {
868
- status: 500
869
- });
1015
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1016
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
1017
+ return encodeResult(safe, headers, 200, codec);
870
1018
  }
871
- const error = x instanceof Error ? x.message : typeof x === "string" ? x : "true";
872
- headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
873
- return encodeResult(x, headers, 200, codec);
874
- }
1019
+ };
1020
+ return commitEventResponse(await dispatch(), event);
875
1021
  }
876
1022
 
877
1023
  exports.ERROR_HEADER = ERROR_HEADER;
878
1024
  exports.FLASH_COOKIE = FLASH_COOKIE;
879
1025
  exports.FUNCTION_HEADER = FUNCTION_HEADER;
1026
+ exports.GENERIC_SERVER_ERROR_MESSAGE = GENERIC_SERVER_ERROR_MESSAGE;
880
1027
  exports.GET = GET;
881
1028
  exports.INSTANCE_HEADER = INSTANCE_HEADER;
882
1029
  exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
@@ -900,5 +1047,7 @@ exports.hasFlashCookie = hasFlashCookie;
900
1047
  exports.isServerFunction = isServerFunction;
901
1048
  exports.registerServerFunction = registerServerFunction;
902
1049
  exports.registerServerReference = registerServerReference;
1050
+ exports.sanitizeServerError = sanitizeServerError;
1051
+ exports.setServerFunctionsDev = setServerFunctionsDev;
903
1052
  exports.subscribeFlightData = subscribeFlightData;
904
1053
  exports.withMeta = withMeta;