@solidjs/web 2.0.0-rc.5 → 2.0.0-rc.7

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 (52) hide show
  1. package/dist/server.cjs +122 -38
  2. package/dist/server.dev.cjs +3794 -0
  3. package/dist/server.dev.js +3627 -0
  4. package/dist/server.js +123 -39
  5. package/dist/web.cjs +102 -366
  6. package/dist/{dev.cjs → web.dev.cjs} +153 -376
  7. package/dist/{dev.js → web.dev.js} +155 -374
  8. package/dist/web.js +104 -364
  9. package/frames/dist/client.cjs +11 -3
  10. package/frames/dist/client.dev.cjs +11 -3
  11. package/frames/dist/client.dev.js +11 -3
  12. package/frames/dist/client.js +11 -3
  13. package/frames/dist/server.cjs +320 -53
  14. package/frames/dist/server.dev.cjs +4584 -0
  15. package/frames/dist/server.dev.js +4571 -0
  16. package/frames/dist/server.js +320 -53
  17. package/frames/package.json +10 -0
  18. package/package.json +78 -8
  19. package/serialization/dist/decode.cjs +18 -4
  20. package/serialization/dist/decode.js +18 -4
  21. package/serialization/dist/serialization.cjs +18 -4
  22. package/serialization/dist/serialization.js +18 -4
  23. package/server-functions/dist/client.cjs +27 -16
  24. package/server-functions/dist/client.js +27 -16
  25. package/server-functions/dist/server.cjs +529 -131
  26. package/server-functions/dist/server.dev.cjs +536 -130
  27. package/server-functions/dist/server.dev.js +536 -130
  28. package/server-functions/dist/server.js +529 -131
  29. package/types/client.d.ts +1 -3
  30. package/types/constants.d.ts +3 -1
  31. package/types/frames/frame-client.d.ts +1 -1
  32. package/types/head.d.ts +3 -0
  33. package/types/index.d.ts +18 -7
  34. package/types/index.server.d.ts +31 -9
  35. package/types/render.d.ts +3 -1
  36. package/types/server-functions/flash.d.ts +12 -3
  37. package/types/server-functions/server.d.ts +100 -5
  38. package/types/server-mock.d.ts +43 -7
  39. package/types/server.d.ts +47 -5
  40. package/types-cjs/client.d.cts +1 -3
  41. package/types-cjs/constants.d.cts +3 -1
  42. package/types-cjs/frames/frame-client.d.cts +1 -1
  43. package/types-cjs/head.d.cts +3 -0
  44. package/types-cjs/index.d.cts +18 -7
  45. package/types-cjs/index.server.d.cts +31 -9
  46. package/types-cjs/render.d.cts +3 -1
  47. package/types-cjs/server-functions/flash.d.cts +12 -3
  48. package/types-cjs/server-functions/server.d.cts +100 -5
  49. package/types-cjs/server-mock.d.cts +43 -7
  50. package/types-cjs/server.d.cts +47 -5
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/patch-driver.d.cts +0 -3
@@ -2,6 +2,16 @@
2
2
 
3
3
  var solidJs = require('solid-js');
4
4
 
