@solidjs/web 2.0.0-rc.6 → 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 (50) hide show
  1. package/dist/server.cjs +105 -35
  2. package/dist/server.dev.cjs +3794 -0
  3. package/dist/server.dev.js +3627 -0
  4. package/dist/server.js +106 -36
  5. package/dist/web.cjs +39 -385
  6. package/dist/{dev.cjs → web.dev.cjs} +91 -396
  7. package/dist/{dev.js → web.dev.js} +93 -393
  8. package/dist/web.js +41 -382
  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 +234 -32
  14. package/frames/dist/server.dev.cjs +4584 -0
  15. package/frames/dist/server.dev.js +4571 -0
  16. package/frames/dist/server.js +234 -32
  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 +13 -14
  24. package/server-functions/dist/client.js +13 -14
  25. package/server-functions/dist/server.cjs +331 -83
  26. package/server-functions/dist/server.dev.cjs +338 -82
  27. package/server-functions/dist/server.dev.js +338 -82
  28. package/server-functions/dist/server.js +331 -83
  29. package/types/client.d.ts +0 -3
  30. package/types/frames/frame-client.d.ts +1 -1
  31. package/types/head.d.ts +3 -0
  32. package/types/index.d.ts +18 -7
  33. package/types/index.server.d.ts +31 -9
  34. package/types/render.d.ts +3 -1
  35. package/types/server-functions/flash.d.ts +12 -3
  36. package/types/server-functions/server.d.ts +27 -3
  37. package/types/server-mock.d.ts +43 -7
  38. package/types/server.d.ts +47 -5
  39. package/types-cjs/client.d.cts +0 -3
  40. package/types-cjs/frames/frame-client.d.cts +1 -1
  41. package/types-cjs/head.d.cts +3 -0
  42. package/types-cjs/index.d.cts +18 -7
  43. package/types-cjs/index.server.d.cts +31 -9
  44. package/types-cjs/render.d.cts +3 -1
  45. package/types-cjs/server-functions/flash.d.cts +12 -3
  46. package/types-cjs/server-functions/server.d.cts +27 -3
  47. package/types-cjs/server-mock.d.cts +43 -7
  48. package/types-cjs/server.d.cts +47 -5
  49. package/types/patch-driver.d.ts +0 -3
  50. package/types-cjs/patch-driver.d.cts +0 -3
@@ -249,7 +249,7 @@ function isJSONSafe(value) {
249
249
  const t = typeof v;
250
250
  if (t === "string" || t === "boolean") continue;
251
251
  if (t === "number") {
252
- if (!Number.isFinite(v)) return false;
252
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
253
253
  continue;
254
254
  }
255
255
  if (t !== "object") return false;
@@ -335,31 +335,30 @@ function getHeadersAndBody(body) {
335
335
  async function extractBody(source, codecOptions) {
336
336
  const contentType = source.headers.get("content-type");
337
337
  const format = source.headers.get(BODY_FORMAT_HEADER);
338
- const clone = source.clone();
339
338
  switch (true) {
340
339
  case format === BodyFormat.Serialized:
341
- return await deserializeStream(clone, codecOptions);
340
+ return await deserializeStream(source, codecOptions);
342
341
  case format === BodyFormat.Json:
343
- return JSON.parse(await clone.text());
342
+ return JSON.parse(await source.text());
344
343
  case format === BodyFormat.String:
345
- return await clone.text();
344
+ return await source.text();
346
345
  case format === BodyFormat.File:
347
346
  {
348
- const formData = await clone.formData();
347
+ const formData = await source.formData();
349
348
  return formData.get(FILE_FORM_KEY);
350
349
  }
351
350
  case format === BodyFormat.FormData:
352
351
  case contentType && contentType.startsWith("multipart/form-data"):
353
- return await clone.formData();
352
+ return await source.formData();
354
353
  case format === BodyFormat.URLSearchParams:
355
354
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
356
- return new URLSearchParams(await clone.text());
355
+ return new URLSearchParams(await source.text());
357
356
  case format === BodyFormat.Blob:
358
- return await clone.blob();
357
+ return await source.blob();
359
358
  case format === BodyFormat.ArrayBuffer:
360
- return await clone.arrayBuffer();
359
+ return await source.arrayBuffer();
361
360
  case format === BodyFormat.Uint8Array:
362
- return new Uint8Array(await clone.arrayBuffer());
361
+ return new Uint8Array(await source.arrayBuffer());
363
362
  }
364
363
  return undefined;
365
364
  }
@@ -495,7 +494,7 @@ async function deserializeString(text, codecOptions) {
495
494
  }
496
495
  async function decodeResponse(response, codecOptions) {
497
496
  if (!response.body) return undefined;
498
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
497
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
499
498
  }
500
499
  async function decodeResponsePayload(response, codecOptions) {
501
500
  const decoded = await decodeResponse(response, codecOptions);
@@ -575,6 +574,62 @@ function commitEventResponse(response, event = getRequestEvent()) {
575
574
  });
576
575
  }
577
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
+ }
578
633
  function encodeInputValue(value) {
579
634
  if (value instanceof FormData) return {
580
635
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -595,7 +650,11 @@ function decodeInputValue(value) {
595
650
  }
596
651
  return value;
597
652
  }
598
- 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
+ }
599
658
  const isError = result instanceof Error;
