@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,6 +1,5 @@
1
- 'use strict';
2
-
3
- var solidJs = require('solid-js');
1
+ import { OBSERVE, getOwner, sharedConfig } from 'solid-js';
2
+ import { reportServerError } from 'solid-js/internal';
4
3
 
5
4
  const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
6
5
  function isHttpNavigationTarget(target) {
@@ -24,6 +23,164 @@ const REVALIDATE_HEADER = "X-Revalidate";
24
23
  const RESPONSE_HEADER_VALUE_LIMIT = 4096;
25
24
  const NULL_BODY_STATUSES = new Set([204, 205, 304]);
26
25
 
26
+ const PROVIDER = Symbol.for("solid-js/observe/server/provider");
27
+ function currentProvider() {
28
+ if (OBSERVE === undefined) return undefined;
29
+ const slot = OBSERVE.server.trace;
30
+ return slot && slot[PROVIDER];
31
+ }
32
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
33
+ const ZERO_TRACE = "00000000000000000000000000000000";
34
+ const ZERO_SPAN = "0000000000000000";
35
+ function parseTraceparent(value) {
36
+ if (!value) return undefined;
37
+ const m = TRACEPARENT.exec(value.trim());
38
+ if (!m) return undefined;
39
+ const [, version, traceId, parentId, flags, rest] = m;
40
+ if (version === "ff") return undefined;
41
+ if (version === "00" && rest !== undefined) return undefined;
42
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
43
+ return {
44
+ traceId,
45
+ parentId,
46
+ sampled: (parseInt(flags, 16) & 1) === 1
47
+ };
48
+ }
49
+ function randomHex(bytes) {
50
+ const buffer = new Uint8Array(bytes);
51
+ crypto.getRandomValues(buffer);
52
+ let out = "";
53
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
54
+ return out;
55
+ }
56
+ function randomTraceId() {
57
+ let id = randomHex(16);
58
+ while (id === ZERO_TRACE) id = randomHex(16);
59
+ return id;
60
+ }
61
+ function randomSpanId() {
62
+ let id = randomHex(8);
63
+ while (id === ZERO_SPAN) id = randomHex(8);
64
+ return id;
65
+ }
66
+ function formatTraceparent(context) {
67
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
68
+ }
69
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
70
+ function records$1() {
71
+ const g = globalThis;
72
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
73
+ }
74
+ function traceFor(key, request) {
75
+ const store = records$1();
76
+ let record = store.get(key);
77
+ if (record) return record;
78
+ const headers = request ? request.headers : undefined;
79
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
80
+ const context = {
81
+ traceId: incoming ? incoming.traceId : randomTraceId(),
82
+ spanId: randomSpanId(),
83
+ entries: {}
84
+ };
85
+ if (incoming) {
86
+ context.parentId = incoming.parentId;
87
+ context.sampled = incoming.sampled;
88
+ }
89
+ if (headers) {
90
+ const state = headers.get("tracestate");
91
+ if (state) context.state = state;
92
+ const baggage = headers.get("baggage");
93
+ if (baggage) context.baggage = baggage;
94
+ }
95
+ let answered = false;
96
+ let providedEntries;
97
+ {
98
+ const provider = currentProvider();
99
+ if (provider) {
100
+ let answer;
101
+ try {
102
+ answer = provider(request);
103
+ } catch (error) {
104
+ console.error(error);
105
+ }
106
+ if (answer !== undefined && answer !== null) {
107
+ answered = true;
108
+ if (answer.traceId !== undefined) context.traceId = answer.traceId;
109
+ if (answer.spanId !== undefined) context.spanId = answer.spanId;
110
+ if (answer.parentId !== undefined) context.parentId = answer.parentId;
111
+ if (answer.sampled !== undefined) context.sampled = answer.sampled;
112
+ if (answer.state !== undefined) context.state = answer.state;
113
+ if (answer.baggage !== undefined) context.baggage = answer.baggage;
114
+ providedEntries = answer.entries;
115
+ }
116
+ }
117
+ }
118
+ context.entries.traceparent = formatTraceparent(context);
119
+ if (providedEntries) Object.assign(context.entries, providedEntries);
120
+ record = {
121
+ context,
122
+ emit: incoming !== undefined && incoming.sampled || answered
123
+ };
124
+ store.set(key, record);
125
+ return record;
126
+ }
127
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
128
+ function splitServerTiming(value) {
129
+ const entries = [];
130
+ let start = 0;
131
+ let quoted = false;
132
+ for (let i = 0; i < value.length; i++) {
133
+ const c = value[i];
134
+ if (quoted) {
135
+ if (c === "\\") i++;else if (c === '"') quoted = false;
136
+ } else if (c === '"') quoted = true;else if (c === ",") {
137
+ entries.push(value.slice(start, i));
138
+ start = i + 1;
139
+ }
140
+ }
141
+ entries.push(value.slice(start));
142
+ return entries;
143
+ }
144
+ function metricName(entry) {
145
+ return entry.split(";")[0].trim().toLowerCase();
146
+ }
147
+ function namesOnServerTiming(headers) {
148
+ const names = new Set();
149
+ const existing = headers.get("server-timing");
150
+ if (existing) {
151
+ for (const entry of splitServerTiming(existing)) {
152
+ const name = metricName(entry);
153
+ if (name) names.add(name);
154
+ }
155
+ }
156
+ return names;
157
+ }
158
+ function quoteDesc(value) {
159
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\"]/g, m => "\\" + m);
160
+ }
161
+ function appendTraceServerTiming(headers, record) {
162
+ if (!record.emit) return;
163
+ const entries = record.context.entries;
164
+ let present;
165
+ for (const name in entries) {
166
+ if (!TOKEN.test(name)) continue;
167
+ if (!present) present = namesOnServerTiming(headers);
168
+ if (present.has(name.toLowerCase())) continue;
169
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
170
+ present.add(name.toLowerCase());
171
+ }
172
+ }
173
+ function mergeServerTiming(target, value) {
174
+ const present = namesOnServerTiming(target);
175
+ for (const entry of splitServerTiming(value)) {
176
+ const trimmed = entry.trim();
177
+ const name = metricName(trimmed);
178
+ if (!name || present.has(name)) continue;
179
+ target.append("Server-Timing", trimmed);
180
+ present.add(name);
181
+ }
182
+ }
183
+
27
184
  const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
28
185
  function getServerFunctionMetadata(fn) {
29
186
  if (typeof fn !== "function") return undefined;
@@ -150,6 +307,10 @@ function serverFunctionAddress(endpoint, id) {
150
307
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
151
308
  return `${mount}/${encodeURIComponent(id)}`;
152
309
  }
310
+ function serverFunctionDataAddress(endpoint, id) {
311
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
312
+ return `${mount}/data/${encodeURIComponent(id)}`;
313
+ }
153
314
  function parseServerFunctionAddress(pathname, endpoint) {
154
315
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
155
316
  if (!pathname.startsWith(mount)) return null;
@@ -171,6 +332,40 @@ function parseServerFunctionAddress(pathname, endpoint) {
171
332
  return null;
172
333
  }
173
334
  }
335
+ const MAX_GET_URL_LENGTH = 2000;
336
+ function urlTargetId(target, helper) {
337
+ if (typeof target === "string") return target;
338
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
339
+ throw new Error(`${helper} expects a server function reference (or its id).`);
340
+ }
341
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
342
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
343
+ if (!boundArgs.length) return address;
344
+ if (!isJSONSafe(boundArgs)) {
345
+ 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.");
346
+ }
347
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
348
+ }
349
+ function serverFunctionUrlFor(endpoint, fn, args) {
350
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
351
+ throw new Error("serverFunctionUrl expects a server function reference.");
352
+ }
353
+ const metadata = getServerFunctionMetadata(fn);
354
+ if (!metadata || metadata.method !== "GET") {
355
+ 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).');
356
+ }
357
+ const address = serverFunctionDataAddress(endpoint, fn.id);
358
+ if (!args.length) return address;
359
+ if (!isJSONSafe(args)) {
360
+ 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.");
361
+ }
362
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
363
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
364
+ if (length > MAX_GET_URL_LENGTH) {
365
+ 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.");
366
+ }
367
+ return url;
368
+ }
174
369
  const ERROR_HEADER = "X-Server-Function-Error";
