@solidjs/web 2.0.0-rc.6 → 2.0.0-rc.8

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 (82) hide show
  1. package/dist/{server.cjs → server.dev.js} +274 -272
  2. package/dist/server.js +119 -36
  3. package/dist/{dev.js → web.dev.js} +131 -399
  4. package/dist/web.js +78 -388
  5. package/dist/{web.cjs → web.observe.js} +174 -622
  6. package/frames/dist/client.dev.js +11 -3
  7. package/frames/dist/client.js +11 -3
  8. package/frames/dist/{server.cjs → server.dev.js} +375 -125
  9. package/frames/dist/server.js +253 -32
  10. package/frames/package.json +7 -15
  11. package/package.json +88 -251
  12. package/serialization/decode/package.json +3 -9
  13. package/serialization/dist/decode.js +18 -4
  14. package/serialization/dist/serialization.js +18 -4
  15. package/serialization/package.json +3 -9
  16. package/serialization/types/serializer-decode.d.ts +49 -2
  17. package/server-functions/dist/client.js +13 -14
  18. package/server-functions/dist/server.dev.js +359 -85
  19. package/server-functions/dist/server.js +352 -86
  20. package/server-functions/package.json +6 -24
  21. package/server-functions/rich-args/package.json +3 -9
  22. package/storage/package.json +3 -9
  23. package/types/client.d.ts +17 -3
  24. package/types/frames/frame-client.d.ts +1 -1
  25. package/types/frames/serializer-decode.d.ts +49 -2
  26. package/types/head.d.ts +3 -0
  27. package/types/index.d.ts +18 -7
  28. package/types/index.server.d.ts +31 -9
  29. package/types/render.d.ts +3 -1
  30. package/types/serializer-decode.d.ts +49 -2
  31. package/types/server-functions/flash.d.ts +12 -3
  32. package/types/server-functions/server.d.ts +50 -3
  33. package/types/server-mock.d.ts +43 -7
  34. package/types/server.d.ts +48 -6
  35. package/dist/dev.cjs +0 -2590
  36. package/frames/dist/client.cjs +0 -2035
  37. package/frames/dist/client.dev.cjs +0 -2055
  38. package/serialization/dist/decode.cjs +0 -141
  39. package/serialization/dist/serialization.cjs +0 -261
  40. package/serialization/types-cjs/index.d.cts +0 -101
  41. package/serialization/types-cjs/package.json +0 -3
  42. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  43. package/serialization/types-cjs/serializer.d.cts +0 -101
  44. package/server-functions/dist/client.cjs +0 -1070
  45. package/server-functions/dist/rich-args.cjs +0 -11
  46. package/server-functions/dist/server.cjs +0 -2133
  47. package/server-functions/dist/server.dev.cjs +0 -2153
  48. package/storage/dist/storage.cjs +0 -12
  49. package/storage/types-cjs/index.d.cts +0 -28
  50. package/storage/types-cjs/package.json +0 -3
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/client.d.cts +0 -200
  53. package/types-cjs/constants.d.cts +0 -20
  54. package/types-cjs/cookies.d.cts +0 -41
  55. package/types-cjs/frames/client.d.cts +0 -36
  56. package/types-cjs/frames/frame-client.d.cts +0 -370
  57. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  58. package/types-cjs/frames/frame-sink.d.cts +0 -92
  59. package/types-cjs/frames/frame-transport.d.cts +0 -189
  60. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  61. package/types-cjs/frames/serializer.d.cts +0 -101
  62. package/types-cjs/frames/server.d.cts +0 -52
  63. package/types-cjs/head.d.cts +0 -16
  64. package/types-cjs/index.d.cts +0 -180
  65. package/types-cjs/index.server.d.cts +0 -125
  66. package/types-cjs/jsx-properties.d.cts +0 -93
  67. package/types-cjs/jsx.d.cts +0 -4146
  68. package/types-cjs/package.json +0 -3
  69. package/types-cjs/patch-driver.d.cts +0 -3
  70. package/types-cjs/reconcile.d.cts +0 -1
  71. package/types-cjs/render.d.cts +0 -4
  72. package/types-cjs/response.d.cts +0 -81
  73. package/types-cjs/serializer-decode.d.cts +0 -172
  74. package/types-cjs/serializer.d.cts +0 -101
  75. package/types-cjs/server-functions/client.d.cts +0 -184
  76. package/types-cjs/server-functions/flash.d.cts +0 -27
  77. package/types-cjs/server-functions/registry.d.cts +0 -100
  78. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  79. package/types-cjs/server-functions/server.d.cts +0 -522
  80. package/types-cjs/server-functions/shared.d.cts +0 -283
  81. package/types-cjs/server-mock.d.cts +0 -301
  82. package/types-cjs/server.d.cts +0 -366