600
659
  const payload = {
601
660
  url,
@@ -604,7 +663,7 @@ function encodeFlashCookie(url, result, input, thrown) {
604
663
  thrown: !!thrown,
605
664
  input: input.map(encodeInputValue)
606
665
  };
607
- if (fitsCookie(payload)) return flashCookie(payload);
666
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
608
667
  payload.truncated = true;
609
668
  payload.input = [];
610
669
  if (!fitsCookie(payload)) {
@@ -621,24 +680,35 @@ function encodeFlashCookie(url, result, input, thrown) {
621
680
  payload.result = true;
622
681
  }
623
682
  }
624
- return flashCookie(payload);
683
+ if (!fitsCookie(payload)) return null;
684
+ return flashCookie(payload, await key);
625
685
  }
626
- function flashCookie(payload) {
627
- 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)), {
628
689
  secure: true,
629
- httpOnly: true
690
+ httpOnly: true,
691
+ sameSite: "lax",
692
+ maxAge: FLASH_MAX_AGE_SECONDS
630
693
  });
631
694
  }
632
695
  const COOKIE_PAIR_BUDGET = 4000;
633
696
  function fitsCookie(payload) {
634
- 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;
635
701
  }
636
- function decodeFlashCookie(cookieHeader) {
702
+ async function decodeFlashCookie(cookieHeader) {
637
703
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
638
704
  if (!match) return;
639
705
  try {
640
- const payload = JSON.parse(match);
641
- 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;
642
712
  const result = payload.error ? new Error(payload.result) : payload.result;
643
713
  const submission = {
644
714
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -649,7 +719,6 @@ function decodeFlashCookie(cookieHeader) {
649
719
  if (payload.truncated) submission.truncated = true;
650
720
  return submission;
651
721
  } catch (error) {
652
- console.error(error);
653
722
  }
654
723
  }
655
724
 
@@ -678,7 +747,8 @@ function configureServerFunctionsServer({
678
747
  csrf,
679
748
  codec,
680
749
  bodySizeLimit,
681
- maxArguments
750
+ maxArguments,
751
+ secret
682
752
  } = {}) {
683
753
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
684
754
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -692,6 +762,7 @@ function configureServerFunctionsServer({
692
762
  if (codec !== undefined) configureServerFunctionsCodec(codec);
693
763
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
694
764
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
765
+ if (secret !== undefined) setFlashSecret(secret);
695
766
  }
696
767
  const flightSources = new Map();
697
768
  function registerFlightDataSource(source, hook) {
@@ -701,13 +772,146 @@ function registerFlightDataSource(source, hook) {
701
772
  if (flightSources.get(source) === hook) flightSources.delete(source);
702
773
  };
703
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
+ }
704
779
  function provideEvent(event, fn) {
705
780
  if (config.provideEvent) return config.provideEvent(event, fn);
706
781
  const ctx = globalThis[RequestContext];
707
782
  if (ctx) return ctx.run(event, fn);
708
783
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
709
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
+ }
710
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) {
711
915
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
712
916
  const promised = scope(() => nativePromise(value));
713
917
  if (promised) {
@@ -755,6 +959,11 @@ function scopeDeferredResult(value, scope) {
755
959
  }
756
960
  const REGISTRATIONS = new Map();
757
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
+ }
758
967
  const INVOCATIONS = new WeakMap();
759
968
  let rpcProvided = false;
760
969
  function provideRPC() {
@@ -851,9 +1060,10 @@ function createServerReference({
851
1060
  });
852
1061
  evt.serverOnly = true;
853
1062
  const scope = run => provideEvent(evt, run);
854
- let result = provideEvent(evt, () => {
1063
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1064
+ let result = provideEventOnce(provideEvent, evt, () => {
855
1065
  const run = () => fn.apply(thisArg, args);
856
- return config.wrapInvocation ? config.wrapInvocation(run, {
1066
+ return wrap ? wrap(run, {
857
1067
  id,
858
1068
  args,
859
1069
  event: evt,
@@ -876,16 +1086,45 @@ function createServerReference({
876
1086
  }), scope) : result;
877
1087
  }
878
1088
  });
1089
+ REFERENCE_BINDINGS.set(proxy, fn);
879
1090
  return proxy;
880
1091
  }
881
1092
  function GET(fn) {
882
1093
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
883
1094
  throw new Error("GET expects a server function reference");
884
1095
  }
885
- METHODS.set(fn.id, "GET");
886
- 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, {
887
1108
  method: "GET"
888
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
+ });
889
1128
  }
890
1129
  function live(fn) {
891
1130
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -1002,6 +1241,13 @@ async function bufferBodyWithin(request, limit) {
1002
1241
  body
1003
1242
  });
1004
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
+ }
1005
1251
  async function parseArguments(request, url, scripted, codec) {
1006
1252
  const parsed = [];
1007
1253
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1025,7 +1271,11 @@ async function parseArguments(request, url, scripted, codec) {
1025
1271
  parsed.push(url.searchParams);
1026
1272
  }
1027
1273
  if (request.method === "POST" && request.body !== null) {
1028
- 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);
1029
1279
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1030
1280
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1031
1281
  if (!Array.isArray(decoded)) {
@@ -1034,7 +1284,7 @@ async function parseArguments(request, url, scripted, codec) {
1034
1284
  return stripUnsafeArgumentKeys(decoded);
1035
1285
  }
1036
1286
  if (decoded === undefined) {
1037
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1287
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1038
1288
  return parsed;
1039
1289
  }
1040
1290
  throw new TypeError("Server function body carries no usable encoding");
@@ -1064,13 +1314,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1064
1314
  data
1065
1315
  }, context);
1066
1316
  if (transformed !== undefined) {
1067
- 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);
1068
1319
  headers.forEach((value, key) => {
1069
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1070
- transformed.headers.set(key, value);
1320
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1321
+ owned.headers.set(key, value);
1071
1322
  }
1072
1323
  });
1073
- return transformed;
1324
+ return owned;
1074
1325
  }
1075
1326
  }
1076
1327
  return outcome.value === undefined ? {
@@ -1191,7 +1442,7 @@ function warnScripted304(functionId) {
1191
1442
  function createNoJSHandler({
1192
1443
  base = ""
1193
1444
  } = {}) {
1194
- return function handleNoJS(result, request, args, thrown) {
1445
+ return async function handleNoJS(result, request, args, thrown) {
1195
1446
  const url = new URL(request.url);
1196
1447
  let back = new URL(base || "/", url.origin).toString();
1197
1448
  try {
@@ -1216,8 +1467,9 @@ function createNoJSHandler({
1216
1467
  Location: back
1217
1468
  });
1218
1469
  }
1219
- if (result && !(result instanceof Response)) {
1220
- 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);
1221
1473
  }
1222
1474
  return new Response(null, {
1223
1475
  status,
@@ -1455,7 +1707,7 @@ function enterGuard(value, state) {
1455
1707
  return new Frame(SET, value, next, [...value], null);
1456
1708
  }
1457
1709
  const prototype = Object.getPrototypeOf(value);
1458
- if (prototype !== Object.prototype && prototype !== null) {
1710
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1459
1711
  state.seen.set(value, value);
1460
1712
  return value;
1461
1713
  }
@@ -1466,7 +1718,11 @@ function enterGuard(value, state) {
1466
1718
  }
1467
1719
  const next = Object.create(prototype, descriptors);
1468
1720
  state.seen.set(value, next);
1469
- return new Frame(OBJECT, value, next, Object.keys(value), 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);
1470
1726
  }
1471
1727
  function keepGuarded(value, next, changed, state) {
1472
1728
  if (changed || state.cyclic.has(value)) return next;
@@ -1743,7 +1999,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1743
1999
  const method = request.method;
1744
2000
  const address = resolveAddress(url);
1745
2001
  const functionId = address && address.id;
1746
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2002
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1747
2003
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1748
2004
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1749
2005
  let serverFunction;
@@ -1774,7 +2030,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1774
2030
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1775
2031
  status: 405,
1776
2032
  headers: {
1777
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2033
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1778
2034
  }
1779
2035
  });
1780
2036
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1796,24 +2052,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1796
2052
  });
1797
2053
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1798
2054
  }
1799
- if (!(declared > 0)) {
1800
- let bounded;
1801
- try {
1802
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1803
- } catch {
1804
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1805
- status: 400
1806
- });
1807
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1808
- }
1809
- if (bounded === null) {
1810
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1811
- status: 413
1812
- });
1813
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1814
- }
1815
- 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);
1816
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);
2069
+ }
2070
+ request = bounded;
1817
2071
  }