175
370
  const ERROR_HEADER_MARKER = "=?1?";
176
371
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -196,7 +391,6 @@ function decodeErrorHeaderValue(value) {
196
391
  return value;
197
392
  }
198
393
  }
199
- const INSTANCE_HEADER = "X-Server-Function-Instance";
200
394
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
201
395
  const UNKNOWN_HEADER = "X-Server-Function-Unknown";
202
396
  const REDIRECT_HEADER = "X-Server-Function-Redirect";
@@ -509,21 +703,62 @@ async function decodeResponsePayload(response, codecOptions) {
509
703
  };
510
704
  }
511
705
 
706
+ function emitFinding(finding, subject = getOwner()) {
707
+ if (OBSERVE === undefined) return;
708
+ OBSERVE.diagnostics.emit(finding, subject);
709
+ }
710
+ function recordFinding(finding, subject = getOwner()) {
711
+ if (OBSERVE !== undefined) OBSERVE.diagnostics.emit(finding, subject);
712
+ }
713
+ function errorText(error) {
714
+ if (error instanceof Error) return error.message ? `${error.name}: ${error.message}` : error.name;
715
+ return String(error);
716
+ }
717
+
512
718
  typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
513
719
  const RequestContext = Symbol.for("solid.RequestContext");
514
720
  function getRequestEvent() {
515
- return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || solidJs.sharedConfig.context && solidJs.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;
721
+ 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;
722
+ }
723
+ function peekRequestEvent() {
724
+ const store = globalThis[RequestContext];
725
+ return store ? store.getStore() : undefined;
726
+ }
727
+ function traceForEvent(event) {
728
+ return traceFor(event.request || event, event.request);
729
+ }
730
+ function traceForStub(stub, event) {
731
+ if (!event) {
732
+ event = peekRequestEvent();
733
+ if (!event || event.response !== stub) return undefined;
734
+ }
735
+ return traceForEvent(event);
516
736
  }
