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

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 (88) hide show
  1. package/dist/server.dev.js +638 -124
  2. package/dist/server.js +445 -94
  3. package/dist/{server.dev.cjs → server.observe.js} +602 -416
  4. package/dist/web.dev.js +229 -49
  5. package/dist/web.js +194 -46
  6. package/dist/{web.cjs → web.observe.js} +290 -275
  7. package/frames/dist/client.dev.js +103 -4
  8. package/frames/dist/client.js +5 -2
  9. package/frames/dist/{client.dev.cjs → client.observe.js} +139 -79
  10. package/frames/dist/server.dev.js +540 -79
  11. package/frames/dist/server.js +371 -52
  12. package/frames/dist/{server.cjs → server.observe.js} +544 -140
  13. package/frames/package.json +15 -21
  14. package/package.json +145 -294
  15. package/serialization/decode/package.json +3 -9
  16. package/serialization/package.json +3 -9
  17. package/serialization/types/serializer-decode.d.ts +49 -2
  18. package/server-functions/dist/{client.cjs → client.dev.js} +140 -107
  19. package/server-functions/dist/client.js +74 -69
  20. package/server-functions/dist/client.observe.js +1102 -0
  21. package/server-functions/dist/server.dev.js +430 -41
  22. package/server-functions/dist/server.js +367 -40
  23. package/server-functions/dist/{server.cjs → server.observe.js} +430 -85
  24. package/server-functions/package.json +15 -21
  25. package/server-functions/rich-args/package.json +3 -9
  26. package/storage/package.json +3 -9
  27. package/types/client.d.ts +39 -1
  28. package/types/diagnostics.d.ts +24 -0
  29. package/types/frames/frame-transport.d.ts +1 -1
  30. package/types/frames/serializer-decode.d.ts +49 -2
  31. package/types/index.d.ts +25 -15
  32. package/types/index.server.d.ts +35 -8
  33. package/types/jsx.d.ts +15 -4
  34. package/types/observe.d.ts +294 -0
  35. package/types/response.d.ts +18 -0
  36. package/types/serializer-decode.d.ts +49 -2
  37. package/types/server-functions/client.d.ts +32 -22
  38. package/types/server-functions/server.d.ts +55 -41
  39. package/types/server-functions/shared.d.ts +39 -9
  40. package/types/server-mock.d.ts +26 -4
  41. package/types/server-observe.d.ts +39 -0
  42. package/types/server.d.ts +105 -6
  43. package/types/trace.d.ts +79 -0
  44. package/dist/server.cjs +0 -3708
  45. package/dist/web.dev.cjs +0 -2285
  46. package/frames/dist/client.cjs +0 -2043
  47. package/frames/dist/server.dev.cjs +0 -4584
  48. package/serialization/dist/decode.cjs +0 -155
  49. package/serialization/dist/serialization.cjs +0 -275
  50. package/serialization/types-cjs/index.d.cts +0 -101
  51. package/serialization/types-cjs/package.json +0 -3
  52. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  53. package/serialization/types-cjs/serializer.d.cts +0 -101
  54. package/server-functions/dist/rich-args.cjs +0 -11
  55. package/server-functions/dist/server.dev.cjs +0 -2409
  56. package/storage/dist/storage.cjs +0 -12
  57. package/storage/types-cjs/index.d.cts +0 -28
  58. package/storage/types-cjs/package.json +0 -3
  59. package/types-cjs/client.d.cts +0 -197
  60. package/types-cjs/constants.d.cts +0 -20
  61. package/types-cjs/cookies.d.cts +0 -41
  62. package/types-cjs/frames/client.d.cts +0 -36
  63. package/types-cjs/frames/frame-client.d.cts +0 -370
  64. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  65. package/types-cjs/frames/frame-sink.d.cts +0 -92
  66. package/types-cjs/frames/frame-transport.d.cts +0 -189
  67. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  68. package/types-cjs/frames/serializer.d.cts +0 -101
  69. package/types-cjs/frames/server.d.cts +0 -52
  70. package/types-cjs/head.d.cts +0 -19
  71. package/types-cjs/index.d.cts +0 -191
  72. package/types-cjs/index.server.d.cts +0 -147
  73. package/types-cjs/jsx-properties.d.cts +0 -93
  74. package/types-cjs/jsx.d.cts +0 -4146
  75. package/types-cjs/package.json +0 -3
  76. package/types-cjs/reconcile.d.cts +0 -1
  77. package/types-cjs/render.d.cts +0 -6
  78. package/types-cjs/response.d.cts +0 -81
  79. package/types-cjs/serializer-decode.d.cts +0 -172
  80. package/types-cjs/serializer.d.cts +0 -101
  81. package/types-cjs/server-functions/client.d.cts +0 -184
  82. package/types-cjs/server-functions/flash.d.cts +0 -36
  83. package/types-cjs/server-functions/registry.d.cts +0 -100
  84. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  85. package/types-cjs/server-functions/server.d.cts +0 -546
  86. package/types-cjs/server-functions/shared.d.cts +0 -283
  87. package/types-cjs/server-mock.d.cts +0 -337
  88. package/types-cjs/server.d.cts +0 -408