@@ -267,7 +267,7 @@ function isJSONSafe(value) {
267
267
  const t = typeof v;
268
268
  if (t === "string" || t === "boolean") continue;
269
269
  if (t === "number") {
270
- if (!Number.isFinite(v)) return false;
270
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
271
271
  continue;
272
272
  }
273
273
  if (t !== "object") return false;
@@ -353,31 +353,30 @@ function getHeadersAndBody(body) {
353
353
  async function extractBody(source, codecOptions) {
354
354
  const contentType = source.headers.get("content-type");
355
355
  const format = source.headers.get(BODY_FORMAT_HEADER);
356
- const clone = source.clone();
357
356
  switch (true) {
358
357
  case format === BodyFormat.Serialized:
359
- return await deserializeStream(clone, codecOptions);
358
+ return await deserializeStream(source, codecOptions);
360
359
  case format === BodyFormat.Json:
361
- return JSON.parse(await clone.text());
360
+ return JSON.parse(await source.text());
362
361
  case format === BodyFormat.String:
363
- return await clone.text();
362
+ return await source.text();
364
363
  case format === BodyFormat.File:
365
364
  {
366
- const formData = await clone.formData();
365
+ const formData = await source.formData();
367
366
  return formData.get(FILE_FORM_KEY);
368
367
  }
369
368
  case format === BodyFormat.FormData:
370
369
  case contentType && contentType.startsWith("multipart/form-data"):
371
- return await clone.formData();
370
+ return await source.formData();
372
371
  case format === BodyFormat.URLSearchParams:
373
372
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
374
- return new URLSearchParams(await clone.text());
373
+ return new URLSearchParams(await source.text());
375
374
  case format === BodyFormat.Blob:
376
- return await clone.blob();
375
+ return await source.blob();
377
376
  case format === BodyFormat.ArrayBuffer:
378
- return await clone.arrayBuffer();
377
+ return await source.arrayBuffer();
379
378
  case format === BodyFormat.Uint8Array:
380
- return new Uint8Array(await clone.arrayBuffer());
379
+ return new Uint8Array(await source.arrayBuffer());
381
380
  }
382
381
  return undefined;
383
382
  }
@@ -513,7 +512,7 @@ async function deserializeString(text, codecOptions) {
513
512
  }
514
513
  async function decodeResponse(response, codecOptions) {
515
514
  if (!response.body) return undefined;
516
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
515
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
517
516
  }
518
517
  async function decodeResponsePayload(response, codecOptions) {
519
518
  const decoded = await decodeResponse(response, codecOptions);
@@ -593,6 +592,76 @@ function commitEventResponse(response, event = getRequestEvent()) {
593
592
  });
594
593
  }
595
594
 
595
+ let configuredSecret;
596
+ function setFlashSecret(secret) {
597
+ configuredSecret = secret;
598
+ }
599
+ function resolveSecret() {
600
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
601
+ }
602
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
603
+ const FLASH_KEY_ITERATIONS = 100_000;
604
+ let cachedSecret;
605
+ let cachedKey;
606
+ function resolveFlashKey() {
607
+ const secret = resolveSecret();
608
+ if (typeof secret !== "string" || secret.length === 0) return null;
609
+ if (secret !== cachedSecret) {
610
+ cachedSecret = secret;
611
+ const encoder = new TextEncoder();
612
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
613
+ name: "PBKDF2",
614
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
615
+ iterations: FLASH_KEY_ITERATIONS,
616
+ hash: "SHA-256"
617
+ }, material, {
618
+ name: "AES-GCM",
619
+ length: 256
620
+ }, false, ["encrypt", "decrypt"]));
621
+ }
622
+ return cachedKey;
623
+ }
624
+ let warnedMissingKey = false;
625
+ function warnMissingKey() {
626
+ if (warnedMissingKey) return;
627
+ warnedMissingKey = true;
628
+ console.warn("[solid] A no-JS form outcome was not flashed: the flash cookie is encrypted and no key " + "is configured. Set configureServerFunctionsServer({ secret }) — or build with the Solid " + "bundler plugin, which provides a per-deployment key automatically. The submission " + "committed and the redirect was served; only the outcome echo was withheld.");
629
+ }
630
+ const FLASH_FORMAT_VERSION = "1.";
631
+ const IV_BYTES = 12;
632
+ const GCM_TAG_BYTES = 16;
633
+ function toBase64url(bytes) {
634
+ let binary = "";
635
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
636
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
637
+ }
638
+ function fromBase64url(text) {
639
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
640
+ const bytes = new Uint8Array(binary.length);
641
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
642
+ return bytes;
643
+ }
644
+ async function encryptFlashValue(key, json) {
645
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
646
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
647
+ name: "AES-GCM",
648
+ iv
649
+ }, key, new TextEncoder().encode(json)));
650
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
651
+ packed.set(iv);
652
+ packed.set(ciphertext, IV_BYTES);
653
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
654
+ }
655
+ async function decryptFlashValue(key, value) {
656
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
657
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
658
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
659
+ const plain = await crypto.subtle.decrypt({
660
+ name: "AES-GCM",
661
+ iv: packed.subarray(0, IV_BYTES)
662
+ }, key, packed.subarray(IV_BYTES));
663
+ return new TextDecoder().decode(plain);
664
+ }
596
665
  function encodeInputValue(value) {
597
666
  if (value instanceof FormData) return {
598
667
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -613,7 +682,12 @@ function decodeInputValue(value) {
613
682
  }
614
683
  return value;
615
684
  }
616
- function encodeFlashCookie(url, result, input, thrown) {
685
+ async function encodeFlashCookie(url, result, input, thrown) {
686
+ const key = resolveFlashKey();
687
+ if (!key) {
688
+ warnMissingKey();
689
+ return null;
690
+ }
617
691
  const isError = result instanceof Error;
618
692
  const payload = {
619
693
  url,
@@ -622,7 +696,7 @@ function encodeFlashCookie(url, result, input, thrown) {
622
696
  thrown: !!thrown,
623
697
  input: input.map(encodeInputValue)
624
698
  };
625
- if (fitsCookie(payload)) return flashCookie(payload);
699
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
626
700
  payload.truncated = true;
627
701
  payload.input = [];
628
702
  if (!fitsCookie(payload)) {
@@ -639,24 +713,35 @@ function encodeFlashCookie(url, result, input, thrown) {
639
713
  payload.result = true;
640
714
  }
641
715
  }
642
- return flashCookie(payload);
716
+ if (!fitsCookie(payload)) return null;
717
+ return flashCookie(payload, await key);
643
718
  }
644
- function flashCookie(payload) {
645
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
719
+ const FLASH_MAX_AGE_SECONDS = 60;
720
+ async function flashCookie(payload, key) {
721
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
646
722
  secure: true,
647
- httpOnly: true
723
+ httpOnly: true,
724
+ sameSite: "lax",
725
+ maxAge: FLASH_MAX_AGE_SECONDS
648
726
  });
649
727
  }
650
728
  const COOKIE_PAIR_BUDGET = 4000;
651
729
  function fitsCookie(payload) {
652
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
730
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
731
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
732
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
733
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
653
734
  }
654
- function decodeFlashCookie(cookieHeader) {
735
+ async function decodeFlashCookie(cookieHeader) {
655
736
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
656
737
  if (!match) return;
657
738
  try {
658
- const payload = JSON.parse(match);
659
- if (!payload || !payload.result) return;
739
+ const key = resolveFlashKey();
740
+ if (!key) return;
741
+ const json = await decryptFlashValue(await key, match);
742
+ if (json === undefined) return;
743
+ const payload = JSON.parse(json);
744
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
660
745
  const result = payload.error ? new Error(payload.result) : payload.result;
661
746
  const submission = {
662
747
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -696,7 +781,8 @@ function configureServerFunctionsServer({
696
781
  csrf,
697
782
  codec,
698
783
  bodySizeLimit,
699
- maxArguments
784
+ maxArguments,
785
+ secret
700
786
  } = {}) {
701
787
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
702
788
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -710,6 +796,7 @@ function configureServerFunctionsServer({
710
796
  if (codec !== undefined) configureServerFunctionsCodec(codec);
711
797
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
712
798
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
799
+ if (secret !== undefined) setFlashSecret(secret);
713
800
  }
714
801
  const flightSources = new Map();
715
802
  function registerFlightDataSource(source, hook) {
@@ -719,13 +806,146 @@ function registerFlightDataSource(source, hook) {
719
806
  if (flightSources.get(source) === hook) flightSources.delete(source);
720
807
  };
721
808
  }
809
+ function resolveWrapInvocation(hook) {
810
+ if (hook === undefined || typeof hook === "function") return hook;
811
+ 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.`);
812
+ }
722
813
  function provideEvent(event, fn) {
723
814
  if (config.provideEvent) return config.provideEvent(event, fn);
724
815
  const ctx = globalThis[RequestContext];
725
816
  if (ctx) return ctx.run(event, fn);
726
817
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
727
818
  }
819
+ 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.";
820
+ 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.";
821
+ function provideEventOnce(provide, event, run) {
822
+ let invocations = 0;
823
+ const settle = () => {
824
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
825
+ };
826
+ const result = provide(event, () => {
827
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
828
+ return run();
829
+ });
830
+ const promised = nativePromise(result);
831
+ if (promised) {
832
+ return promised.then(value => {
833
+ settle();
834
+ return value;
835
+ });
836
+ }
837
+ settle();
838
+ return result;
839
+ }
728
840
  function scopeDeferredResult(value, scope) {
841
+ const bound = bindDeferredBody(value, scope);
842
+ if (bound !== value || value === null || typeof value !== "object") return bound;
843
+ return scopeDeferredContents(value, scope);
844
+ }
845
+ class ScopeFrame {
846
+ constructor(value, next, keys, descriptors) {
847
+ this.value = value;
848
+ this.next = next;
849
+ this.keys = keys;
850
+ this.descriptors = descriptors;
851
+ this.i = 0;
852
+ this.changed = false;
853
+ }
854
+ }
855
+ function enterScopeCarrier(value, state) {
856
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
857
+ if (state.seen.has(value)) {
858
+ state.cyclic.add(value);
859
+ return state.seen.get(value);
860
+ }
861
+ const bound = bindDeferredBody(value, state.scope);
862
+ if (bound !== value) {
863
+ state.seen.set(value, bound);
864
+ return bound;
865
+ }
866
+ if (typeof value !== "object") return value;
867
+ if (Array.isArray(value)) {
868
+ if (Object.isFrozen(value)) {
869
+ state.seen.set(value, value);
870
+ return value;
871
+ }
872
+ const next = value.slice();
873
+ state.seen.set(value, next);
874
+ return new ScopeFrame(value, next, null, null);
875
+ }
876
+ const prototype = Object.getPrototypeOf(value);
877
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
878
+ state.seen.set(value, value);
879
+ return value;
880
+ }
881
+ const descriptors = Object.getOwnPropertyDescriptors(value);
882
+ const next = Object.create(prototype, descriptors);
883
+ state.seen.set(value, next);
884
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
885
+ }
886
+ function scopeDeferredContents(root, scope) {
887
+ const state = {
888
+ seen: new Map(),
889
+ cyclic: new Set(),
890
+ scope
891
+ };
892
+ const entered = enterScopeCarrier(root, state);
893
+ if (!(entered instanceof ScopeFrame)) return entered;
894
+ const stack = [entered];
895
+ let delivered = NOTHING;
896
+ for (;;) {
897
+ const top = stack[stack.length - 1];
898
+ const length = top.keys ? top.keys.length : top.value.length;
899
+ let pushed = null;
900
+ while (top.i < length) {
901
+ const i = top.i;
902
+ let original;
903
+ let writable = true;
904
+ if (top.keys) {
905
+ const descriptor = top.descriptors[top.keys[i]];
906
+ writable = "value" in descriptor && descriptor.writable === true;
907
+ original = writable ? descriptor.value : undefined;
908
+ } else {
909
+ original = top.value[i];
910
+ }
911
+ if (!writable) {
912
+ top.i++;
913
+ continue;
914
+ }
915
+ let bound;
916
+ if (delivered !== NOTHING) {
917
+ bound = delivered;
918
+ delivered = NOTHING;
919
+ } else {
920
+ bound = enterScopeCarrier(original, state);
921
+ if (bound instanceof ScopeFrame) {
922
+ pushed = bound;
923
+ break;
924
+ }
925
+ }
926
+ if (bound !== original) {
927
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
928
+ top.changed = true;
929
+ }
930
+ top.i++;
931
+ }
932
+ if (pushed !== null) {
933
+ stack.push(pushed);
934
+ continue;
935
+ }
936
+ stack.pop();
937
+ let out;
938
+ if (top.changed || state.cyclic.has(top.value)) {
939
+ out = top.next;
940
+ } else {
941
+ state.seen.set(top.value, top.value);
942
+ out = top.value;
943
+ }
944
+ if (stack.length === 0) return out;
945
+ delivered = out;
946
+ }
947
+ }
948
+ function bindDeferredBody(value, scope) {
729
949
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
730
950
  const promised = scope(() => nativePromise(value));
731
951
  if (promised) {
@@ -771,8 +991,17 @@ function scopeDeferredResult(value, scope) {
771
991
  }
772
992
  return value;
773
993
  }
774
- const REGISTRATIONS = new Map();
775
- const METHODS = new Map();
994
+ function processState(key, create) {
995
+ const slot = Symbol.for(key);
996
+ return globalThis[slot] || (globalThis[slot] = create());
997
+ }
998
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
999
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1000
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
1001
+ function declaresRead(id) {
1002
+ const granted = METHODS.get(id);
1003
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
1004
+ }
776
1005
  const INVOCATIONS = new WeakMap();
777
1006
  let rpcProvided = false;
778
1007
  function provideRPC() {
@@ -869,9 +1098,10 @@ function createServerReference({
869
1098
  });
870
1099
  evt.serverOnly = true;
871
1100
  const scope = run => provideEvent(evt, run);
872
- let result = provideEvent(evt, () => {
1101
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1102
+ let result = provideEventOnce(provideEvent, evt, () => {
873
1103
  const run = () => fn.apply(thisArg, args);
874
- return config.wrapInvocation ? config.wrapInvocation(run, {
1104
+ return wrap ? wrap(run, {
875
1105
  id,
876
1106
  args,
877
1107
  event: evt,
@@ -894,16 +1124,45 @@ function createServerReference({
894
1124
  }), scope) : result;
895
1125
  }
896
1126
  });
1127
+ REFERENCE_BINDINGS.set(proxy, fn);
897
1128
  return proxy;
898
1129
  }
899
1130
  function GET(fn) {
900
1131
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
901
1132
  throw new Error("GET expects a server function reference");
902
1133
  }
903
- METHODS.set(fn.id, "GET");
904
- return withMeta(fn, {
1134
+ const id = fn.id;
1135
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1136
+ const existing = METHODS.get(id);
1137
+ if (existing !== undefined && existing !== binding) {
1138
+ if (DEV) {
1139
+ 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.`);
1140
+ }
1141
+ METHODS.delete(id);
1142
+ return fn;
1143
+ }
1144
+ METHODS.set(id, binding);
1145
+ const reference = withMeta(fn, {
905
1146
  method: "GET"
906
1147
  });
1148
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1149
+ return reference;
1150
+ }
1151
+ function guardDeclaredMethod(metadata, id) {
1152
+ let declared = metadata.method;
1153
+ Object.defineProperty(metadata, "method", {
1154
+ configurable: true,
1155
+ enumerable: true,
1156
+ get: () => declared,
1157
+ set(next) {
1158
+ if (next === declared) return;
1159
+ if (DEV) {
1160
+ 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.`);
1161
+ }
1162
+ METHODS.delete(id);
1163
+ declared = next;
1164
+ }
1165
+ });
907
1166
  }
908
1167
  function live(fn) {
909
1168
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -1016,10 +1275,23 @@ async function bufferBodyWithin(request, limit) {
1016
1275
  body.set(chunk, offset);
1017
1276
  offset += chunk.byteLength;
1018
1277
  }
1019
- return new Request(request, {
1278
+ return body;
1279
+ }
1280
+ function withBufferedBody(request, body) {
1281
+ return new Request(request.url, {
1282
+ method: request.method,
1283
+ headers: request.headers,
1284
+ signal: request.signal,
1020
1285
  body
1021
1286
  });
1022
1287
  }
1288
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1289
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1290
+ function unknownFormatError(tag) {
1291
+ 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.");
1292
+ error[FORMAT_SKEW] = true;
1293
+ return error;
1294
+ }
1023
1295
  async function parseArguments(request, url, scripted, codec) {
1024
1296
  const parsed = [];
1025
1297
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1043,7 +1315,11 @@ async function parseArguments(request, url, scripted, codec) {
1043
1315
  parsed.push(url.searchParams);
1044
1316
  }
1045
1317
  if (request.method === "POST" && request.body !== null) {
1046
- const decoded = await extractBody(request.clone(), codec);
1318
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1319
+ throw unknownFormatError(bodyFormat);
1320
+ }
1321
+ const body = request.clone();
1322
+ const decoded = await extractBody(body, codec);
1047
1323
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1048
1324
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1049
1325
  if (!Array.isArray(decoded)) {
@@ -1052,7 +1328,7 @@ async function parseArguments(request, url, scripted, codec) {
1052
1328
  return stripUnsafeArgumentKeys(decoded);
1053
1329
  }
1054
1330
  if (decoded === undefined) {
1055
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1331
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1056
1332
  return parsed;
1057
1333
  }
1058
1334
  throw new TypeError("Server function body carries no usable encoding");
@@ -1082,13 +1358,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1082
1358
  data
1083
1359
  }, context);
1084
1360
  if (transformed !== undefined) {
1085
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1361
+ const owned = ownResponse(transformed);
1362
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
1086
1363
  headers.forEach((value, key) => {
1087
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1088
- transformed.headers.set(key, value);
1364
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1365
+ owned.headers.set(key, value);
1089
1366
  }
1090
1367
  });
1091
- return transformed;
1368
+ return owned;
1092
1369
  }
1093
1370
  }
1094
1371
  return outcome.value === undefined ? {
@@ -1209,7 +1486,7 @@ function warnScripted304(functionId) {
1209
1486
  function createNoJSHandler({
1210
1487
  base = ""
1211
1488
  } = {}) {
1212
- return function handleNoJS(result, request, args, thrown) {
1489
+ return async function handleNoJS(result, request, args, thrown) {
1213
1490
  const url = new URL(request.url);
1214
1491
  let back = new URL(base || "/", url.origin).toString();
1215
1492
  try {
@@ -1234,8 +1511,9 @@ function createNoJSHandler({
1234
1511
  Location: back
1235
1512
  });
1236
1513
  }
1237
- if (result && !(result instanceof Response)) {
1238
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1514
+ if (result !== undefined && !(result instanceof Response)) {
1515
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1516
+ if (flash !== null) headers.append("Set-Cookie", flash);
1239
1517
  }
1240
1518
  return new Response(null, {
1241
1519
  status,
@@ -1473,7 +1751,7 @@ function enterGuard(value, state) {
1473
1751
  return new Frame(SET, value, next, [...value], null);
1474
1752
  }
1475
1753
  const prototype = Object.getPrototypeOf(value);
1476
- if (prototype !== Object.prototype && prototype !== null) {
1754
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1477
1755
  state.seen.set(value, value);
1478
1756
  return value;
1479
1757
  }
@@ -1484,7 +1762,11 @@ function enterGuard(value, state) {
1484
1762
  }
1485
1763
  const next = Object.create(prototype, descriptors);
1486
1764
  state.seen.set(value, next);
1487
- return new Frame(OBJECT, value, next, Object.keys(value), descriptors);
1765
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1766
+ const descriptor = descriptors[key];
1767
+ return descriptor.enumerable || "value" in descriptor;
1768
+ });
1769
+ return new Frame(OBJECT, value, next, children, descriptors);
1488
1770
  }
1489
1771
  function keepGuarded(value, next, changed, state) {
1490
1772
  if (changed || state.cyclic.has(value)) return next;
@@ -1761,7 +2043,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1761
2043
  const method = request.method;
1762
2044
  const address = resolveAddress(url);
1763
2045
  const functionId = address && address.id;
1764
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2046
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1765
2047
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1766
2048
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1767
2049
  let serverFunction;
@@ -1792,7 +2074,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1792
2074
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1793
2075
  status: 405,
1794
2076
  headers: {
1795
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2077
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1796
2078
  }
1797
2079
  });
1798
2080
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1814,24 +2096,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1814
2096
  });
1815
2097
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1816
2098
  }
1817
- if (!(declared > 0)) {
1818
- let bounded;
1819
- try {
1820
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1821
- } catch {
1822
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1823
- status: 400
1824
- });
1825
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1826
- }
1827
- if (bounded === null) {
1828
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1829
- status: 413
1830
- });
1831
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1832
- }
1833
- request = bounded;
2099
+ let buffered;
2100
+ try {
2101
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2102
+ } catch {
2103
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2104
+ status: 400
2105
+ });
2106
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1834
2107
  }
2108
+ if (buffered === null) {
2109
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2110
+ status: 413
2111
+ });
2112
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2113
+ }
2114
+ request = withBufferedBody(request, buffered);
1835
2115
  }
1836
2116
  let event;
1837
2117
  try {
@@ -1859,7 +2139,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1859
2139
  const scope = run => provide(event, run);
1860
2140
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1861
2141
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1862
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2142
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1863
2143
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1864
2144
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1865
2145
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1874,7 +2154,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1874
2154
  }
1875
2155
  }
1876
2156
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1877
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2157
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1878
2158
  const hook = source === "true" ? flightHook : flightSources.get(source);
1879
2159
  return hook ? [[source, hook]] : [];
1880
2160
  }) : [];
@@ -1882,8 +2162,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1882
2162
  let parsed;
1883
2163
  try {
1884
2164
  parsed = await parseArguments(request, url, scripted, codec);
1885
- } catch {
1886
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2165
+ } catch (error) {
2166
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2167
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1887
2168
  status: 400
1888
2169
  });
1889
2170
  return refuseCommitted(response);
@@ -1907,7 +2188,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1907
2188
  const headers = new Headers();
1908
2189
  const dispatch = async () => {
1909
2190
  try {
1910
- let invocations = 0;
1911
2191
  const invokeOnce = async () => {
1912
2192
  INVOCATIONS.set(event, {
1913
2193
  id: functionId
@@ -1921,15 +2201,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1921
2201
  direct: false
1922
2202
  }) : run();
1923
2203
  };
1924
- let result = await provide(event, () => {
1925
- if (++invocations > 1) {
1926
- 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.");
1927
- }
1928
- return invokeOnce();
1929
- });
1930
- if (invocations !== 1) {
1931
- 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.");
1932
- }
2204
+ let result = await provideEventOnce(provide, event, invokeOnce);
1933
2205
  if (transformResult) {
1934
2206
  result = await transformResult(event, result, flightContext);
1935
2207
  }
@@ -1981,7 +2253,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1981
2253
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1982
2254
  }
1983
2255
  if (!scripted) {
1984
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2256
+ if (handleNoJS) {
2257
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2258
+ }
1985
2259
  if (result instanceof Response) return result;
1986
2260
  return encodeResult(result, headers, status, codec, request.signal, scope);
1987
2261
  }
@@ -2001,17 +2275,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2001
2275
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2002
2276
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
2003
2277
  };
2004
- if (x instanceof Response || isResponseEnvelope(x)) {
2005
- if (transformResult) {
2006
- try {
2007
- x = await transformResult(event, x, {
2008
- ...flightContext,
2009
- thrown: true
2010
- });
2011
- } catch (hookError) {
2012
- return respondThrown(hookError);
2013
- }
2278
+ if (transformResult) {
2279
+ try {
2280
+ x = await transformResult(event, x, {
2281
+ ...flightContext,
2282
+ thrown: true
2283
+ });
2284
+ } catch (hookError) {
2285
+ return respondThrown(hookError);
2014
2286
  }
2287
+ }
2288
+ if (x instanceof Response || isResponseEnvelope(x)) {
2015
2289
  let status = 200;
2016
2290
  let metadata;
2017
2291
  if (isResponseEnvelope(x)) {