517
737
  function reportLostHeaderWrite(method, name) {
518
- 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).";
738
+ 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).";
739
+ recordFinding({
740
+ code: "LATE_HEADER_WRITE",
741
+ kind: "head",
742
+ severity: "error",
743
+ message,
744
+ data: {
745
+ method,
746
+ name: String(name)
747
+ }
748
+ });
519
749
  console.error(message);
520
750
  }
521
751
  function commitResponseStub(stub, {
522
- allowLateLocation = false
752
+ allowLateLocation = false,
753
+ event
523
754
  } = {}) {
524
755
  if (!stub || stub.committed) return stub;
525
- stub.committed = true;
526
756
  const headers = stub.headers;
757
+ if (headers && typeof headers.append === "function") {
758
+ const trace = traceForStub(stub, event);
759
+ if (trace) appendTraceServerTiming(headers, trace);
760
+ }
761
+ stub.committed = true;
527
762
  if (!headers || typeof headers.set !== "function") return stub;
528
763
  for (const method of ["set", "append", "delete"]) {
529
764
  const original = headers[method].bind(headers);
@@ -554,19 +789,35 @@ function fillsStubGap(key, headers, response) {
554
789
  }
555
790
  function commitEventResponse(response, event = getRequestEvent()) {
556
791
  const stub = event && event.response;
557
- if (!stub || !stub.headers || stub.committed) return response;
792
+ if (!stub || !stub.headers || stub.committed) {
793
+ if (!event || stub) return response;
794
+ const trace = traceForEvent(event);
795
+ if (!trace.emit) return response;
796
+ const headers = copyInitHeaders(response.headers);
797
+ appendTraceServerTiming(headers, trace);
798
+ return new Response(response.body, {
799
+ status: response.status,
800
+ statusText: response.statusText,
801
+ headers
802
+ });
803
+ }
558
804
  const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
559
- commitResponseStub(stub);
805
+ commitResponseStub(stub, {
806
+ event
807
+ });
560
808
  let hasGaps = false;
561
809
  stub.headers.forEach((value, key) => {
562
810
  if (fillsStubGap(key, response.headers, response)) hasGaps = true;
563
811
  });
564
- if (!cookies.length && !hasGaps) return response;
812
+ const timing = stub.headers.get("server-timing");
813
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
814
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
565
815
  const headers = copyInitHeaders(response.headers);
566
816
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
567
817
  stub.headers.forEach((value, key) => {
568
818
  if (fillsStubGap(key, headers, response)) headers.set(key, value);
569
819
  });
820
+ if (mergesTiming) mergeServerTiming(headers, timing);
570
821
  return new Response(response.body, {
571
822
  status: response.status,
572
823
  statusText: response.statusText,
@@ -574,6 +825,71 @@ function commitEventResponse(response, event = getRequestEvent()) {
574
825
  });
575
826
  }
576
827
 
828
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
829
+ function records() {
830
+ return globalThis[RECORDS];
831
+ }
832
+ function settledPromise(value) {
833
+ if (value instanceof Promise) return value;
834
+ try {
835
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
836
+ } catch {}
837
+ return undefined;
838
+ }
839
+ function isDeferredBody(value) {
840
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
841
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
842
+ const v = value;
843
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
844
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
845
+ }
846
+
847
+ function deliver(context, at, boundary, outcome, value) {
848
+ const record = {
849
+ id: context.id,
850
+ direct: context.direct,
851
+ at,
852
+ durationMs: performance.now() - at,
853
+ outcome
854
+ };
855
+ if (boundary !== undefined) record.boundary = boundary;
856
+ const live = {
857
+ event: context.event,
858
+ args: context.args
859
+ };
860
+ if (context.request !== undefined) live.request = context.request;
861
+ if (outcome === "ok") {
862
+ live.result = value;
863
+ if (isDeferredBody(value)) record.deferred = true;
864
+ } else live.error = value;
865
+ records().emit("invocation", record, live);
866
+ }
867
+ function observeInvocation(context, execute) {
868
+ const channel = records();
869
+ if (channel === undefined || !channel.observed("invocation")) return execute();
870
+ const at = performance.now();
871
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
872
+ let result;
873
+ try {
874
+ result = execute();
875
+ } catch (error) {
876
+ deliver(context, at, boundary, "error", error);
877
+ throw error;
878
+ }
879
+ const promised = settledPromise(result);
880
+ if (promised !== undefined) {
881
+ return promised.then(value => {
882
+ deliver(context, at, boundary, "ok", value);
883
+ return value;
884
+ }, error => {
885
+ deliver(context, at, boundary, "error", error);
886
+ throw error;
887
+ });
888
+ }
889
+ deliver(context, at, boundary, "ok", result);
890
+ return result;
891
+ }
892
+
577
893
  let configuredSecret;
578
894
  function setFlashSecret(secret) {
579
895
  configuredSecret = secret;
@@ -582,6 +898,7 @@ function resolveSecret() {
582
898
  return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
583
899
  }
584
900
  const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
901
+ const FLASH_KEY_ITERATIONS = 100_000;
585
902
  let cachedSecret;
586
903
  let cachedKey;
587
904
  function resolveFlashKey() {
@@ -589,8 +906,15 @@ function resolveFlashKey() {
589
906
  if (typeof secret !== "string" || secret.length === 0) return null;
590
907
  if (secret !== cachedSecret) {
591
908
  cachedSecret = secret;
592
- cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
593
- name: "AES-GCM"
909
+ const encoder = new TextEncoder();
910
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
911
+ name: "PBKDF2",
912
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
913
+ iterations: FLASH_KEY_ITERATIONS,
914
+ hash: "SHA-256"
915
+ }, material, {
916
+ name: "AES-GCM",
917
+ length: 256
594
918
  }, false, ["encrypt", "decrypt"]));
595
919
  }
596
920
  return cachedKey;
@@ -957,9 +1281,13 @@ function bindDeferredBody(value, scope) {
957
1281
  }
958
1282
  return value;
959
1283
  }
960
- const REGISTRATIONS = new Map();
961
- const METHODS = new Map();
962
- const REFERENCE_BINDINGS = new WeakMap();
1284
+ function processState(key, create) {
1285
+ const slot = Symbol.for(key);
1286
+ return globalThis[slot] || (globalThis[slot] = create());
1287
+ }
1288
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
1289
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1290
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
963
1291
  function declaresRead(id) {
964
1292
  const granted = METHODS.get(id);
965
1293
  return granted !== undefined && granted === REGISTRATIONS.get(id);
@@ -1063,12 +1391,17 @@ function createServerReference({
1063
1391
  const wrap = resolveWrapInvocation(config.wrapInvocation);
1064
1392
  let result = provideEventOnce(provideEvent, evt, () => {
1065
1393
  const run = () => fn.apply(thisArg, args);
1066
- return wrap ? wrap(run, {
1394
+ return observeInvocation({
1395
+ id,
1396
+ direct: true,
1397
+ event: evt,
1398
+ args
1399
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
1067
1400
  id,
1068
1401
  args,
1069
1402
  event: evt,
1070
1403
  direct: true
1071
- }) : run();
1404
+ }) : run(), id));
1072
1405
  });
1073
1406
  result = scopeDeferredResult(result, scope);
1074
1407
  const transform = config.transformDirectResult;
@@ -1237,7 +1570,13 @@ async function bufferBodyWithin(request, limit) {
1237
1570
  body.set(chunk, offset);
1238
1571
  offset += chunk.byteLength;
1239
1572
  }
1240
- return new Request(request, {
1573
+ return body;
1574
+ }
1575
+ function withBufferedBody(request, body) {
1576
+ return new Request(request.url, {
1577
+ method: request.method,
1578
+ headers: request.headers,
1579
+ signal: request.signal,
1241
1580
  body
1242
1581
  });
1243
1582
  }
@@ -1508,7 +1847,7 @@ function guardFailures(value, state) {
1508
1847
  try {
1509
1848
  top.accessorValue = descriptor.get.call(top.value);
1510
1849
  } catch (error) {
1511
- throw sanitizeServerError(error);
1850
+ throw wireServerFunctionError(error, "channel");
1512
1851
  }
1513
1852
  top.accessorRead = i;
1514
1853
  }
@@ -1618,7 +1957,7 @@ function enterGuard(value, state) {
1618
1957
  } = await guardOperation(state, () => reader.read());
1619
1958
  done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1620
1959
  } catch (error) {
1621
- controller.error(guardOperation(state, () => sanitizeServerError(error)));
1960
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
1622
1961
  }
1623
1962
  },
1624
1963
  cancel(reason) {
@@ -1632,7 +1971,7 @@ function enterGuard(value, state) {
1632
1971
  }
1633
1972
  if (typeof value.then === "function") {
1634
1973
  const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1635
- throw guardOperation(state, () => sanitizeServerError(error));
1974
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1636
1975
  });
1637
1976
  guardedPromise.catch(() => {});
1638
1977
  state.seen.set(value, guardedPromise);
@@ -1667,7 +2006,7 @@ function enterGuard(value, state) {
1667
2006
  value: guardOperation(state, () => guardFailures(step.value, state))
1668
2007
  };
1669
2008
  }, error => {
1670
- throw guardOperation(state, () => sanitizeServerError(error));
2009
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1671
2010
  });