@@ -1,4 +1,5 @@
1
1
  import { sharedConfig } from 'solid-js';
2
+ import { reportServerError } from 'solid-js/internal';
2
3
 
3
4
  const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
4
5
  function isHttpNavigationTarget(target) {
@@ -22,6 +23,135 @@ const REVALIDATE_HEADER = "X-Revalidate";
22
23
  const RESPONSE_HEADER_VALUE_LIMIT = 4096;
23
24
  const NULL_BODY_STATUSES = new Set([204, 205, 304]);
24
25
 
26
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
27
+ const ZERO_TRACE = "00000000000000000000000000000000";
28
+ const ZERO_SPAN = "0000000000000000";
29
+ function parseTraceparent(value) {
30
+ if (!value) return undefined;
31
+ const m = TRACEPARENT.exec(value.trim());
32
+ if (!m) return undefined;
33
+ const [, version, traceId, parentId, flags, rest] = m;
34
+ if (version === "ff") return undefined;
35
+ if (version === "00" && rest !== undefined) return undefined;
36
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
37
+ return {
38
+ traceId,
39
+ parentId,
40
+ sampled: (parseInt(flags, 16) & 1) === 1
41
+ };
42
+ }
43
+ function randomHex(bytes) {
44
+ const buffer = new Uint8Array(bytes);
45
+ crypto.getRandomValues(buffer);
46
+ let out = "";
47
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
48
+ return out;
49
+ }
50
+ function randomTraceId() {
51
+ let id = randomHex(16);
52
+ while (id === ZERO_TRACE) id = randomHex(16);
53
+ return id;
54
+ }
55
+ function randomSpanId() {
56
+ let id = randomHex(8);
57
+ while (id === ZERO_SPAN) id = randomHex(8);
58
+ return id;
59
+ }
60
+ function formatTraceparent(context) {
61
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
62
+ }
63
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
64
+ function records$1() {
65
+ const g = globalThis;
66
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
67
+ }
68
+ function traceFor(key, request) {
69
+ const store = records$1();
70
+ let record = store.get(key);
71
+ if (record) return record;
72
+ const headers = request ? request.headers : undefined;
73
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
74
+ const context = {
75
+ traceId: incoming ? incoming.traceId : randomTraceId(),
76
+ spanId: randomSpanId(),
77
+ entries: {}
78
+ };
79
+ if (incoming) {
80
+ context.parentId = incoming.parentId;
81
+ context.sampled = incoming.sampled;
82
+ }
83
+ if (headers) {
84
+ const state = headers.get("tracestate");
85
+ if (state) context.state = state;
86
+ const baggage = headers.get("baggage");
87
+ if (baggage) context.baggage = baggage;
88
+ }
89
+ let answered = false;
90
+ context.entries.traceparent = formatTraceparent(context);
91
+ record = {
92
+ context,
93
+ emit: incoming !== undefined && incoming.sampled || answered
94
+ };
95
+ store.set(key, record);
96
+ return record;
97
+ }
98
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
99
+ function splitServerTiming(value) {
100
+ const entries = [];
101
+ let start = 0;
102
+ let quoted = false;
103
+ for (let i = 0; i < value.length; i++) {
104
+ const c = value[i];
105
+ if (quoted) {
106
+ if (c === "\\") i++;else if (c === '"') quoted = false;
107
+ } else if (c === '"') quoted = true;else if (c === ",") {
108
+ entries.push(value.slice(start, i));
109
+ start = i + 1;
110
+ }
111
+ }
112
+ entries.push(value.slice(start));
113
+ return entries;
114
+ }
115
+ function metricName(entry) {
116
+ return entry.split(";")[0].trim().toLowerCase();
117
+ }
118
+ function namesOnServerTiming(headers) {
119
+ const names = new Set();
120
+ const existing = headers.get("server-timing");
121
+ if (existing) {
122
+ for (const entry of splitServerTiming(existing)) {
123
+ const name = metricName(entry);
124
+ if (name) names.add(name);
125
+ }
126
+ }
127
+ return names;
128
+ }
129
+ function quoteDesc(value) {
130
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\"]/g, m => "\\" + m);
131
+ }
132
+ function appendTraceServerTiming(headers, record) {
133
+ if (!record.emit) return;
134
+ const entries = record.context.entries;
135
+ let present;
136
+ for (const name in entries) {
137
+ if (!TOKEN.test(name)) continue;
138
+ if (!present) present = namesOnServerTiming(headers);
139
+ if (present.has(name.toLowerCase())) continue;
140
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
141
+ present.add(name.toLowerCase());
142
+ }
143
+ }
144
+ function mergeServerTiming(target, value) {
145
+ const present = namesOnServerTiming(target);
146
+ for (const entry of splitServerTiming(value)) {
147
+ const trimmed = entry.trim();
148
+ const name = metricName(trimmed);
149
+ if (!name || present.has(name)) continue;
150
+ target.append("Server-Timing", trimmed);
151
+ present.add(name);
152
+ }
153
+ }
154
+
25
155
  const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
26
156
  function getServerFunctionMetadata(fn) {
27
157
  if (typeof fn !== "function") return undefined;
@@ -148,6 +278,10 @@ function serverFunctionAddress(endpoint, id) {
148
278
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
149
279
  return `${mount}/${encodeURIComponent(id)}`;
150
280
  }
281
+ function serverFunctionDataAddress(endpoint, id) {
282
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
283
+ return `${mount}/data/${encodeURIComponent(id)}`;
284
+ }
151
285
  function parseServerFunctionAddress(pathname, endpoint) {
152
286
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
153
287
  if (!pathname.startsWith(mount)) return null;
@@ -169,6 +303,40 @@ function parseServerFunctionAddress(pathname, endpoint) {
169
303
  return null;
170
304
  }
171
305
  }
306
+ const MAX_GET_URL_LENGTH = 2000;
307
+ function urlTargetId(target, helper) {
308
+ if (typeof target === "string") return target;
309
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
310
+ throw new Error(`${helper} expects a server function reference (or its id).`);
311
+ }
312
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
313
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
314
+ if (!boundArgs.length) return address;
315
+ if (!isJSONSafe(boundArgs)) {
316
+ throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
317
+ }
318
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
319
+ }
320
+ function serverFunctionUrlFor(endpoint, fn, args) {
321
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
322
+ throw new Error("serverFunctionUrl expects a server function reference.");
323
+ }
324
+ const metadata = getServerFunctionMetadata(fn);
325
+ if (!metadata || metadata.method !== "GET") {
326
+ throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
327
+ }
328
+ const address = serverFunctionDataAddress(endpoint, fn.id);
329
+ if (!args.length) return address;
330
+ if (!isJSONSafe(args)) {
331
+ throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
332
+ }
333
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
334
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
335
+ if (length > MAX_GET_URL_LENGTH) {
336
+ throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
337
+ }
338
+ return url;
339
+ }
172
340
  const ERROR_HEADER = "X-Server-Function-Error";