5
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
6
+ function isHttpNavigationTarget(target) {
7
+ try {
8
+ const protocol = new URL(target, "http://base.invalid").protocol;
9
+ return protocol === "http:" || protocol === "https:";
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
5
15
  const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
6
16
  function isResponseEnvelope(value) {
7
17
  return !!(value && typeof value === "object" && value[ENVELOPE]);
@@ -239,7 +249,7 @@ function isJSONSafe(value) {
239
249
  const t = typeof v;
240
250
  if (t === "string" || t === "boolean") continue;
241
251
  if (t === "number") {
242
- if (!Number.isFinite(v)) return false;
252
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
243
253
  continue;
244
254
  }
245
255
  if (t !== "object") return false;
@@ -325,31 +335,30 @@ function getHeadersAndBody(body) {
325
335
  async function extractBody(source, codecOptions) {
326
336
  const contentType = source.headers.get("content-type");
327
337
  const format = source.headers.get(BODY_FORMAT_HEADER);
328
- const clone = source.clone();
329
338
  switch (true) {
330
339
  case format === BodyFormat.Serialized:
331
- return await deserializeStream(clone, codecOptions);
340
+ return await deserializeStream(source, codecOptions);
332
341
  case format === BodyFormat.Json:
333
- return JSON.parse(await clone.text());
342
+ return JSON.parse(await source.text());
334
343
  case format === BodyFormat.String:
335
- return await clone.text();
344
+ return await source.text();
336
345
  case format === BodyFormat.File:
337
346
  {
338
- const formData = await clone.formData();
347
+ const formData = await source.formData();
339
348
  return formData.get(FILE_FORM_KEY);
340
349
  }
341
350
  case format === BodyFormat.FormData:
342
351
  case contentType && contentType.startsWith("multipart/form-data"):
343
- return await clone.formData();
352
+ return await source.formData();
344
353
  case format === BodyFormat.URLSearchParams:
345
354
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
346
- return new URLSearchParams(await clone.text());
355
+ return new URLSearchParams(await source.text());
347
356
  case format === BodyFormat.Blob:
348
- return await clone.blob();
357
+ return await source.blob();
349
358
  case format === BodyFormat.ArrayBuffer:
350
- return await clone.arrayBuffer();
359
+ return await source.arrayBuffer();
351
360
  case format === BodyFormat.Uint8Array:
352
- return new Uint8Array(await clone.arrayBuffer());
361
+ return new Uint8Array(await source.arrayBuffer());
353
362
  }
354
363
  return undefined;
355
364
  }
@@ -485,7 +494,7 @@ async function deserializeString(text, codecOptions) {
485
494
  }
486
495
  async function decodeResponse(response, codecOptions) {
487
496
  if (!response.body) return undefined;
488
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
497
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
489
498
  }
490
499
  async function decodeResponsePayload(response, codecOptions) {
491
500
  const decoded = await decodeResponse(response, codecOptions);
@@ -536,7 +545,8 @@ function copyInitHeaders(init) {
536
545
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
537
546
  return headers;
538
547
  }
539
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location"].map(header => header.toLowerCase()));
548
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
549
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
540
550
  function fillsStubGap(key, headers, response) {
541
551
  if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
542
552
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
@@ -564,6 +574,62 @@ function commitEventResponse(response, event = getRequestEvent()) {
564
574
  });
565
575
  }
566
576
 
577
+ let configuredSecret;
578
+ function setFlashSecret(secret) {
579
+ configuredSecret = secret;
580
+ }
581
+ function resolveSecret() {
582
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
583
+ }
584
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
585
+ let cachedSecret;
586
+ let cachedKey;
587
+ function resolveFlashKey() {
588
+ const secret = resolveSecret();
589
+ if (typeof secret !== "string" || secret.length === 0) return null;
590
+ if (secret !== cachedSecret) {
591
+ cachedSecret = secret;
592
+ cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
593
+ name: "AES-GCM"
594
+ }, false, ["encrypt", "decrypt"]));
595
+ }
596
+ return cachedKey;
597
+ }
598
+ const FLASH_FORMAT_VERSION = "1.";
599
+ const IV_BYTES = 12;
600
+ const GCM_TAG_BYTES = 16;
601
+ function toBase64url(bytes) {
602
+ let binary = "";
603
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
604
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
605
+ }
606
+ function fromBase64url(text) {
607
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
608
+ const bytes = new Uint8Array(binary.length);
609
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
610
+ return bytes;
611
+ }
612
+ async function encryptFlashValue(key, json) {
613
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
614
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
615
+ name: "AES-GCM",
616
+ iv
617
+ }, key, new TextEncoder().encode(json)));
618
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
619
+ packed.set(iv);
620
+ packed.set(ciphertext, IV_BYTES);
621
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
622
+ }
623
+ async function decryptFlashValue(key, value) {
624
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
625
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
626
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
627
+ const plain = await crypto.subtle.decrypt({
628
+ name: "AES-GCM",
629
+ iv: packed.subarray(0, IV_BYTES)
630
+ }, key, packed.subarray(IV_BYTES));
631
+ return new TextDecoder().decode(plain);
632
+ }
567
633
  function encodeInputValue(value) {
568
634
  if (value instanceof FormData) return {
569
635
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -584,7 +650,11 @@ function decodeInputValue(value) {
584
650
  }
585
651
  return value;
586
652
  }
587
- function encodeFlashCookie(url, result, input, thrown) {
653
+ async function encodeFlashCookie(url, result, input, thrown) {
654
+ const key = resolveFlashKey();
655
+ if (!key) {
656
+ return null;
657
+ }
588
658
  const isError = result instanceof Error;
589
659
  const payload = {
590
660
  url,
@@ -593,7 +663,7 @@ function encodeFlashCookie(url, result, input, thrown) {
593
663
  thrown: !!thrown,
594
664
  input: input.map(encodeInputValue)
595
665
  };
596
- if (fitsCookie(payload)) return flashCookie(payload);
666
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
597
667
  payload.truncated = true;
598
668
  payload.input = [];
599
669
  if (!fitsCookie(payload)) {
@@ -610,24 +680,35 @@ function encodeFlashCookie(url, result, input, thrown) {
610
680
  payload.result = true;
611
681
  }
612
682
  }
613
- return flashCookie(payload);
683
+ if (!fitsCookie(payload)) return null;
684
+ return flashCookie(payload, await key);
614
685
  }
615
- function flashCookie(payload) {
616
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
686
+ const FLASH_MAX_AGE_SECONDS = 60;
687
+ async function flashCookie(payload, key) {
688
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
617
689
  secure: true,
618
- httpOnly: true
690
+ httpOnly: true,
691
+ sameSite: "lax",
692
+ maxAge: FLASH_MAX_AGE_SECONDS
619
693
  });
620
694
  }
621
695
  const COOKIE_PAIR_BUDGET = 4000;
622
696
  function fitsCookie(payload) {
623
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
697
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
698
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
699
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
700
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
624
701
  }
625
- function decodeFlashCookie(cookieHeader) {
702
+ async function decodeFlashCookie(cookieHeader) {
626
703
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
627
704
  if (!match) return;
628
705
  try {
629
- const payload = JSON.parse(match);
630
- if (!payload || !payload.result) return;
706
+ const key = resolveFlashKey();
707
+ if (!key) return;
708
+ const json = await decryptFlashValue(await key, match);
709
+ if (json === undefined) return;
710
+ const payload = JSON.parse(json);
711
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
631
712
  const result = payload.error ? new Error(payload.result) : payload.result;
632
713
  const submission = {
633
714
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -638,7 +719,6 @@ function decodeFlashCookie(cookieHeader) {
638
719
  if (payload.truncated) submission.truncated = true;
639
720
  return submission;
640
721
  } catch (error) {
641
- console.error(error);
642
722
  }
643
723
  }
644
724
 
@@ -667,7 +747,8 @@ function configureServerFunctionsServer({
667
747
  csrf,
668
748
  codec,
669
749
  bodySizeLimit,
670
- maxArguments
750
+ maxArguments,
751
+ secret
671
752
  } = {}) {
672
753
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
673
754
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -681,6 +762,7 @@ function configureServerFunctionsServer({
681
762
  if (codec !== undefined) configureServerFunctionsCodec(codec);
682
763
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
683
764
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
765
+ if (secret !== undefined) setFlashSecret(secret);
684
766
  }
685
767
  const flightSources = new Map();
686
768
  function registerFlightDataSource(source, hook) {
@@ -690,14 +772,198 @@ function registerFlightDataSource(source, hook) {
690
772
  if (flightSources.get(source) === hook) flightSources.delete(source);
691
773
  };
692
774
  }
775
+ function resolveWrapInvocation(hook) {
776
+ if (hook === undefined || typeof hook === "function") return hook;
777
+ 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.`);
778
+ }
693
779
  function provideEvent(event, fn) {
694
780
  if (config.provideEvent) return config.provideEvent(event, fn);
695
781
  const ctx = globalThis[RequestContext];
696
782
  if (ctx) return ctx.run(event, fn);
697
783
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
698
784
  }
785
+ 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.";
786
+ 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.";
787
+ function provideEventOnce(provide, event, run) {
788
+ let invocations = 0;
789
+ const settle = () => {
790
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
791
+ };
792
+ const result = provide(event, () => {
793
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
794
+ return run();
795
+ });
796
+ const promised = nativePromise(result);
797
+ if (promised) {
798
+ return promised.then(value => {
799
+ settle();
800
+ return value;
801
+ });
802
+ }
803
+ settle();
804
+ return result;
805
+ }
806
+ function scopeDeferredResult(value, scope) {
807
+ const bound = bindDeferredBody(value, scope);
808
+ if (bound !== value || value === null || typeof value !== "object") return bound;
809
+ return scopeDeferredContents(value, scope);
810
+ }
811
+ class ScopeFrame {
812
+ constructor(value, next, keys, descriptors) {
813
+ this.value = value;
814
+ this.next = next;
815
+ this.keys = keys;
816
+ this.descriptors = descriptors;
817
+ this.i = 0;
818
+ this.changed = false;
819
+ }
820
+ }
821
+ function enterScopeCarrier(value, state) {
822
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
823
+ if (state.seen.has(value)) {
824
+ state.cyclic.add(value);
825
+ return state.seen.get(value);
826
+ }
827
+ const bound = bindDeferredBody(value, state.scope);
828
+ if (bound !== value) {
829
+ state.seen.set(value, bound);
830
+ return bound;
831
+ }
832
+ if (typeof value !== "object") return value;
833
+ if (Array.isArray(value)) {
834
+ if (Object.isFrozen(value)) {
835
+ state.seen.set(value, value);
836
+ return value;
837
+ }
838
+ const next = value.slice();
839
+ state.seen.set(value, next);
840
+ return new ScopeFrame(value, next, null, null);
841
+ }
842
+ const prototype = Object.getPrototypeOf(value);
843
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
844
+ state.seen.set(value, value);
845
+ return value;
846
+ }
847
+ const descriptors = Object.getOwnPropertyDescriptors(value);
848
+ const next = Object.create(prototype, descriptors);
849
+ state.seen.set(value, next);
850
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
851
+ }
852
+ function scopeDeferredContents(root, scope) {
853
+ const state = {
854
+ seen: new Map(),
855
+ cyclic: new Set(),
856
+ scope
857
+ };
858
+ const entered = enterScopeCarrier(root, state);
859
+ if (!(entered instanceof ScopeFrame)) return entered;
860
+ const stack = [entered];
861
+ let delivered = NOTHING;
862
+ for (;;) {
863
+ const top = stack[stack.length - 1];
864
+ const length = top.keys ? top.keys.length : top.value.length;
865
+ let pushed = null;
866
+ while (top.i < length) {
867
+ const i = top.i;
868
+ let original;
869
+ let writable = true;
870
+ if (top.keys) {
871
+ const descriptor = top.descriptors[top.keys[i]];
872
+ writable = "value" in descriptor && descriptor.writable === true;
873
+ original = writable ? descriptor.value : undefined;
874
+ } else {
875
+ original = top.value[i];
876
+ }
877
+ if (!writable) {
878
+ top.i++;
879
+ continue;
880
+ }
881
+ let bound;
882
+ if (delivered !== NOTHING) {
883
+ bound = delivered;
884
+ delivered = NOTHING;
885
+ } else {
886
+ bound = enterScopeCarrier(original, state);
887
+ if (bound instanceof ScopeFrame) {
888
+ pushed = bound;
889
+ break;
890
+ }
891
+ }
892
+ if (bound !== original) {
893
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
894
+ top.changed = true;
895
+ }
896
+ top.i++;
897
+ }
898
+ if (pushed !== null) {
899
+ stack.push(pushed);
900
+ continue;
901
+ }
902
+ stack.pop();
903
+ let out;
904
+ if (top.changed || state.cyclic.has(top.value)) {
905
+ out = top.next;
906
+ } else {
907
+ state.seen.set(top.value, top.value);
908
+ out = top.value;
909
+ }
910
+ if (stack.length === 0) return out;
911
+ delivered = out;
912
+ }
913
+ }
914
+ function bindDeferredBody(value, scope) {
915
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
916
+ const promised = scope(() => nativePromise(value));
917
+ if (promised) {
918
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
919
+ }
920
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
921
+ let reader;
922
+ return new ReadableStream({
923
+ async pull(controller) {
924
+ try {
925
+ const step = await scope(() => {
926
+ if (!reader) reader = value.getReader();
927
+ return reader.read();
928
+ });
929
+ if (step.done) controller.close();else controller.enqueue(step.value);
930
+ } catch (error) {
931
+ controller.error(error);
932
+ }
933
+ },
934
+ cancel(reason) {
935
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
936
+ }
937
+ }, {
938
+ highWaterMark: 0
939
+ });
940
+ }
941
+ const scopedIterator = symbol => ({
942
+ [symbol]() {
943
+ const iterator = scope(() => value[symbol]());
944
+ return new Proxy(iterator, {
945
+ get(target, property) {
946
+ const member = Reflect.get(target, property, target);
947
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
948
+ }
949
+ });
950
+ }
951
+ });
952
+ if (typeof value[Symbol.asyncIterator] === "function") {
953
+ return scopedIterator(Symbol.asyncIterator);
954
+ }
955
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
956
+ return scopedIterator(Symbol.iterator);
957
+ }
958
+ return value;
959
+ }
699
960
  const REGISTRATIONS = new Map();
700
961
  const METHODS = new Map();
962
+ const REFERENCE_BINDINGS = new WeakMap();
963
+ function declaresRead(id) {
964
+ const granted = METHODS.get(id);
965
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
966
+ }
701
967
  const INVOCATIONS = new WeakMap();
702
968
  let rpcProvided = false;
703
969
  function provideRPC() {
@@ -793,40 +1059,72 @@ function createServerReference({
793
1059
  id
794
1060
  });
795
1061
  evt.serverOnly = true;
796
- const result = provideEvent(evt, () => {
1062
+ const scope = run => provideEvent(evt, run);
1063
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1064
+ let result = provideEventOnce(provideEvent, evt, () => {
797
1065
  const run = () => fn.apply(thisArg, args);
798
- return config.wrapInvocation ? config.wrapInvocation(run, {
1066
+ return wrap ? wrap(run, {
799
1067
  id,
800
1068
  args,
801
1069
  event: evt,
802
1070
  direct: true
803
1071
  }) : run();
804
1072
  });
1073
+ result = scopeDeferredResult(result, scope);
805
1074
  const transform = config.transformDirectResult;
806
1075
  if (transform && result && typeof result.then === "function") {
807
- return result.then(value => transform(value, {
1076
+ return result.then(value => scopeDeferredResult(transform(value, {
808
1077
  id,
809
1078
  args,
810
1079
  event: evt
811
- }));
1080
+ }), scope));
812
1081
  }
813
- return transform ? transform(result, {
1082
+ return transform ? scopeDeferredResult(transform(result, {
814
1083
  id,
815
1084
  args,
816
1085
  event: evt
817
- }) : result;
1086
+ }), scope) : result;
818
1087
  }
819
1088
  });
1089
+ REFERENCE_BINDINGS.set(proxy, fn);
820
1090
  return proxy;
821
1091
  }
822
1092
  function GET(fn) {
823
1093
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
824
1094
  throw new Error("GET expects a server function reference");
825
1095
  }
826
- METHODS.set(fn.id, "GET");
827
- return withMeta(fn, {
1096
+ const id = fn.id;
1097
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1098
+ const existing = METHODS.get(id);
1099
+ if (existing !== undefined && existing !== binding) {
1100
+ if (DEV) {
1101
+ 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.`);
1102
+ }
1103
+ METHODS.delete(id);
1104
+ return fn;
1105
+ }
1106
+ METHODS.set(id, binding);
1107
+ const reference = withMeta(fn, {
828
1108
  method: "GET"
829
1109
  });
1110
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1111
+ return reference;
1112
+ }
1113
+ function guardDeclaredMethod(metadata, id) {
1114
+ let declared = metadata.method;
1115
+ Object.defineProperty(metadata, "method", {
1116
+ configurable: true,
1117
+ enumerable: true,
1118
+ get: () => declared,
1119
+ set(next) {
1120
+ if (next === declared) return;
1121
+ if (DEV) {
1122
+ 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.`);
1123
+ }
1124
+ METHODS.delete(id);
1125
+ declared = next;
1126
+ }
1127
+ });
830
1128
  }
831
1129
  function live(fn) {
832
1130
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -880,22 +1178,58 @@ function assertDecodeDepth(value) {
880
1178
  level = next;
881
1179
  }
882
1180
  }
1181
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1182
+ function stripUnsafeArgumentKeys(value) {
1183
+ const stack = [value];
1184
+ const seen = new Set();
1185
+ while (stack.length) {
1186
+ const v = stack.pop();
1187
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1188
+ seen.add(v);
1189
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1190
+ delete v[key];
1191
+ }
1192
+ for (const key of Object.keys(v)) stack.push(v[key]);
1193
+ if (v instanceof Map) {
1194
+ for (const [k, entry] of v) stack.push(k, entry);
1195
+ } else if (v instanceof Set) {
1196
+ for (const member of v) stack.push(member);
1197
+ }
1198
+ }
1199
+ return value;
1200
+ }
883
1201
  async function bufferBodyWithin(request, limit) {
884
- const reader = request.clone().body.getReader();
1202
+ const reader = request.body.getReader();
1203
+ const signal = request.signal;
885
1204
  const chunks = [];
886
1205
  let total = 0;
887
- for (;;) {
888
- const {
889
- done,
890
- value
891
- } = await reader.read();
892
- if (done) break;
893
- total += value.byteLength;
894
- if (total > limit) {
895
- reader.cancel().catch(() => {});
896
- return null;
1206
+ const onAbort = () => {
1207
+ reader.cancel(signal.reason).catch(() => {});
1208
+ };
1209
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1210
+ once: true
1211
+ });
1212
+ try {
1213
+ for (;;) {
1214
+ const {
1215
+ done,
1216
+ value
1217
+ } = await reader.read();
1218
+ if (signal.aborted) throw signal.reason;
1219
+ if (done) break;
1220
+ total += value.byteLength;
1221
+ if (total > limit) {
1222
+ reader.cancel().catch(() => {});
1223
+ return null;
1224
+ }
1225
+ chunks.push(value);
897
1226
  }
898
- chunks.push(value);
1227
+ } catch (error) {
1228
+ reader.cancel(error).catch(() => {});
1229
+ throw error;
1230
+ } finally {
1231
+ signal.removeEventListener("abort", onAbort);
1232
+ reader.releaseLock();
899
1233
  }
900
1234
  const body = new Uint8Array(total);
901
1235
  let offset = 0;
@@ -907,6 +1241,13 @@ async function bufferBodyWithin(request, limit) {
907
1241
  body
908
1242
  });
909
1243
  }
1244
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1245
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1246
+ function unknownFormatError(tag) {
1247
+ 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.");
1248
+ error[FORMAT_SKEW] = true;
1249
+ return error;
1250
+ }
910
1251
  async function parseArguments(request, url, scripted, codec) {
911
1252
  const parsed = [];
912
1253
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -922,6 +1263,7 @@ async function parseArguments(request, url, scripted, codec) {
922
1263
  if (!Array.isArray(result)) {
923
1264
  throw new TypeError("Server function arguments must encode an array");
924
1265
  }
1266
+ stripUnsafeArgumentKeys(result);
925
1267
  for (const arg of result) {
926
1268
  parsed.push(arg);
927
1269
  }
@@ -929,15 +1271,22 @@ async function parseArguments(request, url, scripted, codec) {
929
1271
  parsed.push(url.searchParams);
930
1272
  }
931
1273
  if (request.method === "POST" && request.body !== null) {
932
- const decoded = await extractBody(request.clone(), codec);
1274
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1275
+ throw unknownFormatError(bodyFormat);
1276
+ }
1277
+ const body = request.clone();
1278
+ const decoded = await extractBody(body, codec);
933
1279
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
934
1280
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
935
1281
  if (!Array.isArray(decoded)) {
936
1282
  throw new TypeError("Server function arguments must encode an array");
937
1283
  }
938
- return decoded;
1284
+ return stripUnsafeArgumentKeys(decoded);
939
1285
  }
940
1286
  if (decoded === undefined) {
1287
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1288
+ return parsed;
1289
+ }
941
1290
  throw new TypeError("Server function body carries no usable encoding");
942
1291
  }
943
1292
  parsed.push(decoded);
@@ -965,13 +1314,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
965
1314
  data
966
1315
  }, context);
967
1316
  if (transformed !== undefined) {
968
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1317
+ const owned = ownResponse(transformed);
1318
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
969
1319
  headers.forEach((value, key) => {
970
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
971
- transformed.headers.set(key, value);
1320
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1321
+ owned.headers.set(key, value);
972
1322
  }
973
1323
  });
974
- return transformed;
1324
+ return owned;
975
1325
  }
976
1326
  }
977
1327
  return outcome.value === undefined ? {
@@ -1038,7 +1388,7 @@ function foldSetCookies(headers, setCookies) {
1038
1388
  }
1039
1389
  function mergeResponseHeaders(target, source) {
1040
1390
  source.forEach((value, key) => {
1041
- if (key !== "set-cookie") target.append(key, value);
1391
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1042
1392
  });
1043
1393
  if (source.getSetCookie) {
1044
1394
  for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
@@ -1055,10 +1405,6 @@ function maskRedirect(headers, response, requestUrl) {
1055
1405
  headers.delete("Location");
1056
1406
  }
1057
1407
  const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1058
- function refusedTargetScheme(target) {
1059
- const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.exec(target);
1060
- return match !== null && !/^https?:$/i.test(match[0]);
1061
- }
1062
1408
  function enforceComposedHeaderInvariants(response) {
1063
1409
  for (const name of BOUNDED_COMPOSED_HEADERS) {
1064
1410
  const value = response.headers.get(name);
@@ -1068,7 +1414,7 @@ function enforceComposedHeaderInvariants(response) {
1068
1414
  }
1069
1415
  if (name === REVALIDATE_HEADER) continue;
1070
1416
  const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1071
- if (refusedTargetScheme(target)) {
1417
+ if (!isHttpNavigationTarget(target)) {
1072
1418
  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);
1073
1419
  }
1074
1420
  }
@@ -1096,7 +1442,7 @@ function warnScripted304(functionId) {
1096
1442
  function createNoJSHandler({
1097
1443
  base = ""
1098
1444
  } = {}) {
1099
- return function handleNoJS(result, request, args, thrown) {
1445
+ return async function handleNoJS(result, request, args, thrown) {
1100
1446
  const url = new URL(request.url);
1101
1447
  let back = new URL(base || "/", url.origin).toString();
1102
1448
  try {
@@ -1121,8 +1467,9 @@ function createNoJSHandler({
1121
1467
  Location: back
1122
1468
  });
1123
1469
  }
1124
- if (result && !(result instanceof Response)) {
1125
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1470
+ if (result !== undefined && !(result instanceof Response)) {
1471
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1472
+ if (flash !== null) headers.append("Set-Cookie", flash);
1126
1473
  }
1127
1474
  return new Response(null, {
1128
1475
  status,
@@ -1196,14 +1543,11 @@ function guardFailures(value, state) {
1196
1543
  top.next.add(guarded);
1197
1544
  if (guarded !== original) top.changed = true;
1198
1545
  } else if (guarded !== original || top.accessorRead === i) {
1199
- Object.defineProperty(top.next, items[i], top.accessorRead === i ? {
1200
- enumerable: true,
1201
- configurable: true,
1546
+ Object.defineProperty(top.next, items[i], {
1547
+ value: guarded,
1202
1548
  writable: true,
1203
- value: guarded
1204
- } : {
1205
- ...top.descriptors[items[i]],
1206
- value: guarded
1549
+ configurable: true,
1550
+ enumerable: top.descriptors[items[i]].enumerable
1207
1551
  });
1208
1552
  top.changed = true;
1209
1553
  }
@@ -1238,6 +1582,9 @@ class Frame {
1238
1582
  this.pendingKey = undefined;
1239
1583
  }
1240
1584
  }
1585
+ function guardOperation(state, run) {
1586
+ return state.scope ? state.scope(run) : run();
1587
+ }
1241
1588
  function enterGuard(value, state) {
1242
1589
  if (value === null || typeof value !== "object") return value;
1243
1590
  if (state.seen.has(value)) {
@@ -1252,7 +1599,7 @@ function enterGuard(value, state) {
1252
1599
  if (finished) return;
1253
1600
  finished = true;
1254
1601
  try {
1255
- const cancelled = reader ? reader.cancel() : value.cancel();
1602
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1256
1603
  if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1257
1604
  } catch {}
1258
1605
  };
@@ -1264,19 +1611,19 @@ function enterGuard(value, state) {
1264
1611
  controller.close();
1265
1612
  return;
1266
1613
  }
1267
- if (!reader) reader = value.getReader();
1614
+ if (!reader) reader = guardOperation(state, () => value.getReader());
1268
1615
  const {
1269
1616
  done,
1270
1617
  value: chunk
1271
- } = await reader.read();
1272
- done ? controller.close() : controller.enqueue(guardFailures(chunk, state));
1618
+ } = await guardOperation(state, () => reader.read());
1619
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1273
1620
  } catch (error) {
1274
- controller.error(sanitizeServerError(error));
1621
+ controller.error(guardOperation(state, () => sanitizeServerError(error)));
1275
1622
  }
1276
1623
  },
1277
1624
  cancel(reason) {
1278
1625
  finished = true;
1279
- return reader ? reader.cancel(reason) : value.cancel(reason);
1626
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1280
1627
  }
1281
1628
  });
1282
1629
  if (gate) gate.onOpen(close);
@@ -1284,9 +1631,10 @@ function enterGuard(value, state) {
1284
1631
  return guardedStream;
1285
1632
  }
1286
1633
  if (typeof value.then === "function") {
1287
- const guardedPromise = Promise.resolve(value).then(resolved => guardFailures(resolved, state), error => {
1288
- throw sanitizeServerError(error);
1634
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1635
+ throw guardOperation(state, () => sanitizeServerError(error));
1289
1636
  });
1637
+ guardedPromise.catch(() => {});
1290
1638
  state.seen.set(value, guardedPromise);
1291
1639
  return guardedPromise;
1292
1640
  }
@@ -1295,13 +1643,13 @@ function enterGuard(value, state) {
1295
1643
  const gate = state.gate;
1296
1644
  const guardedIterable = {
1297
1645
  [Symbol.asyncIterator]() {
1298
- const iterator = source[Symbol.asyncIterator]();
1646
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1299
1647
  let finished = false;
1300
1648
  const close = () => {
1301
1649
  if (finished) return;
1302
1650
  finished = true;
1303
1651
  try {
1304
- const returned = iterator.return && iterator.return();
1652
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
1305
1653
  if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1306
1654
  } catch {}
1307
1655
  };
@@ -1309,17 +1657,17 @@ function enterGuard(value, state) {
1309
1657
  const step = () => finished ? Promise.resolve({
1310
1658
  done: true,
1311
1659
  value: undefined
1312
- }) : iterator.next().then(step => {
1660
+ }) : guardOperation(state, () => iterator.next()).then(step => {
1313
1661
  if (step.done) {
1314
1662
  finished = true;
1315
1663
  return step;
1316
1664
  }
1317
1665
  return {
1318
1666
  done: false,
1319
- value: guardFailures(step.value, state)
1667
+ value: guardOperation(state, () => guardFailures(step.value, state))
1320
1668
  };
1321
1669
  }, error => {
1322
- throw sanitizeServerError(error);
1670
+ throw guardOperation(state, () => sanitizeServerError(error));
1323
1671
  });
1324
1672
  return {
1325
1673
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1336,6 +1684,11 @@ function enterGuard(value, state) {
1336
1684
  state.seen.set(value, guardedIterable);
1337
1685
  return guardedIterable;
1338
1686
  }
1687
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1688
+ const scopedIterable = scopeDeferredResult(value, state.scope);
1689
+ state.seen.set(value, scopedIterable);
1690
+ return scopedIterable;
1691
+ }
1339
1692
  if (Array.isArray(value)) {
1340
1693
  const next = value.slice();
1341
1694
  state.seen.set(value, next);
@@ -1354,21 +1707,29 @@ function enterGuard(value, state) {
1354
1707
  return new Frame(SET, value, next, [...value], null);
1355
1708
  }
1356
1709
  const prototype = Object.getPrototypeOf(value);
1357
- if (prototype !== Object.prototype && prototype !== null) {
1710
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1358
1711
  state.seen.set(value, value);
1359
1712
  return value;
1360
1713
  }
1361
1714
  const descriptors = Object.getOwnPropertyDescriptors(value);
1715
+ for (const key of Object.keys(descriptors)) {
1716
+ descriptors[key].configurable = true;
1717
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
1718
+ }
1362
1719
  const next = Object.create(prototype, descriptors);
1363
1720
  state.seen.set(value, next);
1364
- return new Frame(OBJECT, value, next, Object.keys(descriptors), descriptors);
1721
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1722
+ const descriptor = descriptors[key];
1723
+ return descriptor.enumerable || "value" in descriptor;
1724
+ });
1725
+ return new Frame(OBJECT, value, next, children, descriptors);
1365
1726
  }
1366
1727
  function keepGuarded(value, next, changed, state) {
1367
1728
  if (changed || state.cyclic.has(value)) return next;
1368
1729
  state.seen.set(value, value);
1369
1730
  return value;
1370
1731
  }
1371
- function serializeResponseStream(value, codecOptions, signal) {
1732
+ function serializeResponseStream(value, codecOptions, signal, scope) {
1372
1733
  let closed = false;
1373
1734
  let streamController = null;
1374
1735
  let demandWaiters = null;
@@ -1387,11 +1748,13 @@ function serializeResponseStream(value, codecOptions, signal) {
1387
1748
  if (closed) close();else sourceClosers.add(close);
1388
1749
  }
1389
1750
  };
1390
- value = guardFailures(value, {
1751
+ const guardState = {
1391
1752
  seen: new WeakMap(),
1392
1753
  cyclic: new WeakSet(),
1393
- gate
1394
- });
1754
+ gate,
1755
+ scope
1756
+ };
1757
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
1395
1758
  let cancelSerialize = null;
1396
1759
  let onAbort = null;
1397
1760
  const finishSource = () => {
@@ -1472,14 +1835,14 @@ function serializeResponseStream(value, codecOptions, signal) {
1472
1835
  }
1473
1836
  });
1474
1837
  }
1475
- function serializedResponse(value, headers, codec, signal) {
1838
+ function serializedResponse(value, headers, codec, signal, scope) {
1476
1839
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
1477
1840
  headers.set("Content-Type", "text/plain");
1478
- return new Response(serializeResponseStream(value, codec, signal), {
1841
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
1479
1842
  headers
1480
1843
  });
1481
1844
  }
1482
- function encodeResult(value, headers, status, codec, signal) {
1845
+ function encodeResult(value, headers, status, codec, signal, scope) {
1483
1846
  if (NULL_BODY_STATUSES.has(status)) {
1484
1847
  if (value === undefined || value === null) {
1485
1848
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
@@ -1490,7 +1853,7 @@ function encodeResult(value, headers, status, codec, signal) {
1490
1853
  }
1491
1854
  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.`);
1492
1855
  headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
1493
- return encodeResult(error, headers, 500, codec, signal);
1856
+ return encodeResult(error, headers, 500, codec, signal, scope);
1494
1857
  }
1495
1858
  const direct = getHeadersAndBody(value);
1496
1859
  if (direct) {
@@ -1510,10 +1873,12 @@ function encodeResult(value, headers, status, codec, signal) {
1510
1873
  });
1511
1874
  }
1512
1875
  try {
1513
- if (isJSONSafe(value)) {
1876
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
1877
+ if (jsonSafe) {
1514
1878
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
1515
1879
  headers.set("Content-Type", "application/json");
1516
- return new Response(JSON.stringify(value), {
1880
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
1881
+ return new Response(body, {
1517
1882
  status,
1518
1883
  headers
1519
1884
  });
@@ -1521,7 +1886,7 @@ function encodeResult(value, headers, status, codec, signal) {
1521
1886
  } catch {
1522
1887
  }
1523
1888
  try {
1524
- const response = serializedResponse(value, headers, codec, signal);
1889
+ const response = serializedResponse(value, headers, codec, signal, scope);
1525
1890
  return status === 200 ? response : new Response(response.body, {
1526
1891
  status,
1527
1892
  headers
@@ -1619,13 +1984,22 @@ function forbiddenResponse() {
1619
1984
  }
1620
1985
  }));
1621
1986
  }
1987
+ function nativePromise(value) {
1988
+ if (value instanceof Promise) return value;
1989
+ try {
1990
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
1991
+ } catch {}
1992
+ }
1622
1993
  async function handleServerFunctionRequest(request, options = {}) {
1623
- const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
1994
+ const codec = {
1995
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
1996
+ };
1997
+ codec.serializeErrorStacks ??= DEV;
1624
1998
  const url = new URL(request.url);
1625
1999
  const method = request.method;
1626
2000
  const address = resolveAddress(url);
1627
2001
  const functionId = address && address.id;
1628
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2002
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1629
2003
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1630
2004
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1631
2005
  let serverFunction;
@@ -1656,7 +2030,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1656
2030
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1657
2031
  status: 405,
1658
2032
  headers: {
1659
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2033
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1660
2034
  }
1661
2035
  });
1662
2036
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1678,30 +2052,50 @@ async function handleServerFunctionRequest(request, options = {}) {
1678
2052
  });
1679
2053
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1680
2054
  }
1681
- if (!(declared > 0)) {
1682
- const bounded = await bufferBodyWithin(request, bodySizeLimit);
1683
- if (bounded === null) {
1684
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1685
- status: 413
1686
- });
1687
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1688
- }
1689
- request = bounded;
2055
+ let bounded;
2056
+ try {
2057
+ bounded = await bufferBodyWithin(request, bodySizeLimit);
2058
+ } catch {
2059
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2060
+ status: 400
2061
+ });
2062
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2063
+ }
2064
+ if (bounded === null) {
2065
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2066
+ status: 413
2067
+ });
2068
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1690
2069
  }
2070
+ request = bounded;
2071
+ }
2072
+ let event;
2073
+ try {
2074
+ event = options.createEvent ? options.createEvent(request) : {
2075
+ request,
2076
+ locals: {}
2077
+ };
2078
+ const promised = nativePromise(event);
2079
+ if (promised) event = await promised;
2080
+ } catch (error) {
2081
+ const safe = sanitizeServerError(error);
2082
+ const message = safe instanceof Error ? safe.message : String(safe);
2083
+ const headers = new Headers();
2084
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2085
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2086
+ status: 500
2087
+ });
2088
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1691
2089
  }