1818
2072
  let event;
1819
2073
  try {
@@ -1841,7 +2095,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1841
2095
  const scope = run => provide(event, run);
1842
2096
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1843
2097
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1844
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2098
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1845
2099
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1846
2100
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1847
2101
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1856,7 +2110,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1856
2110
  }
1857
2111
  }
1858
2112
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1859
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2113
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1860
2114
  const hook = source === "true" ? flightHook : flightSources.get(source);
1861
2115
  return hook ? [[source, hook]] : [];
1862
2116
  }) : [];
@@ -1864,8 +2118,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1864
2118
  let parsed;
1865
2119
  try {
1866
2120
  parsed = await parseArguments(request, url, scripted, codec);
1867
- } catch {
1868
- 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, {
1869
2124
  status: 400
1870
2125
  });
1871
2126
  return refuseCommitted(response);
@@ -1889,7 +2144,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1889
2144
  const headers = new Headers();
1890
2145
  const dispatch = async () => {
1891
2146
  try {
1892
- let invocations = 0;
1893
2147
  const invokeOnce = async () => {
1894
2148
  INVOCATIONS.set(event, {
1895
2149
  id: functionId
@@ -1903,15 +2157,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1903
2157
  direct: false
1904
2158
  }) : run();
1905
2159
  };
1906
- let result = await provide(event, () => {
1907
- if (++invocations > 1) {
1908
- throw new Error("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.");
1909
- }
1910
- return invokeOnce();
1911
- });
1912
- if (invocations !== 1) {
1913
- throw new Error(invocations === 0 ? "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." : "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.");
1914
- }
2160
+ let result = await provideEventOnce(provide, event, invokeOnce);
1915
2161
  if (transformResult) {
1916
2162
  result = await transformResult(event, result, flightContext);
1917
2163
  }
@@ -1963,7 +2209,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1963
2209
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1964
2210
  }
1965
2211
  if (!scripted) {
1966
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2212
+ if (handleNoJS) {
2213
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2214
+ }
1967
2215
  if (result instanceof Response) return result;
1968
2216
  return encodeResult(result, headers, status, codec, request.signal, scope);
1969
2217
  }
@@ -1983,17 +2231,17 @@ async function handleServerFunctionRequest(request, options = {}) {
1983
2231
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1984
2232
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
1985
2233
  };
1986
- if (x instanceof Response || isResponseEnvelope(x)) {
1987
- if (transformResult) {
1988
- try {
1989
- x = await transformResult(event, x, {
1990
- ...flightContext,
1991
- thrown: true
1992
- });
1993
- } catch (hookError) {
1994
- return respondThrown(hookError);
1995
- }
2234
+ if (transformResult) {
2235
+ try {
2236
+ x = await transformResult(event, x, {
2237
+ ...flightContext,
2238
+ thrown: true
2239
+ });
2240
+ } catch (hookError) {
2241
+ return respondThrown(hookError);
1996
2242
  }
2243
+ }
2244
+ if (x instanceof Response || isResponseEnvelope(x)) {
1997
2245
  let status = 200;
1998
2246
  let metadata;
1999
2247
  if (isResponseEnvelope(x)) {