173
341
  const ERROR_HEADER_MARKER = "=?1?";
174
342
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -194,7 +362,6 @@ function decodeErrorHeaderValue(value) {
194
362
  return value;
195
363
  }
196
364
  }
197
- const INSTANCE_HEADER = "X-Server-Function-Instance";
198
365
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
199
366
  const UNKNOWN_HEADER = "X-Server-Function-Unknown";
200
367
  const REDIRECT_HEADER = "X-Server-Function-Redirect";
@@ -512,16 +679,35 @@ const RequestContext = Symbol.for("solid.RequestContext");
512
679
  function getRequestEvent() {
513
680
  return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
514
681
  }
682
+ function peekRequestEvent() {
683
+ const store = globalThis[RequestContext];
684
+ return store ? store.getStore() : undefined;
685
+ }
686
+ function traceForEvent(event) {
687
+ return traceFor(event.request || event, event.request);
688
+ }
689
+ function traceForStub(stub, event) {
690
+ if (!event) {
691
+ event = peekRequestEvent();
692
+ if (!event || event.response !== stub) return undefined;
693
+ }
694
+ return traceForEvent(event);
695
+ }
515
696
  function reportLostHeaderWrite(method, name) {
516
- const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
697
+ const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
517
698
  console.error(message);
518
699
  }