1692
- let event = options.createEvent ? options.createEvent(request) : {
1693
- request,
1694
- locals: {}
1695
- };
1696
- if (typeof event?.then === "function") event = await event;
1697
2090
  const refuseCommitted = raw => {
1698
2091
  const response = commitEventResponse(raw, event);
1699
2092
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1700
2093
  };
1701
2094
  const provide = options.provideEvent || provideEvent;
2095
+ const scope = run => provide(event, run);
1702
2096
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1703
2097
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1704
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2098
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1705
2099
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1706
2100
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1707
2101
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1716,7 +2110,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1716
2110
  }
1717
2111
  }
1718
2112
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1719
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2113
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1720
2114
  const hook = source === "true" ? flightHook : flightSources.get(source);
1721
2115
  return hook ? [[source, hook]] : [];
1722
2116
  }) : [];
@@ -1724,8 +2118,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1724
2118
  let parsed;
1725
2119
  try {
1726
2120
  parsed = await parseArguments(request, url, scripted, codec);
1727
- } catch {
1728
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2121
+ } catch (error) {
2122
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2123
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1729
2124
  status: 400
1730
2125
  });
1731
2126
  return refuseCommitted(response);
@@ -1749,7 +2144,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1749
2144
  const headers = new Headers();
1750
2145
  const dispatch = async () => {
1751
2146
  try {
1752
- let result = await provide(event, async () => {
2147
+ const invokeOnce = async () => {
1753
2148
  INVOCATIONS.set(event, {
1754
2149
  id: functionId
1755
2150
  });
@@ -1761,7 +2156,8 @@ async function handleServerFunctionRequest(request, options = {}) {
1761
2156
  request,
1762
2157
  direct: false
1763
2158
  }) : run();
1764
- });
2159
+ };
2160
+ let result = await provideEventOnce(provide, event, invokeOnce);
1765
2161
  if (transformResult) {
1766
2162
  result = await transformResult(event, result, flightContext);
1767
2163
  }
@@ -1813,12 +2209,14 @@ async function handleServerFunctionRequest(request, options = {}) {
1813
2209
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1814
2210
  }
1815
2211
  if (!scripted) {
1816
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2212
+ if (handleNoJS) {
2213
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2214
+ }
1817
2215
  if (result instanceof Response) return result;
1818
- return encodeResult(result, headers, status, codec, request.signal);
2216
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1819
2217
  }
1820
2218
  if (status === 304) warnScripted304(functionId);
1821
- return encodeResult(result, headers, status, codec, request.signal);
2219
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1822
2220
  } catch (x) {
1823
2221
  const respondThrown = value => {
1824
2222
  const safe = sanitizeServerError(value);
@@ -1831,19 +2229,19 @@ async function handleServerFunctionRequest(request, options = {}) {
1831
2229
  }
1832
2230
  const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1833
2231
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1834
- return encodeResult(safe, headers, 500, codec, request.signal);
2232
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
1835
2233
  };
1836
- if (x instanceof Response || isResponseEnvelope(x)) {
1837
- if (transformResult) {
1838
- try {
1839
- x = await transformResult(event, x, {
1840
- ...flightContext,
1841
- thrown: true
1842
- });
1843
- } catch (hookError) {
1844
- return respondThrown(hookError);
1845
- }
2234
+ if (transformResult) {
2235
+ try {
2236
+ x = await transformResult(event, x, {
2237
+ ...flightContext,
2238
+ thrown: true
2239
+ });
2240
+ } catch (hookError) {
2241
+ return respondThrown(hookError);
1846
2242
  }
2243
+ }
2244
+ if (x instanceof Response || isResponseEnvelope(x)) {
1847
2245
  let status = 200;
1848
2246
  let metadata;
1849
2247
  if (isResponseEnvelope(x)) {
@@ -1895,7 +2293,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1895
2293
  if (x instanceof Response) return x;
1896
2294
  }
1897
2295
  if (scripted && status === 304) warnScripted304(functionId);
1898
- return encodeResult(x, headers, status, codec, request.signal);
2296
+ return encodeResult(x, headers, status, codec, request.signal, scope);
1899
2297
  }
1900
2298
  return respondThrown(x);
1901
2299
  }