@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
@@ -247,7 +247,7 @@ function isJSONSafe(value) {
247
247
  const t = typeof v;
248
248
  if (t === "string" || t === "boolean") continue;
249
249
  if (t === "number") {
250
- if (!Number.isFinite(v)) return false;
250
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
251
251
  continue;
252
252
  }
253
253
  if (t !== "object") return false;
@@ -333,31 +333,30 @@ function getHeadersAndBody(body) {
333
333
  async function extractBody(source, codecOptions) {
334
334
  const contentType = source.headers.get("content-type");
335
335
  const format = source.headers.get(BODY_FORMAT_HEADER);
336
- const clone = source.clone();
337
336
  switch (true) {
338
337
  case format === BodyFormat.Serialized:
339
- return await deserializeStream(clone, codecOptions);
338
+ return await deserializeStream(source, codecOptions);
340
339
  case format === BodyFormat.Json:
341
- return JSON.parse(await clone.text());
340
+ return JSON.parse(await source.text());
342
341
  case format === BodyFormat.String:
343
- return await clone.text();
342
+ return await source.text();
344
343
  case format === BodyFormat.File:
345
344
  {
346
- const formData = await clone.formData();
345
+ const formData = await source.formData();
347
346
  return formData.get(FILE_FORM_KEY);
348
347
  }
349
348
  case format === BodyFormat.FormData:
350
349
  case contentType && contentType.startsWith("multipart/form-data"):
351
- return await clone.formData();
350
+ return await source.formData();
352
351
  case format === BodyFormat.URLSearchParams:
353
352
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
354
- return new URLSearchParams(await clone.text());
353
+ return new URLSearchParams(await source.text());
355
354
  case format === BodyFormat.Blob:
356
- return await clone.blob();
355
+ return await source.blob();
357
356
  case format === BodyFormat.ArrayBuffer:
358
- return await clone.arrayBuffer();
357
+ return await source.arrayBuffer();
359
358
  case format === BodyFormat.Uint8Array:
360
- return new Uint8Array(await clone.arrayBuffer());
359
+ return new Uint8Array(await source.arrayBuffer());
361
360
  }
362
361
  return undefined;
363
362
  }
@@ -493,7 +492,7 @@ async function deserializeString(text, codecOptions) {
493
492
  }
494
493
  async function decodeResponse(response, codecOptions) {
495
494
  if (!response.body) return undefined;
496
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
495
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
497
496
  }
498
497
  async function decodeResponsePayload(response, codecOptions) {
499
498
  const decoded = await decodeResponse(response, codecOptions);
@@ -573,6 +572,62 @@ function commitEventResponse(response, event = getRequestEvent()) {
573
572
  });
574
573
  }
575
574
 
575
+ let configuredSecret;
576
+ function setFlashSecret(secret) {
577
+ configuredSecret = secret;
578
+ }
579
+ function resolveSecret() {
580
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
581
+ }
582
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
583
+ let cachedSecret;
584
+ let cachedKey;
585
+ function resolveFlashKey() {
586
+ const secret = resolveSecret();
587
+ if (typeof secret !== "string" || secret.length === 0) return null;
588
+ if (secret !== cachedSecret) {
589
+ cachedSecret = secret;
590
+ cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
591
+ name: "AES-GCM"
592
+ }, false, ["encrypt", "decrypt"]));
593
+ }
594
+ return cachedKey;
595
+ }
596
+ const FLASH_FORMAT_VERSION = "1.";
597
+ const IV_BYTES = 12;
598
+ const GCM_TAG_BYTES = 16;
599
+ function toBase64url(bytes) {
600
+ let binary = "";
601
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
602
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
603
+ }
604
+ function fromBase64url(text) {
605
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
606
+ const bytes = new Uint8Array(binary.length);
607
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
608
+ return bytes;
609
+ }
610
+ async function encryptFlashValue(key, json) {
611
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
612
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
613
+ name: "AES-GCM",
614
+ iv
615
+ }, key, new TextEncoder().encode(json)));
616
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
617
+ packed.set(iv);
618
+ packed.set(ciphertext, IV_BYTES);
619
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
620
+ }
621
+ async function decryptFlashValue(key, value) {
622
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
623
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
624
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
625
+ const plain = await crypto.subtle.decrypt({
626
+ name: "AES-GCM",
627
+ iv: packed.subarray(0, IV_BYTES)
628
+ }, key, packed.subarray(IV_BYTES));
629
+ return new TextDecoder().decode(plain);
630
+ }
576
631
  function encodeInputValue(value) {
577
632
  if (value instanceof FormData) return {
578
633
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -593,7 +648,11 @@ function decodeInputValue(value) {
593
648
  }
594
649
  return value;
595
650
  }
596
- function encodeFlashCookie(url, result, input, thrown) {
651
+ async function encodeFlashCookie(url, result, input, thrown) {
652
+ const key = resolveFlashKey();
653
+ if (!key) {
654
+ return null;
655
+ }
597
656
  const isError = result instanceof Error;
598
657
  const payload = {
599
658
  url,
@@ -602,7 +661,7 @@ function encodeFlashCookie(url, result, input, thrown) {
602
661
  thrown: !!thrown,
603
662
  input: input.map(encodeInputValue)
604
663
  };
605
- if (fitsCookie(payload)) return flashCookie(payload);
664
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
606
665
  payload.truncated = true;
607
666
  payload.input = [];
608
667
  if (!fitsCookie(payload)) {
@@ -619,24 +678,35 @@ function encodeFlashCookie(url, result, input, thrown) {
619
678
  payload.result = true;
620
679
  }
621
680
  }
622
- return flashCookie(payload);
681
+ if (!fitsCookie(payload)) return null;
682
+ return flashCookie(payload, await key);
623
683
  }
624
- function flashCookie(payload) {
625
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
684
+ const FLASH_MAX_AGE_SECONDS = 60;
685
+ async function flashCookie(payload, key) {
686
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
626
687
  secure: true,
627
- httpOnly: true
688
+ httpOnly: true,
689
+ sameSite: "lax",
690
+ maxAge: FLASH_MAX_AGE_SECONDS
628
691
  });
629
692
  }
630
693
  const COOKIE_PAIR_BUDGET = 4000;
631
694
  function fitsCookie(payload) {
632
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
695
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
696
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
697
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
698
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
633
699
  }
634
- function decodeFlashCookie(cookieHeader) {
700
+ async function decodeFlashCookie(cookieHeader) {
635
701
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
636
702
  if (!match) return;
637
703
  try {
638
- const payload = JSON.parse(match);
639
- if (!payload || !payload.result) return;
704
+ const key = resolveFlashKey();
705
+ if (!key) return;
706
+ const json = await decryptFlashValue(await key, match);
707
+ if (json === undefined) return;
708
+ const payload = JSON.parse(json);
709
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
640
710
  const result = payload.error ? new Error(payload.result) : payload.result;
641
711
  const submission = {
642
712
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -647,7 +717,6 @@ function decodeFlashCookie(cookieHeader) {
647
717
  if (payload.truncated) submission.truncated = true;
648
718
  return submission;
649
719
  } catch (error) {
650
- console.error(error);
651
720
  }
652
721
  }
653
722
 
@@ -676,7 +745,8 @@ function configureServerFunctionsServer({
676
745
  csrf,
677
746
  codec,
678
747
  bodySizeLimit,
679
- maxArguments
748
+ maxArguments,
749
+ secret
680
750
  } = {}) {
681
751
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
682
752
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -690,6 +760,7 @@ function configureServerFunctionsServer({
690
760
  if (codec !== undefined) configureServerFunctionsCodec(codec);
691
761
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
692
762
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
763
+ if (secret !== undefined) setFlashSecret(secret);
693
764
  }
694
765
  const flightSources = new Map();
695
766
  function registerFlightDataSource(source, hook) {
@@ -699,13 +770,146 @@ function registerFlightDataSource(source, hook) {
699
770
  if (flightSources.get(source) === hook) flightSources.delete(source);
700
771
  };
701
772
  }
773
+ function resolveWrapInvocation(hook) {
774
+ if (hook === undefined || typeof hook === "function") return hook;
775
+ 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.`);
776
+ }
702
777
  function provideEvent(event, fn) {
703
778
  if (config.provideEvent) return config.provideEvent(event, fn);
704
779
  const ctx = globalThis[RequestContext];
705
780
  if (ctx) return ctx.run(event, fn);
706
781
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
707
782
  }
783
+ 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.";
784
+ 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.";
785
+ function provideEventOnce(provide, event, run) {
786
+ let invocations = 0;
787
+ const settle = () => {
788
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
789
+ };
790
+ const result = provide(event, () => {
791
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
792
+ return run();
793
+ });
794
+ const promised = nativePromise(result);
795
+ if (promised) {
796
+ return promised.then(value => {
797
+ settle();
798
+ return value;
799
+ });
800
+ }
801
+ settle();
802
+ return result;
803
+ }
708
804
  function scopeDeferredResult(value, scope) {
805
+ const bound = bindDeferredBody(value, scope);
806
+ if (bound !== value || value === null || typeof value !== "object") return bound;
807
+ return scopeDeferredContents(value, scope);
808
+ }
809
+ class ScopeFrame {
810
+ constructor(value, next, keys, descriptors) {
811
+ this.value = value;
812
+ this.next = next;
813
+ this.keys = keys;
814
+ this.descriptors = descriptors;
815
+ this.i = 0;
816
+ this.changed = false;
817
+ }
818
+ }
819
+ function enterScopeCarrier(value, state) {
820
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
821
+ if (state.seen.has(value)) {
822
+ state.cyclic.add(value);
823
+ return state.seen.get(value);
824
+ }
825
+ const bound = bindDeferredBody(value, state.scope);
826
+ if (bound !== value) {
827
+ state.seen.set(value, bound);
828
+ return bound;
829
+ }
830
+ if (typeof value !== "object") return value;
831
+ if (Array.isArray(value)) {
832
+ if (Object.isFrozen(value)) {
833
+ state.seen.set(value, value);
834
+ return value;
835
+ }
836
+ const next = value.slice();
837
+ state.seen.set(value, next);
838
+ return new ScopeFrame(value, next, null, null);
839
+ }
840
+ const prototype = Object.getPrototypeOf(value);
841
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
842
+ state.seen.set(value, value);
843
+ return value;
844
+ }
845
+ const descriptors = Object.getOwnPropertyDescriptors(value);
846
+ const next = Object.create(prototype, descriptors);
847
+ state.seen.set(value, next);
848
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
849
+ }
850
+ function scopeDeferredContents(root, scope) {
851
+ const state = {
852
+ seen: new Map(),
853
+ cyclic: new Set(),
854
+ scope
855
+ };
856
+ const entered = enterScopeCarrier(root, state);
857
+ if (!(entered instanceof ScopeFrame)) return entered;
858
+ const stack = [entered];
859
+ let delivered = NOTHING;
860
+ for (;;) {
861
+ const top = stack[stack.length - 1];
862
+ const length = top.keys ? top.keys.length : top.value.length;
863
+ let pushed = null;
864
+ while (top.i < length) {
865
+ const i = top.i;
866
+ let original;
867
+ let writable = true;
868
+ if (top.keys) {
869
+ const descriptor = top.descriptors[top.keys[i]];
870
+ writable = "value" in descriptor && descriptor.writable === true;
871
+ original = writable ? descriptor.value : undefined;
872
+ } else {
873
+ original = top.value[i];
874
+ }
875
+ if (!writable) {
876
+ top.i++;
877
+ continue;
878
+ }
879
+ let bound;
880
+ if (delivered !== NOTHING) {
881
+ bound = delivered;
882
+ delivered = NOTHING;
883
+ } else {
884
+ bound = enterScopeCarrier(original, state);
885
+ if (bound instanceof ScopeFrame) {
886
+ pushed = bound;
887
+ break;
888
+ }
889
+ }
890
+ if (bound !== original) {
891
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
892
+ top.changed = true;
893
+ }
894
+ top.i++;
895
+ }
896
+ if (pushed !== null) {
897
+ stack.push(pushed);
898
+ continue;
899
+ }
900
+ stack.pop();
901
+ let out;
902
+ if (top.changed || state.cyclic.has(top.value)) {
903
+ out = top.next;
904
+ } else {
905
+ state.seen.set(top.value, top.value);
906
+ out = top.value;
907
+ }
908
+ if (stack.length === 0) return out;
909
+ delivered = out;
910
+ }
911
+ }
912
+ function bindDeferredBody(value, scope) {
709
913
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
710
914
  const promised = scope(() => nativePromise(value));
711
915
  if (promised) {
@@ -753,6 +957,11 @@ function scopeDeferredResult(value, scope) {
753
957
  }
754
958
  const REGISTRATIONS = new Map();
755
959
  const METHODS = new Map();
960
+ const REFERENCE_BINDINGS = new WeakMap();
961
+ function declaresRead(id) {
962
+ const granted = METHODS.get(id);
963
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
964
+ }
756
965
  const INVOCATIONS = new WeakMap();
757
966
  let rpcProvided = false;
758
967
  function provideRPC() {
@@ -849,9 +1058,10 @@ function createServerReference({
849
1058
  });
850
1059
  evt.serverOnly = true;
851
1060
  const scope = run => provideEvent(evt, run);
852
- let result = provideEvent(evt, () => {
1061
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1062
+ let result = provideEventOnce(provideEvent, evt, () => {
853
1063
  const run = () => fn.apply(thisArg, args);
854
- return config.wrapInvocation ? config.wrapInvocation(run, {
1064
+ return wrap ? wrap(run, {
855
1065
  id,
856
1066
  args,
857
1067
  event: evt,
@@ -874,16 +1084,45 @@ function createServerReference({
874
1084
  }), scope) : result;
875
1085
  }
876
1086
  });
1087
+ REFERENCE_BINDINGS.set(proxy, fn);
877
1088
  return proxy;
878
1089
  }
879
1090
  function GET(fn) {
880
1091
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
881
1092
  throw new Error("GET expects a server function reference");
882
1093
  }
883
- METHODS.set(fn.id, "GET");
884
- return withMeta(fn, {
1094
+ const id = fn.id;
1095
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1096
+ const existing = METHODS.get(id);
1097
+ if (existing !== undefined && existing !== binding) {
1098
+ if (DEV) {
1099
+ 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.`);
1100
+ }
1101
+ METHODS.delete(id);
1102
+ return fn;
1103
+ }
1104
+ METHODS.set(id, binding);
1105
+ const reference = withMeta(fn, {
885
1106
  method: "GET"
886
1107
  });
1108
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1109
+ return reference;
1110
+ }
1111
+ function guardDeclaredMethod(metadata, id) {
1112
+ let declared = metadata.method;
1113
+ Object.defineProperty(metadata, "method", {
1114
+ configurable: true,
1115
+ enumerable: true,
1116
+ get: () => declared,
1117
+ set(next) {
1118
+ if (next === declared) return;
1119
+ if (DEV) {
1120
+ 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.`);
1121
+ }
1122
+ METHODS.delete(id);
1123
+ declared = next;
1124
+ }
1125
+ });
887
1126
  }
888
1127
  function live(fn) {
889
1128
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -1000,6 +1239,13 @@ async function bufferBodyWithin(request, limit) {
1000
1239
  body
1001
1240
  });
1002
1241
  }
1242
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1243
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1244
+ function unknownFormatError(tag) {
1245
+ 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.");
1246
+ error[FORMAT_SKEW] = true;
1247
+ return error;
1248
+ }
1003
1249
  async function parseArguments(request, url, scripted, codec) {
1004
1250
  const parsed = [];
1005
1251
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1023,7 +1269,11 @@ async function parseArguments(request, url, scripted, codec) {
1023
1269
  parsed.push(url.searchParams);
1024
1270
  }
1025
1271
  if (request.method === "POST" && request.body !== null) {
1026
- const decoded = await extractBody(request.clone(), codec);
1272
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1273
+ throw unknownFormatError(bodyFormat);
1274
+ }
1275
+ const body = request.clone();
1276
+ const decoded = await extractBody(body, codec);
1027
1277
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1028
1278
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1029
1279
  if (!Array.isArray(decoded)) {
@@ -1032,7 +1282,7 @@ async function parseArguments(request, url, scripted, codec) {
1032
1282
  return stripUnsafeArgumentKeys(decoded);
1033
1283
  }
1034
1284
  if (decoded === undefined) {
1035
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1285
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1036
1286
  return parsed;
1037
1287
  }
1038
1288
  throw new TypeError("Server function body carries no usable encoding");
@@ -1062,13 +1312,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1062
1312
  data
1063
1313
  }, context);
1064
1314
  if (transformed !== undefined) {
1065
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1315
+ const owned = ownResponse(transformed);
1316
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
1066
1317
  headers.forEach((value, key) => {
1067
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1068
- transformed.headers.set(key, value);
1318
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1319
+ owned.headers.set(key, value);
1069
1320
  }
1070
1321
  });
1071
- return transformed;
1322
+ return owned;
1072
1323
  }
1073
1324
  }
1074
1325
  return outcome.value === undefined ? {
@@ -1189,7 +1440,7 @@ function warnScripted304(functionId) {
1189
1440
  function createNoJSHandler({
1190
1441
  base = ""
1191
1442
  } = {}) {
1192
- return function handleNoJS(result, request, args, thrown) {
1443
+ return async function handleNoJS(result, request, args, thrown) {
1193
1444
  const url = new URL(request.url);
1194
1445
  let back = new URL(base || "/", url.origin).toString();
1195
1446
  try {
@@ -1214,8 +1465,9 @@ function createNoJSHandler({
1214
1465
  Location: back
1215
1466
  });
1216
1467
  }
1217
- if (result && !(result instanceof Response)) {
1218
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1468
+ if (result !== undefined && !(result instanceof Response)) {
1469
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1470
+ if (flash !== null) headers.append("Set-Cookie", flash);
1219
1471
  }
1220
1472
  return new Response(null, {
1221
1473
  status,
@@ -1453,7 +1705,7 @@ function enterGuard(value, state) {
1453
1705
  return new Frame(SET, value, next, [...value], null);
1454
1706
  }
1455
1707
  const prototype = Object.getPrototypeOf(value);
1456
- if (prototype !== Object.prototype && prototype !== null) {
1708
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1457
1709
  state.seen.set(value, value);
1458
1710
  return value;
1459
1711
  }
@@ -1464,7 +1716,11 @@ function enterGuard(value, state) {
1464
1716
  }
1465
1717
  const next = Object.create(prototype, descriptors);
1466
1718
  state.seen.set(value, next);
1467
- return new Frame(OBJECT, value, next, Object.keys(value), descriptors);
1719
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1720
+ const descriptor = descriptors[key];
1721
+ return descriptor.enumerable || "value" in descriptor;
1722
+ });
1723
+ return new Frame(OBJECT, value, next, children, descriptors);
1468
1724
  }
1469
1725
  function keepGuarded(value, next, changed, state) {
1470
1726
  if (changed || state.cyclic.has(value)) return next;
@@ -1741,7 +1997,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1741
1997
  const method = request.method;
1742
1998
  const address = resolveAddress(url);
1743
1999
  const functionId = address && address.id;
1744
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2000
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1745
2001
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1746
2002
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1747
2003
  let serverFunction;
@@ -1772,7 +2028,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1772
2028
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1773
2029
  status: 405,
1774
2030
  headers: {
1775
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2031
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1776
2032
  }
1777
2033
  });
1778
2034
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1794,24 +2050,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1794
2050
  });
1795
2051
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1796
2052
  }
1797
- if (!(declared > 0)) {
1798
- let bounded;
1799
- try {
1800
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1801
- } catch {
1802
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1803
- status: 400
1804
- });
1805
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1806
- }
1807
- if (bounded === null) {
1808
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1809
- status: 413
1810
- });
1811
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1812
- }
1813
- request = bounded;
2053
+ let bounded;
2054
+ try {
2055
+ bounded = await bufferBodyWithin(request, bodySizeLimit);
2056
+ } catch {
2057
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2058
+ status: 400
2059
+ });
2060
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1814
2061
  }
2062
+ if (bounded === null) {
2063
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2064
+ status: 413
2065
+ });
2066
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2067
+ }
2068
+ request = bounded;
1815
2069
  }
1816
2070
  let event;
1817
2071
  try {
@@ -1839,7 +2093,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1839
2093
  const scope = run => provide(event, run);
1840
2094
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1841
2095
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1842
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2096
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1843
2097
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1844
2098
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1845
2099
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1854,7 +2108,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1854
2108
  }
1855
2109
  }
1856
2110
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1857
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2111
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1858
2112
  const hook = source === "true" ? flightHook : flightSources.get(source);
1859
2113
  return hook ? [[source, hook]] : [];
1860
2114
  }) : [];
@@ -1862,8 +2116,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1862
2116
  let parsed;
1863
2117
  try {
1864
2118
  parsed = await parseArguments(request, url, scripted, codec);
1865
- } catch {
1866
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2119
+ } catch (error) {
2120
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2121
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1867
2122
  status: 400
1868
2123
  });
1869
2124
  return refuseCommitted(response);
@@ -1887,7 +2142,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1887
2142
  const headers = new Headers();
1888
2143
  const dispatch = async () => {
1889
2144
  try {
1890
- let invocations = 0;
1891
2145
  const invokeOnce = async () => {
1892
2146
  INVOCATIONS.set(event, {
1893
2147
  id: functionId
@@ -1901,15 +2155,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1901
2155
  direct: false
1902
2156
  }) : run();
1903
2157
  };
1904
- let result = await provide(event, () => {
1905
- if (++invocations > 1) {
1906
- 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.");
1907
- }
1908
- return invokeOnce();
1909
- });
1910
- if (invocations !== 1) {
1911
- 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.");
1912
- }
2158
+ let result = await provideEventOnce(provide, event, invokeOnce);
1913
2159
  if (transformResult) {
1914
2160
  result = await transformResult(event, result, flightContext);
1915
2161
  }
@@ -1961,7 +2207,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1961
2207
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1962
2208
  }
1963
2209
  if (!scripted) {
1964
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2210
+ if (handleNoJS) {
2211
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2212
+ }
1965
2213
  if (result instanceof Response) return result;
1966
2214
  return encodeResult(result, headers, status, codec, request.signal, scope);
1967
2215
  }
@@ -1981,17 +2229,17 @@ async function handleServerFunctionRequest(request, options = {}) {
1981
2229
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1982
2230
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
1983
2231
  };
1984
- if (x instanceof Response || isResponseEnvelope(x)) {
1985
- if (transformResult) {
1986
- try {
1987
- x = await transformResult(event, x, {
1988
- ...flightContext,
1989
- thrown: true
1990
- });
1991
- } catch (hookError) {
1992
- return respondThrown(hookError);
1993
- }
2232
+ if (transformResult) {
2233
+ try {
2234
+ x = await transformResult(event, x, {
2235
+ ...flightContext,
2236
+ thrown: true
2237
+ });
2238
+ } catch (hookError) {
2239
+ return respondThrown(hookError);
1994
2240
  }
2241
+ }
2242
+ if (x instanceof Response || isResponseEnvelope(x)) {
1995
2243
  let status = 200;
1996
2244
  let metadata;
1997
2245
  if (isResponseEnvelope(x)) {