519
700
  function commitResponseStub(stub, {
520
- allowLateLocation = false
701
+ allowLateLocation = false,
702
+ event
521
703
  } = {}) {
522
704
  if (!stub || stub.committed) return stub;
523
- stub.committed = true;
524
705
  const headers = stub.headers;
706
+ if (headers && typeof headers.append === "function") {
707
+ const trace = traceForStub(stub, event);
708
+ if (trace) appendTraceServerTiming(headers, trace);
709
+ }
710
+ stub.committed = true;
525
711
  if (!headers || typeof headers.set !== "function") return stub;
526
712
  for (const method of ["set", "append", "delete"]) {
527
713
  const original = headers[method].bind(headers);
@@ -552,19 +738,35 @@ function fillsStubGap(key, headers, response) {
552
738
  }
553
739
  function commitEventResponse(response, event = getRequestEvent()) {
554
740
  const stub = event && event.response;
555
- if (!stub || !stub.headers || stub.committed) return response;
741
+ if (!stub || !stub.headers || stub.committed) {
742
+ if (!event || stub) return response;
743
+ const trace = traceForEvent(event);
744
+ if (!trace.emit) return response;
745
+ const headers = copyInitHeaders(response.headers);
746
+ appendTraceServerTiming(headers, trace);
747
+ return new Response(response.body, {
748
+ status: response.status,
749
+ statusText: response.statusText,
750
+ headers
751
+ });
752
+ }
556
753
  const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
557
- commitResponseStub(stub);
754
+ commitResponseStub(stub, {
755
+ event
756
+ });
558
757
  let hasGaps = false;
559
758
  stub.headers.forEach((value, key) => {
560
759
  if (fillsStubGap(key, response.headers, response)) hasGaps = true;
561
760
  });
562
- if (!cookies.length && !hasGaps) return response;
761
+ const timing = stub.headers.get("server-timing");
762
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
763
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
563
764
  const headers = copyInitHeaders(response.headers);
564
765
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
565
766
  stub.headers.forEach((value, key) => {
566
767
  if (fillsStubGap(key, headers, response)) headers.set(key, value);
567
768
  });
769
+ if (mergesTiming) mergeServerTiming(headers, timing);
568
770
  return new Response(response.body, {
569
771
  status: response.status,
570
772
  statusText: response.statusText,
@@ -572,6 +774,70 @@ function commitEventResponse(response, event = getRequestEvent()) {
572
774
  });
573
775
  }
574
776
 
777
+ function records() {
778
+ return undefined;
779
+ }
780
+ function settledPromise(value) {
781
+ if (value instanceof Promise) return value;
782
+ try {
783
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
784
+ } catch {}
785
+ return undefined;
786
+ }
787
+ function isDeferredBody(value) {
788
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
789
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
790
+ const v = value;
791
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
792
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
793
+ }
794
+
795
+ function deliver(context, at, boundary, outcome, value) {
796
+ const record = {
797
+ id: context.id,
798
+ direct: context.direct,
799
+ at,
800
+ durationMs: performance.now() - at,
801
+ outcome
802
+ };
803
+ if (boundary !== undefined) record.boundary = boundary;
804
+ const live = {
805
+ event: context.event,
806
+ args: context.args
807
+ };
808
+ if (context.request !== undefined) live.request = context.request;
809
+ if (outcome === "ok") {
810
+ live.result = value;
811
+ if (isDeferredBody(value)) record.deferred = true;
812
+ } else live.error = value;
813
+ records().emit("invocation", record, live);
814
+ }
815
+ function observeInvocation(context, execute) {
816
+ const channel = records();
817
+ if (channel === undefined || !channel.observed("invocation")) return execute();
818
+ const at = performance.now();
819
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
820
+ let result;
821
+ try {
822
+ result = execute();
823
+ } catch (error) {
824
+ deliver(context, at, boundary, "error", error);
825
+ throw error;
826
+ }
827
+ const promised = settledPromise(result);
828
+ if (promised !== undefined) {
829
+ return promised.then(value => {
830
+ deliver(context, at, boundary, "ok", value);
831
+ return value;
832
+ }, error => {
833
+ deliver(context, at, boundary, "error", error);
834
+ throw error;
835
+ });
836
+ }
837
+ deliver(context, at, boundary, "ok", result);
838
+ return result;
839
+ }
840
+
575
841
  let configuredSecret;
576
842
  function setFlashSecret(secret) {
577
843
  configuredSecret = secret;
@@ -580,6 +846,7 @@ function resolveSecret() {
580
846
  return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
581
847
  }
582
848
  const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
849
+ const FLASH_KEY_ITERATIONS = 100_000;
583
850
  let cachedSecret;
584
851
  let cachedKey;
585
852
  function resolveFlashKey() {
@@ -587,8 +854,15 @@ function resolveFlashKey() {
587
854
  if (typeof secret !== "string" || secret.length === 0) return null;
588
855
  if (secret !== cachedSecret) {
589
856
  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"
857
+ const encoder = new TextEncoder();
858
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
859
+ name: "PBKDF2",
860
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
861
+ iterations: FLASH_KEY_ITERATIONS,
862
+ hash: "SHA-256"
863
+ }, material, {
864
+ name: "AES-GCM",
865
+ length: 256
592
866
  }, false, ["encrypt", "decrypt"]));
593
867
  }
594
868
  return cachedKey;
@@ -955,9 +1229,13 @@ function bindDeferredBody(value, scope) {
955
1229
  }
956
1230
  return value;
957
1231
  }
958
- const REGISTRATIONS = new Map();
959
- const METHODS = new Map();
960
- const REFERENCE_BINDINGS = new WeakMap();
1232
+ function processState(key, create) {
1233
+ const slot = Symbol.for(key);
1234
+ return globalThis[slot] || (globalThis[slot] = create());
1235
+ }
1236
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
1237
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1238
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
961
1239
  function declaresRead(id) {
962
1240
  const granted = METHODS.get(id);
963
1241
  return granted !== undefined && granted === REGISTRATIONS.get(id);
@@ -1061,12 +1339,17 @@ function createServerReference({
1061
1339
  const wrap = resolveWrapInvocation(config.wrapInvocation);
1062
1340
  let result = provideEventOnce(provideEvent, evt, () => {
1063
1341
  const run = () => fn.apply(thisArg, args);
1064
- return wrap ? wrap(run, {
1342
+ return observeInvocation({
1343
+ id,
1344
+ direct: true,
1345
+ event: evt,
1346
+ args
1347
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
1065
1348
  id,
1066
1349
  args,
1067
1350
  event: evt,
1068
1351
  direct: true
1069
- }) : run();
1352
+ }) : run(), id));
1070
1353
  });
1071
1354
  result = scopeDeferredResult(result, scope);
1072
1355
  const transform = config.transformDirectResult;
@@ -1235,7 +1518,13 @@ async function bufferBodyWithin(request, limit) {
1235
1518
  body.set(chunk, offset);
1236
1519
  offset += chunk.byteLength;
1237
1520
  }
1238
- return new Request(request, {
1521
+ return body;
1522
+ }
1523
+ function withBufferedBody(request, body) {
1524
+ return new Request(request.url, {
1525
+ method: request.method,
1526
+ headers: request.headers,
1527
+ signal: request.signal,
1239
1528
  body
1240
1529
  });
1241
1530
  }
@@ -1506,7 +1795,7 @@ function guardFailures(value, state) {
1506
1795
  try {
1507
1796
  top.accessorValue = descriptor.get.call(top.value);
1508
1797
  } catch (error) {
1509
- throw sanitizeServerError(error);
1798
+ throw wireServerFunctionError(error, "channel");
1510
1799
  }
1511
1800
  top.accessorRead = i;
1512
1801
  }
@@ -1616,7 +1905,7 @@ function enterGuard(value, state) {
1616
1905
  } = await guardOperation(state, () => reader.read());
1617
1906
  done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1618
1907
  } catch (error) {
1619
- controller.error(guardOperation(state, () => sanitizeServerError(error)));
1908
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
1620
1909
  }
1621
1910
  },
1622
1911
  cancel(reason) {
@@ -1630,7 +1919,7 @@ function enterGuard(value, state) {
1630
1919
  }
1631
1920
  if (typeof value.then === "function") {
1632
1921
  const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1633
- throw guardOperation(state, () => sanitizeServerError(error));
1922
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1634
1923
  });
1635
1924
  guardedPromise.catch(() => {});
1636
1925
  state.seen.set(value, guardedPromise);
@@ -1665,7 +1954,7 @@ function enterGuard(value, state) {
1665
1954
  value: guardOperation(state, () => guardFailures(step.value, state))
1666
1955
  };
1667
1956
  }, error => {
1668
- throw guardOperation(state, () => sanitizeServerError(error));
1957
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1669
1958
  });