1672
2011
  return {
1673
2012
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1816,7 +2155,7 @@ function serializeResponseStream(value, codecOptions, signal, scope) {
1816
2155
  if (onAbort) signal.removeEventListener("abort", onAbort);
1817
2156
  finishSource();
1818
2157
  try {
1819
- const delivered = sanitizeServerError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error);
2158
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
1820
2159
  controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
1821
2160
  controller.close();
1822
2161
  } catch {
@@ -1910,23 +2249,65 @@ let DEV = false === true;
1910
2249
  function setServerFunctionsDev(dev) {
1911
2250
  DEV = !!dev;
1912
2251
  }
2252
+ const REQUEST_ERROR_HOOKS = new WeakMap();
2253
+ function siteFor(handling, event, direct) {
2254
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
2255
+ const site = {
2256
+ kind: "server-function",
2257
+ handling,
2258
+ direct
2259
+ };
2260
+ if (invocation) site.functionId = invocation.id;
2261
+ if (event) site.event = event;
2262
+ return site;
2263
+ }
2264
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
2265
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
2266
+ return report.mapped ? report.value : sanitizeServerError(value);
2267
+ }
2268
+ function currentEvent() {
2269
+ const store = globalThis[RequestContext];
2270
+ return store ? store.getStore() : undefined;
2271
+ }
2272
+ function reportDirectFailure(run, id) {
2273
+ const report = error => {
2274
+ reportServerError(error, {
2275
+ kind: "server-function",
2276
+ handling: "thrown",
2277
+ functionId: id,
2278
+ direct: true
2279
+ }, null);
2280
+ throw error;
2281
+ };
2282
+ let result;
2283
+ try {
2284
+ result = run();
2285
+ } catch (error) {
2286
+ report(error);
2287
+ }
2288
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
2289
+ }
1913
2290
  function sanitizeServerError(value) {
1914
2291
  if (DEV) return value;
1915
2292
  if (isSafeError(value)) return value;
2293
+ emitFinding({
2294
+ code: "SERVER_FN_ERROR_SANITIZED",
2295
+ kind: "ssr",
2296
+ severity: "error",
2297
+ message: `[SERVER_FN_ERROR_SANITIZED] Server function error replaced with a generic Error before serialization: ${errorText(value)}`,
2298
+ data: {
2299
+ error: value
2300
+ }
2301
+ }, null);
1916
2302
  return new Error(GENERIC_SERVER_ERROR_MESSAGE);
1917
2303
  }
1918
- function observeServerFunctionCalls() {
1919
- return () => {};
2304
+ function serverFunctionUrl(fn, ...args) {
2305
+ return serverFunctionUrlFor(config.endpoint, fn, args);
1920
2306
  }
1921
- function serverFunctionUrl(id, boundArgs) {
1922
- const address = serverFunctionAddress(config.endpoint, id);
1923
- if (!boundArgs || !boundArgs.length) return address;
1924
- if (!isJSONSafe(boundArgs)) {
1925
- 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.");
1926
- }
1927
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
2307
+ function serverFunctionActionUrl(fn, ...boundArgs) {
2308
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
1928
2309
  }
1929
- function parseServerFunctionUrl(url) {
2310
+ function parseServerFunctionActionUrl(url) {
1930
2311
  const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
1931
2312
  return parsed && parsed.id;
1932
2313
  }
@@ -2018,7 +2399,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2018
2399
  if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
2019
2400
  return finalizeTransportResponse(forbiddenResponse(), method);
2020
2401
  }
2021
- const instance = request.headers.get(INSTANCE_HEADER);
2022
2402
  if (!functionId) {
2023
2403
  const response = new Response(DEV ? "Server function not found" : null, {
2024
2404
  status: 404
@@ -2052,22 +2432,22 @@ async function handleServerFunctionRequest(request, options = {}) {
2052
2432
  });
2053
2433
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2054
2434
  }
2055
- let bounded;
2435
+ let buffered;
2056
2436
  try {
2057
- bounded = await bufferBodyWithin(request, bodySizeLimit);
2437
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2058
2438
  } catch {
2059
2439
  const response = new Response(DEV ? "Malformed server function arguments" : null, {
2060
2440
  status: 400
2061
2441
  });
2062
2442
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2063
2443
  }
2064
- if (bounded === null) {
2444
+ if (buffered === null) {
2065
2445
  const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2066
2446
  status: 413
2067
2447
  });
2068
2448
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2069
2449
  }
2070
- request = bounded;
2450
+ request = withBufferedBody(request, buffered);
2071
2451
  }
2072
2452
  let event;
2073
2453
  try {
@@ -2093,6 +2473,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2093
2473
  };
2094
2474
  const provide = options.provideEvent || provideEvent;
2095
2475
  const scope = run => provide(event, run);
2476
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
2096
2477
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
2097
2478
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
2098
2479
  const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
@@ -2135,7 +2516,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2135
2516
  const flightContext = {
2136
2517
  id: functionId,
2137
2518
  args: parsed,
2138
- instance,
2139
2519
  request,
2140
2520
  collectsFlight,
2141
2521
  codec,
@@ -2149,13 +2529,19 @@ async function handleServerFunctionRequest(request, options = {}) {
2149
2529
  id: functionId
2150
2530
  });
2151
2531
  const run = () => serverFunction(...parsed);
2152
- return wrapInvocation ? wrapInvocation(run, {
2532
+ return observeInvocation({
2533
+ id: functionId,
2534
+ direct: false,
2535
+ event,
2536
+ request,
2537
+ args: parsed
2538
+ }, () => wrapInvocation ? wrapInvocation(run, {
2153
2539
  id: functionId,
2154
2540
  args: parsed,
2155
2541
  event,
2156
2542
  request,
2157
2543
  direct: false
2158
- }) : run();
2544
+ }) : run());
2159
2545
  };
2160
2546
  let result = await provideEventOnce(provide, event, invokeOnce);
2161
2547
  if (transformResult) {
@@ -2219,7 +2605,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2219
2605
  return encodeResult(result, headers, status, codec, request.signal, scope);
2220
2606
  } catch (x) {
2221
2607
  const respondThrown = value => {
2222
- const safe = sanitizeServerError(value);
2608
+ const safe = wireServerFunctionError(value, "thrown", event);
2223
2609
  if (!scripted) {
2224
2610
  if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2225
2611
  const message = safe instanceof Error ? safe.message : String(safe);
@@ -2337,45 +2723,4 @@ function finalizeTransportResponse(response, method) {
2337
2723
  return response;
2338
2724
  }
2339
2725
 
2340
- exports.ERROR_HEADER = ERROR_HEADER;
2341
- exports.FLASH_COOKIE = FLASH_COOKIE;
2342
- exports.GENERIC_SERVER_ERROR_MESSAGE = GENERIC_SERVER_ERROR_MESSAGE;
2343
- exports.GET = GET;
2344
- exports.INSTANCE_HEADER = INSTANCE_HEADER;
2345
- exports.REDIRECT_HEADER = REDIRECT_HEADER;
2346
- exports.SERVER_FUNCTION_INVOKE = SERVER_FUNCTION_INVOKE;
2347
- exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
2348
- exports.UNKNOWN_HEADER = UNKNOWN_HEADER;
2349
- exports.clearFlashCookie = clearFlashCookie;
2350
- exports.configureServerFunctionsServer = configureServerFunctionsServer;
2351
- exports.createNoJSHandler = createNoJSHandler;
2352
- exports.createServerReference = createServerReference;
2353
- exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
2354
- exports.decodeFlashCookie = decodeFlashCookie;
2355
- exports.decodeRedirectHeaderValue = decodeRedirectHeaderValue;
2356
- exports.decodeResponse = decodeResponse;
2357
- exports.decodeResponsePayload = decodeResponsePayload;
2358
- exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
2359
- exports.encodeFlashCookie = encodeFlashCookie;
2360
- exports.foldSetCookies = foldSetCookies;
2361
- exports.getEventServerFunctionInvocation = getEventServerFunctionInvocation;
2362
- exports.getServerFunction = getServerFunction;
2363
- exports.getServerFunctionInvocation = getServerFunctionInvocation;
2364
- exports.getServerFunctionMetadata = getServerFunctionMetadata;
2365
- exports.guardFailures = guardFailures;
2366
- exports.handleServerFunctionRequest = handleServerFunctionRequest;
2367
- exports.hasFlashCookie = hasFlashCookie;
2368
- exports.invoke = invoke;
2369
- exports.isServerFunction = isServerFunction;
2370
- exports.live = live;
2371
- exports.observeServerFunctionCalls = observeServerFunctionCalls;
2372
- exports.parseServerFunctionUrl = parseServerFunctionUrl;
2373
- exports.registerFlightDataSource = registerFlightDataSource;
2374
- exports.registerServerFunction = registerServerFunction;
2375
- exports.registerServerReference = registerServerReference;
2376
- exports.sanitizeServerError = sanitizeServerError;
2377
- exports.serializeResponseStream = serializeResponseStream;
2378
- exports.serverFunctionUrl = serverFunctionUrl;
2379
- exports.setServerFunctionsDev = setServerFunctionsDev;
2380
- exports.subscribeFlightData = subscribeFlightData;
2381
- exports.withMeta = withMeta;
2726
+ 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 };