1670
1959
  return {
1671
1960
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1814,7 +2103,7 @@ function serializeResponseStream(value, codecOptions, signal, scope) {
1814
2103
  if (onAbort) signal.removeEventListener("abort", onAbort);
1815
2104
  finishSource();
1816
2105
  try {
1817
- const delivered = sanitizeServerError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error);
2106
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
1818
2107
  controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
1819
2108
  controller.close();
1820
2109
  } catch {
@@ -1908,23 +2197,56 @@ let DEV = false === true;
1908
2197
  function setServerFunctionsDev(dev) {
1909
2198
  DEV = !!dev;
1910
2199
  }
2200
+ const REQUEST_ERROR_HOOKS = new WeakMap();
2201
+ function siteFor(handling, event, direct) {
2202
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
2203
+ const site = {
2204
+ kind: "server-function",
2205
+ handling,
2206
+ direct
2207
+ };
2208
+ if (invocation) site.functionId = invocation.id;
2209
+ if (event) site.event = event;
2210
+ return site;
2211
+ }
2212
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
2213
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
2214
+ return report.mapped ? report.value : sanitizeServerError(value);
2215
+ }
2216
+ function currentEvent() {
2217
+ const store = globalThis[RequestContext];
2218
+ return store ? store.getStore() : undefined;
2219
+ }
2220
+ function reportDirectFailure(run, id) {
2221
+ const report = error => {
2222
+ reportServerError(error, {
2223
+ kind: "server-function",
2224
+ handling: "thrown",
2225
+ functionId: id,
2226
+ direct: true
2227
+ }, null);
2228
+ throw error;
2229
+ };
2230
+ let result;
2231
+ try {
2232
+ result = run();
2233
+ } catch (error) {
2234
+ report(error);
2235
+ }
2236
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
2237
+ }
1911
2238
  function sanitizeServerError(value) {
1912
2239
  if (DEV) return value;
1913
2240
  if (isSafeError(value)) return value;
1914
2241
  return new Error(GENERIC_SERVER_ERROR_MESSAGE);
1915
2242
  }
1916
- function observeServerFunctionCalls() {
1917
- return () => {};
2243
+ function serverFunctionUrl(fn, ...args) {
2244
+ return serverFunctionUrlFor(config.endpoint, fn, args);
1918
2245
  }
1919
- function serverFunctionUrl(id, boundArgs) {
1920
- const address = serverFunctionAddress(config.endpoint, id);
1921
- if (!boundArgs || !boundArgs.length) return address;
1922
- if (!isJSONSafe(boundArgs)) {
1923
- throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
1924
- }
1925
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
2246
+ function serverFunctionActionUrl(fn, ...boundArgs) {
2247
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
1926
2248
  }
1927
- function parseServerFunctionUrl(url) {
2249
+ function parseServerFunctionActionUrl(url) {
1928
2250
  const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
1929
2251
  return parsed && parsed.id;
1930
2252
  }
@@ -2016,7 +2338,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2016
2338
  if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
2017
2339
  return finalizeTransportResponse(forbiddenResponse(), method);
2018
2340
  }
2019
- const instance = request.headers.get(INSTANCE_HEADER);
2020
2341
  if (!functionId) {
2021
2342
  const response = new Response(DEV ? "Server function not found" : null, {
2022
2343
  status: 404
@@ -2050,22 +2371,22 @@ async function handleServerFunctionRequest(request, options = {}) {
2050
2371
  });
2051
2372
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2052
2373
  }
2053
- let bounded;
2374
+ let buffered;
2054
2375
  try {
2055
- bounded = await bufferBodyWithin(request, bodySizeLimit);
2376
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2056
2377
  } catch {
2057
2378
  const response = new Response(DEV ? "Malformed server function arguments" : null, {
2058
2379
  status: 400
2059
2380
  });
2060
2381
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2061
2382
  }
2062
- if (bounded === null) {
2383
+ if (buffered === null) {
2063
2384
  const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2064
2385
  status: 413
2065
2386
  });
2066
2387
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2067
2388
  }
2068
- request = bounded;
2389
+ request = withBufferedBody(request, buffered);
2069
2390
  }
2070
2391
  let event;
2071
2392
  try {
@@ -2091,6 +2412,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2091
2412
  };
2092
2413
  const provide = options.provideEvent || provideEvent;
2093
2414
  const scope = run => provide(event, run);
2415
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
2094
2416
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
2095
2417
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
2096
2418
  const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
@@ -2133,7 +2455,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2133
2455
  const flightContext = {
2134
2456
  id: functionId,
2135
2457
  args: parsed,
2136
- instance,
2137
2458
  request,
2138
2459
  collectsFlight,
2139
2460
  codec,
@@ -2147,13 +2468,19 @@ async function handleServerFunctionRequest(request, options = {}) {
2147
2468
  id: functionId
2148
2469
  });
2149
2470
  const run = () => serverFunction(...parsed);
2150
- return wrapInvocation ? wrapInvocation(run, {
2471
+ return observeInvocation({
2472
+ id: functionId,
2473
+ direct: false,
2474
+ event,
2475
+ request,
2476
+ args: parsed
2477
+ }, () => wrapInvocation ? wrapInvocation(run, {
2151
2478
  id: functionId,
2152
2479
  args: parsed,
2153
2480
  event,
2154
2481
  request,
2155
2482
  direct: false
2156
- }) : run();
2483
+ }) : run());
2157
2484
  };
2158
2485
  let result = await provideEventOnce(provide, event, invokeOnce);
2159
2486
  if (transformResult) {
@@ -2217,7 +2544,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2217
2544
  return encodeResult(result, headers, status, codec, request.signal, scope);
2218
2545
  } catch (x) {
2219
2546
  const respondThrown = value => {
2220
- const safe = sanitizeServerError(value);
2547
+ const safe = wireServerFunctionError(value, "thrown", event);
2221
2548
  if (!scripted) {
2222
2549
  if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2223
2550
  const message = safe instanceof Error ? safe.message : String(safe);
@@ -2335,4 +2662,4 @@ function finalizeTransportResponse(response, method) {
2335
2662
  return response;
2336
2663
  }
2337
2664
 
2338
- export { ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, INSTANCE_HEADER, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, observeServerFunctionCalls, parseServerFunctionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, withMeta };
2665
+ export { ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, withMeta };