@solidjs/web 2.0.0-rc.11 → 2.0.0-rc.14

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 (60) hide show
  1. package/dist/server.dev.js +705 -151
  2. package/dist/server.js +604 -123
  3. package/dist/server.observe.js +617 -124
  4. package/dist/web.dev.js +102 -41
  5. package/dist/web.js +75 -37
  6. package/dist/web.observe.js +75 -39
  7. package/frames/dist/assets.js +92 -0
  8. package/frames/dist/bind.dev.js +326 -0
  9. package/frames/dist/bind.js +295 -0
  10. package/frames/dist/client.dev.js +693 -919
  11. package/frames/dist/client.js +636 -917
  12. package/frames/dist/client.observe.js +637 -917
  13. package/frames/dist/regions.js +130 -0
  14. package/frames/dist/server.dev.js +607 -212
  15. package/frames/dist/server.js +554 -212
  16. package/frames/dist/server.observe.js +554 -212
  17. package/frames/dist/trace.js +42 -0
  18. package/frames/dist/wire.js +133 -0
  19. package/package.json +30 -3
  20. package/performance-tracks/dist/performance-tracks.dev.js +2 -1
  21. package/performance-tracks/dist/performance-tracks.observe.js +2 -1
  22. package/performance-tracks/types/index.d.ts +8 -6
  23. package/serialization/dist/decode.js +37 -8
  24. package/serialization/dist/serialization.js +39 -10
  25. package/serialization/types/serializer-decode.d.ts +24 -2
  26. package/server-functions/dist/client.dev.js +178 -72
  27. package/server-functions/dist/client.js +99 -61
  28. package/server-functions/dist/client.observe.js +178 -72
  29. package/server-functions/dist/server.dev.js +117 -56
  30. package/server-functions/dist/server.js +117 -56
  31. package/server-functions/dist/server.observe.js +117 -56
  32. package/skills/server-components/SKILL.md +228 -0
  33. package/types/client.d.ts +37 -2
  34. package/types/constants.d.ts +2 -1
  35. package/types/diagnostics.d.ts +8 -0
  36. package/types/frames/assets-tier.d.ts +78 -0
  37. package/types/frames/bind-tier.d.ts +60 -0
  38. package/types/frames/client.d.ts +37 -3
  39. package/types/frames/frame-client.d.ts +249 -96
  40. package/types/frames/frame-container-plugin.d.ts +2 -10
  41. package/types/frames/frame-sink.d.ts +33 -0
  42. package/types/frames/frame-transport.d.ts +66 -18
  43. package/types/frames/regions-tier.d.ts +45 -0
  44. package/types/frames/serializer-decode.d.ts +24 -2
  45. package/types/frames/server.d.ts +53 -1
  46. package/types/frames/trace-tier.d.ts +2 -0
  47. package/types/frames/tree-rewrite.d.ts +39 -0
  48. package/types/frames/wire-tier.d.ts +116 -0
  49. package/types/index.d.ts +38 -0
  50. package/types/index.server.d.ts +10 -1
  51. package/types/jsx.d.ts +11 -1
  52. package/types/observe.d.ts +182 -12
  53. package/types/request-error-hook.d.ts +5 -0
  54. package/types/serializer-decode.d.ts +24 -2
  55. package/types/server-functions/client.d.ts +26 -0
  56. package/types/server-functions/registry.d.ts +4 -1
  57. package/types/server-functions/shared.d.ts +12 -8
  58. package/types/server-mock.d.ts +13 -1
  59. package/types/server-observe.d.ts +8 -0
  60. package/types/server.d.ts +125 -12
@@ -1,5 +1,5 @@
1
- import { OBSERVE, sharedConfig, getOwner } from 'solid-js';
2
- import { reportServerError } from 'solid-js/internal';
1
+ import { OBSERVE, getOwner } from 'solid-js';
2
+ import { sharedConfig, reportServerError } from 'solid-js/internal';
3
3
 
4
4
  const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
5
5
  function isHttpNavigationTarget(target) {
@@ -23,6 +23,15 @@ const REVALIDATE_HEADER = "X-Revalidate";
23
23
  const RESPONSE_HEADER_VALUE_LIMIT = 4096;
24
24
  const NULL_BODY_STATUSES = new Set([204, 205, 304]);
25
25
 
26
+ const REQUEST_ERROR_HOOK = Symbol.for("solid-js/server/request-error-hook");
27
+ function hooks() {
28
+ const g = globalThis;
29
+ return g[REQUEST_ERROR_HOOK] || (g[REQUEST_ERROR_HOOK] = new WeakMap());
30
+ }
31
+ function requestErrorHook(event) {
32
+ return event === undefined ? undefined : hooks().get(event);
33
+ }
34
+
26
35
  const PROVIDER = Symbol.for("solid-js/observe/server/provider");
27
36
  function currentProvider() {
28
37
  if (OBSERVE === undefined) return undefined;
@@ -363,7 +372,7 @@ function serializeCookie(name, value, options = {}) {
363
372
  return cookie;
364
373
  }
365
374
  const FLASH_COOKIE = "flash";
366
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
375
+ const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
367
376
  function hasFlashCookie(cookieHeader) {
368
377
  return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
369
378
  }
@@ -681,7 +690,7 @@ async function extractBody(source, codecOptions, wire) {
681
690
  const format = source.headers.get(BODY_FORMAT_HEADER);
682
691
  switch (true) {
683
692
  case format === BodyFormat.Serialized:
684
- return await deserializeStream(source, codecOptions);
693
+ return await deserializeStream(source, codecOptions, wire);
685
694
  case format === BodyFormat.Json:
686
695
  return JSON.parse(await source.text());
687
696
  case format === BodyFormat.String:
@@ -707,26 +716,42 @@ async function extractBody(source, codecOptions, wire) {
707
716
  return undefined;
708
717
  }
709
718
  function createChunk(data) {
710
- const encoder = new TextEncoder();
711
- const encodeData = encoder.encode(data);
719
+ const encodeData = CHUNK_ENCODER.encode(data);
712
720
  const bytes = encodeData.length;
721
+ if (bytes > MAX_CHUNK_BYTES) {
722
+ throw new RangeError("Server function chunk is too large to frame.");
723
+ }
713
724
  const chunk = new Uint8Array(12 + bytes);
714
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
725
+ chunk.set(CHUNK_ENCODER.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
715
726
  chunk.set(encodeData, 12);
716
727
  return chunk;
717
728
  }
729
+ const CHUNK_ENCODER = /* @__PURE__ */new TextEncoder();
730
+ const CHUNK_DECODER = /* @__PURE__ */new TextDecoder("utf-8", {
731
+ fatal: true
732
+ });
733
+ const MAX_CHUNK_BYTES = 0xffffffff;
734
+ const RETAINED_STORE_BYTES = 64 * 1024;
735
+ const DONE = {
736
+ done: true,
737
+ value: undefined
738
+ };
739
+ function malformedStream() {
740
+ return new Error("Malformed server function stream.");
741
+ }
718
742
  class ChunkReader {
719
743
  constructor(stream) {
720
744
  this.reader = stream.getReader();
721
745
  this.store = new Uint8Array(0);
722
746
  this.buffer = this.store;
723
747
  this.done = false;
748
+ this.cancelled = false;
724
749
  }
725
750
  async readChunk() {
726
751
  const chunk = await this.reader.read();
727
752
  if (chunk.done) {
728
753
  this.done = true;
729
- return;
754
+ return this.cancelled;
730
755
  }
731
756
  const incoming = chunk.value;
732
757
  const store = this.store;
@@ -747,55 +772,66 @@ class ChunkReader {
747
772
  this.store = grown;
748
773
  this.buffer = grown.subarray(0, needed);
749
774
  }
775
+ return this.cancelled;
750
776
  }
751
777
  async next() {
778
+ if (this.cancelled) return DONE;
752
779
  while (this.buffer.length < 12) {
753
780
  if (this.done) {
754
- if (this.buffer.length === 0) return {
755
- done: true,
756
- value: undefined
757
- };
758
- throw new Error("Malformed server function stream.");
781
+ if (this.buffer.length === 0) return DONE;
782
+ throw malformedStream();
759
783
  }
760
- await this.readChunk();
761
- }
762
- const decoder = new TextDecoder();
763
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
764
- if (Number.isNaN(bytes)) {
765
- throw new Error("Malformed server function stream.");
784
+ if (await this.readChunk()) return DONE;
766
785
  }
786
+ const header = String.fromCharCode(...this.buffer.subarray(0, 12));
787
+ if (!/^;0x[\dA-Fa-f]{8};$/.test(header)) throw malformedStream();
788
+ const bytes = parseInt(header.slice(3, 11), 16);
767
789
  while (bytes > this.buffer.length - 12) {
768
790
  if (this.done) {
769
- throw new Error("Malformed server function stream.");
791
+ throw malformedStream();
770
792
  }
771
- await this.readChunk();
793
+ if (await this.readChunk()) return DONE;
794
+ }
795
+ let partial;
796
+ try {
797
+ partial = CHUNK_DECODER.decode(this.buffer.subarray(12, 12 + bytes));
798
+ } catch {
799
+ throw malformedStream();
772
800
  }
773
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
774
801
  this.buffer = this.buffer.subarray(12 + bytes);
802
+ if (this.store.length > RETAINED_STORE_BYTES && this.buffer.length <= RETAINED_STORE_BYTES) {
803
+ this.store = this.buffer = this.buffer.slice();
804
+ }
775
805
  return {
776
806
  done: false,
777
807
  value: partial
778
808
  };
779
809
  }
780
810
  async drain(interpret) {
781
- while (true) {
782
- const result = await this.next();
783
- if (result.done) {
784
- break;
811
+ try {
812
+ while (true) {
813
+ const result = await this.next();
814
+ if (result.done) {
815
+ break;
816
+ }
817
+ interpret(result.value);
785
818
  }
786
- interpret(result.value);
819
+ } catch (error) {
820
+ this.cancel(error).catch(() => {});
821
+ throw error;
787
822
  }
788
823
  }
789
824
  cancel(reason) {
825
+ this.cancelled = true;
790
826
  return this.reader.cancel(reason);
791
827
  }
792
828
  }
793
829
  function createEventChunk(data, id) {
794
830
  let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
795
831
  for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
796
- return new TextEncoder().encode(event + "\n");
832
+ return CHUNK_ENCODER.encode(event + "\n");
797
833
  }
798
- const EVENT_STREAM_HEARTBEAT = new TextEncoder().encode(":\n\n");
834
+ const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
799
835
  function positionDigest(value) {
800
836
  if (value === undefined || !isJSONSafe(value)) return undefined;
801
837
  const text = JSON.stringify(value);
@@ -859,29 +895,36 @@ async function deserializeStream(source, codecOptions, wire) {
859
895
  throw new Error("missing body");
860
896
  }
861
897
  const reader = new ChunkReader(source.body);
862
- const result = await reader.next();
863
- if (!result.done) {
864
- if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
865
- throw errorFromTrailer(result.value);
866
- }
867
- const {
868
- createJSONDeserializer
869
- } = await import('@solidjs/web/serialization/decode');
870
- const deserializeChunk = createJSONDeserializer(codecOptions);
871
- function interpretChunk(chunk) {
872
- if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
873
- throw errorFromTrailer(chunk);
898
+ try {
899
+ const result = await reader.next();
900
+ if (!result.done) {
901
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
902
+ throw errorFromTrailer(result.value);
874
903
  }
875
- return deserializeChunk(JSON.parse(chunk));
904
+ const {
905
+ createJSONDeserializer
906
+ } = await import('@solidjs/web/serialization/decode');
907
+ const deserializeChunk = createJSONDeserializer(codecOptions);
908
+ function interpretChunk(chunk) {
909
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
910
+ throw errorFromTrailer(chunk);
911
+ }
912
+ return deserializeChunk(JSON.parse(chunk));
913
+ }
914
+ const connection = wire && wire.connection;
915
+ let endConnection;
916
+ if (connection) ;
917
+ const end = error => {
918
+ const sweep = () => deserializeChunk.abort(error);
919
+ if (connection) ; else sweep();
920
+ };
921
+ reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
922
+ return interpretChunk(result.value);
876
923
  }
877
- const end = error => {
878
- const sweep = () => deserializeChunk.abort(error);
879
- sweep();
880
- };
881
- reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
882
- return interpretChunk(result.value);
924
+ } catch (error) {
925
+ reader.cancel(error).catch(() => {});
926
+ throw error;
883
927
  }
884
- return undefined;
885
928
  }
886
929
  async function deserializeString(text, codecOptions) {
887
930
  return await deserializeStream(new Response(text), codecOptions);
@@ -918,7 +961,21 @@ function errorText(error) {
918
961
  typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
919
962
  const RequestContext = Symbol.for("solid.RequestContext");
920
963
  function getRequestEvent() {
921
- 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;
964
+ const store = globalThis[RequestContext];
965
+ if (!store) return undefined;
966
+ const event = store.getStore();
967
+ if (event) return event;
968
+ const ctx = renderContextOf(getOwner());
969
+ return ctx && ctx.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.");
970
+ }
971
+ const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
972
+ function renderContextOf(owner) {
973
+ const roots = globalThis[RENDER_ROOTS];
974
+ if (!roots) return undefined;
975
+ for (; owner; owner = owner._parent) {
976
+ const context = roots.get(owner);
977
+ if (context) return context;
978
+ }
922
979
  }
923
980
  function peekRequestEvent() {
924
981
  const store = globalThis[RequestContext];
@@ -977,10 +1034,13 @@ function copyInitHeaders(init) {
977
1034
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
978
1035
  return headers;
979
1036
  }
980
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
981
- ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
1037
+ let stubGapFillExcluded;
1038
+ function isStubGapFillExcluded(key) {
1039
+ return (stubGapFillExcluded ||= new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
1040
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()))).has(key);
1041
+ }
982
1042
  function fillsStubGap(key, headers, response) {
983
- if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
1043
+ if (key === "set-cookie" || isStubGapFillExcluded(key)) return false;
984
1044
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
985
1045
  return !headers.has(key);
986
1046
  }
@@ -1534,6 +1594,7 @@ function createServerReference({
1534
1594
  evt.serverOnly = true;
1535
1595
  const scope = run => provideEvent(evt, run);
1536
1596
  const wrap = resolveWrapInvocation(config.wrapInvocation);
1597
+ const hook = requestErrorHook(ogEvt);
1537
1598
  let result = provideEventOnce(provideEvent, evt, () => {
1538
1599
  const run = () => fn.apply(thisArg, args);
1539
1600
  return observeInvocation({
@@ -1546,7 +1607,7 @@ function createServerReference({
1546
1607
  args,
1547
1608
  event: evt,
1548
1609
  direct: true
1549
- }) : run(), id));
1610
+ }) : run(), id, hook));
1550
1611
  });
1551
1612
  result = scopeDeferredResult(result, scope);
1552
1613
  const transform = config.transformDirectResult;
@@ -2516,14 +2577,14 @@ function currentEvent() {
2516
2577
  const store = globalThis[RequestContext];
2517
2578
  return store ? store.getStore() : undefined;
2518
2579
  }
2519
- function reportDirectFailure(run, id) {
2580
+ function reportDirectFailure(run, id, hook) {
2520
2581
  const report = error => {
2521
2582
  reportServerError(error, {
2522
2583
  kind: "server-function",
2523
2584
  handling: "thrown",
2524
2585
  functionId: id,
2525
2586
  direct: true
2526
- }, null);
2587
+ }, null, hook);
2527
2588
  throw error;
2528
2589
  };
2529
2590
  let result;
@@ -0,0 +1,228 @@
1
+ # Writing Solid server components with slots
2
+
3
+ A Solid server component is a `"use server"` function that returns a
4
+ template; the browser receives its markup and never its code. Anything the
5
+ client contributes goes through a **slot** on the component's props. This
6
+ guide is the set of rules an author — a person or an agent — needs to write
7
+ one correctly the first time. The design record is
8
+ `documentation/server-components/server-components-principles.md` §9.2.3;
9
+ this file is the operative subset.
10
+
11
+ ## Where things go
12
+
13
+ > **An element lives where the data that creates it lives.**
14
+
15
+ - Exists because of **server data** (a todo row, a nav link, a search
16
+ form the server renders)? It is **server markup**. Client behavior or a
17
+ client-driven value on it is a **binding slot** — bind, never wrap.
18
+ Do not wrap a server-rendered element in a client component to give it a
19
+ handler or a class.
20
+ - Exists because of **client state alone** (an optimistic add, a modal, a
21
+ drag ghost, an editor open over a field)? It is a **client component**
22
+ placed through a **template slot**.
23
+
24
+ When the client confirms an optimistic entity and the server renders it, the
25
+ row _becomes_ server markup; `$key` on the element reconciles the two.
26
+
27
+ ## The two kinds of slot
28
+
29
+ ```tsx
30
+ import type { BindingSlot, Slot } from "@solidjs/web/frames";
31
+
32
+ interface TodosProps {
33
+ pending: Slot; // template: the client returns JSX
34
+ row: BindingSlot<{ id: string; completed: boolean }, RowBehavior>; // bindings: the client returns an object
35
+ filters: BindingSlot<{}, FilterBehavior>; // no args: called bare
36
+ }
37
+ ```
38
+
39
+ A **template slot** is placed as an element: `<props.pending />`. The client
40
+ owns those nodes.
41
+
42
+ A **binding slot** is _called_ once per data context and its properties
43
+ are _bound_ at positions of the server's own template:
44
+
45
+ ```tsx
46
+ export async function todoList() {
47
+ "use server";
48
+ const todos = await db.list();
49
+ return (props: TodosProps) => {
50
+ const filters = props.filters();
51
+ return (
52
+ <>
53
+ <ul>
54
+ {todos.map(t => (
55
+ <TodoRow
56
+ id={t.id}
57
+ title={t.title}
58
+ row={props.row({ id: t.id, completed: t.completed })}
59
+ />
60
+ ))}
61
+ <props.pending />
62
+ </ul>
63
+ <a href="#/" class={{ selected: filters.all }}>
64
+ All
65
+ </a>
66
+ </>
67
+ );
68
+ };
69
+ }
70
+ ```
71
+
72
+ The client passes the fill — a function of the args that returns the object:
73
+
74
+ ```tsx
75
+ <Todos row={rowFor} filters={() => ({ get all() { return filter() === "all"; }, … })} pending={() => <For each={adds}>{…}</For>} />
76
+ ```
77
+
78
+ The fill must return a plain object. An array, a DOM node, a function or
79
+ an async value is a type error on both sides (`BindingSlot`'s return is
80
+ `SlotOutput<J>`, a branded `SlotError` naming the reason) and a
81
+ `fill-shape` finding at runtime.
82
+
83
+ ## The one rule for binding slots
84
+
85
+ > **A slot property is a JSX attribute value or a text child, whole, and nothing else.**
86
+
87
+ Legal positions: an attribute (`hidden={row.removed}`, `checked={row.done}`,
88
+ `title={row.error}`), a class name inside object form
89
+ (`class={{ completed: row.done }}`), the whole `class`/`style`
90
+ (`class={row.rowClass}`), a style property (`style={{ opacity: row.fade }}`),
91
+ an event (`onInput={row.onToggle}`), a ref (`ref={row.ref}`) — on an element
92
+ with a spread too (`<button {...rest} onClick={row.go} />` — the last
93
+ source that has the key wins, `undefined` included, as the client's
94
+ spread reads it) — and a text child (`<strong>{list.remaining}</strong> items
95
+ left`): a string or number renders, nullish and booleans render empty, and
96
+ the client owns the text between a `<!--_s:t=…-->` marker pair. Never the
97
+ content of `<textarea>`, `<title>`, `<style>` or `<script>`, where the
98
+ markers would be literal text — bind `value=` or a style property there.
99
+ Not a `prop:*` property, not inside another slot call's args (nested in
100
+ plain objects and arrays included). Reserved keys the fill must not use:
101
+ keys beginning with `$` or a digit, `length`, `slice`, `t`/`h`/`p`, `then`,
102
+ `constructor`/`toString`/`valueOf`/`toJSON`; anything else (`filter`, `map`
103
+ included) is a plain property.
104
+
105
+ The server **does not have the value** — on the stream face a property read
106
+ is a stand-in with no value, on the document face only the initial one — so
107
+ nothing can be computed from it on the server. Every one of these is wrong:
108
+
109
+ | Wrong | Why | Write instead |
110
+ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
111
+ | ``class={`todo ${row.done}`}`` | stringified: not the whole value | `class={{ todo: true, completed: row.done }}` or return `rowClass` from the fill |
112
+ | `row.count > 3 ? "a" : "b"` | comparison on a stand-in | decide in the fill; return the decided value |
113
+ | `if (row.error) …`, `row.error && <button/>`, `<Show when={row.done}>` | truthiness: a stand-in is an object and **always truthy** — the branch always renders | presence → `hidden={…}` or a class; a node that exists because of client state → a template slot |
114
+ | `<strong>{row.label}</strong>` where the fill returns JSX for `label` | a text position renders a string or number | a template slot for markup |
115
+ | `<textarea>{row.draft}</textarea>` | raw-text content: the markers land in the text | `value={row.draft}` |
116
+ | `format(row.title)` (a server helper) | the helper receives a stand-in | do the formatting in the fill |
117
+ | `<li {...row}>` | spread: the template must show what the client owns | name each position |
118
+ | `onClick={() => …}` on a server element | a server function can never run in the browser | bind a slot property or a form `action` |
119
+ | `onKeyDown={[row.key, 1]}` | a tuple: a marker names keys, never data | return `onKeyDown: [handler, data]` from the fill; bind `onKeyDown={row.onKeyDown}` |
120
+
121
+ Every case except truthiness and raw-text content is a dev finding
122
+ (`BINDING_SLOT_POSITION`) and renders **nothing on either face**, so it
123
+ shows on the first render. Truthiness has no runtime hook: if a retry button
124
+ appears on every row, this is why. Raw-text content has none either; in
125
+ `<textarea>` and `<title>` the markers show as text.
126
+
127
+ ## Writing the fill
128
+
129
+ - **The fill runs once per occurrence, as a component body does.** It runs
130
+ untracked, under the occurrence's owner, with live args. State it
131
+ creates (a signal, a memo, an `onCleanup`) lives as long as the
132
+ occurrence. A top-level read is read once, and `STRICT_READ_UNTRACKED`
133
+ names it.
134
+ - **Values as getters, handlers as plain closures.** A getter is the
135
+ reactive form, as on a component's props object; a plain value never
136
+ updates:
137
+
138
+ ```tsx
139
+ const rowFor = (p: { id: string; completed: boolean }): RowBehavior => ({
140
+ get rowClass() {
141
+ return { todo: true, completed: done(p.id, p.completed), pending: !!intent.byId[p.id] };
142
+ },
143
+ get done() {
144
+ return done(p.id, p.completed);
145
+ },
146
+ get removed() {
147
+ return removed(p.id);
148
+ },
149
+ onToggle: e => actions.toggle(p.id, e.currentTarget.checked),
150
+ onRemove: () => actions.remove(p.id)
151
+ });
152
+ ```
153
+
154
+ Each getter is read where its position binds, so a change moves the
155
+ positions that read it. The same object serves a client
156
+ `<TodoRow row={rowFor(todo)} />`, whose body reads it the same way. A
157
+ plain value is right only for what never changes (a constant handler,
158
+ a fixed class).
159
+
160
+ - **Name it like a props interface**, because it is one (a shared component
161
+ takes it as a prop). Handlers are `on` + intent — `onToggle`, `onRemove`,
162
+ `onCopy`, `onClearCompleted`; the position names the DOM event, the key
163
+ names the meaning, as a component's `onSelect` does. Values are nouns or
164
+ adjectives (`done`, `rowClass`, `error`, `busy`); a ref is `ref`. The
165
+ runtime reads nothing into the prefix — the position decides what a
166
+ property is — but a reader can tell a handler from a value without
167
+ opening the type.
168
+ - Handlers and refs are read once, when an element binds, and bind as in
169
+ client JSX: delegated events delegate, a `[handler, data]` tuple returned
170
+ from the fill binds as a tuple, a ref fires once per element. A handler
171
+ behind a getter is read once, as `onClick={cond() ? a : b}` is.
172
+ - **`$key` is optional.** A call repeated within a render (a component
173
+ prop re-evaluates it per position) is one occurrence either way. Add
174
+ `$key: t.id` when the fill holds its own state (an edit draft, a signal
175
+ created inside) that must follow the entity across refetches and
176
+ reorders. Values never depend on it.
177
+ - Reserved keys in the returned object: anything beginning with `$`, the
178
+ node keys `t` `h` `p` `then`, and `Object`/`Array` prototype member names
179
+ (`length`, `map`, …).
180
+
181
+ ## Shared components
182
+
183
+ One component can render on both sides: on the server its `row` prop is
184
+ the binding slot's return, on the client it is the fill's result. It
185
+ cannot tell and need not. Put `$key={props.id}` on the element it renders
186
+ (morph identity) — the slot call's own `$key` is a different key for a
187
+ different job. Do not read `document`/`window` during render; that is the
188
+ ordinary isomorphic rule.
189
+
190
+ ## Compiling
191
+
192
+ Server components need the SSR compile with the `serverComponents` compiler
193
+ option. With `@solidjs/vite-plugin`, `solid({ ssr: true, serverFunctions:
194
+ { components: true } })` is the turnkey setup (the examples under
195
+ `examples/todos-server`, `examples/notes`, `examples/chat`); a hand-rolled
196
+ build passes `serverComponents: true` to `@solidjs/compiler` or
197
+ `@solidjs/babel-plugin` for the SSR side. Without it a dynamic
198
+ `class`/`style` compiles inside the template's quotes, where a slot value
199
+ cannot be marked — the `inline` finding below.
200
+
201
+ ## Diagnostics
202
+
203
+ `BINDING_SLOT_POSITION` (`data.reason`):
204
+
205
+ | reason | severity | what happened | fix |
206
+ | -------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
207
+ | `spread` | error (throws) | a slot's return was spread onto an element | name each position |
208
+ | `stringified` | warn | template literal / concatenation | whole value at one position |
209
+ | `coerced` | warn | comparison, arithmetic, `==` | decide in the fill |
210
+ | `inline` | warn | reached `class`/`style` inside template quotes | compile with `serverComponents: true` |
211
+ | `markup` | warn | the fill returned JSX but the template read a property | return an object, or place the slot |
212
+ | `server-local` | warn | a server function at `on*`/`ref` | bind a slot property |
213
+ | `tuple` | warn | an array at an `on*` position | return the tuple from the fill |
214
+ | `reserved-key` | warn | the fill used a reserved key | rename it |
215
+ | `arg` | warn | a slot property passed in another slot call's argument (nested in plain objects/arrays; `data.path`) | pass the server's own value, or read it in the fill from client state |
216
+ | `prop` | warn | a slot property at a `prop:*` key of a spread | bind the attribute form, or set the property in the fill's ref |
217
+ | `fill-shape` | warn (client) | the fill returned a non-object (`null`, array, DOM node, async value, primitive), or the prop read as data is not a function | return a plain object from a function prop |
218
+ | `text-shape` | warn (client) | a text position received a non-primitive (object, array, DOM node, function, async value — `data.key`, `data.shape`) | return a string or number; markup goes in a template slot |
219
+ | `orphan` | warn (client) | markers for an occurrence that can never bind: `data.why` `"fill"` — no fill for the prop; `"record"` — a called occurrence with no args record | `fill`: pass the prop / match the name on both sides. `record`: not the fill — rebuild client and server together (stale prebundle, cached asset), else report it |
220
+
221
+ Every reason but `fill-shape`, `text-shape` and `orphan` comes from the server render.
222
+ `orphan` is the one failure this model cannot otherwise show you: the
223
+ element is inert — a handler that never fires, a class that never updates —
224
+ with no error.
225
+
226
+ `STRICT_READ_UNTRACKED` naming a fill ("the \`row\` binding-slot fill",
227
+ "the \`comment\` template-slot fill"): a top-level read in its body; use
228
+ getters (above).
package/types/client.d.ts CHANGED
@@ -2,7 +2,7 @@ import { getOwner, createComponent, untrack, merge as mergeProps } from "solid-j
2
2
  import type { ClientErrorHook } from "solid-js";
3
3
  import { effect, memo } from "./render.js";
4
4
  import { JSX } from "./jsx.js";
5
- import type { RequestEventLocals } from "./server.js";
5
+ import type { RequestEventLocals, HydrationWriter, HydrationValue } from "./server.js";
6
6
  import type { TraceContext } from "./trace.js";
7
7
  type MountableElement = Element | Document | ShadowRoot | DocumentFragment | Node;
8
8
  /**
@@ -74,12 +74,13 @@ export interface ResponseStub {
74
74
  * `locals`, whichever entry typed the event.
75
75
  */
76
76
  export { RequestEventLocals } from "./server.js";
77
+ export type { HydrationWriter, HydrationValue } from "./server.js";
77
78
  export interface RequestEvent {
78
79
  request: Request;
79
80
  locals: RequestEventLocals;
80
81
  }
81
82
  export type { CookieOptions } from "./cookies.js";
82
- export type { CallEvent, CallListener, CallLive, FrameAppliedEvent, FrameEvent, FrameListener, FrameLive, FrameProducedEvent, InvocationEvent, InvocationListener, InvocationLive, RenderEvent, RenderListener, RenderLive } from "./observe.js";
83
+ export type { CallEvent, CallListener, CallLive, CallRequestEvent, CallRequestListener, FrameAppliedEvent, FrameEvent, FrameListener, FrameLive, FrameProducedEvent, InvocationEvent, InvocationListener, InvocationLive, RenderEvent, RenderListener, RenderLive, RenderRoute } from "./observe.js";
83
84
  export type { TraceContext, TraceProvider } from "./trace.js";
84
85
  export type { ServerFunction, ServerFunctionMetadata, ServerFunctionRPC } from "./server-functions/shared.js";
85
86
  export declare const waitAsset: (promise: Promise<unknown>) => void;
@@ -103,6 +104,20 @@ export { effect, memo, untrack, getOwner, createComponent };
103
104
  */
104
105
  export { mergeProps };
105
106
  export declare const getRequestEvent: () => RequestEvent | undefined;
107
+ /** Client stub — values are written by the server render. See the server entry. */
108
+ export declare const getHydrationWriter: () => HydrationWriter | undefined;
109
+ /**
110
+ * Removes and returns the value the server render wrote under `key` with
111
+ * `getHydrationWriter().write(key, value)`, or `undefined` when the page
112
+ * carries none (or it was already taken). A written promise arrives as
113
+ * `"pending"` until its settlement streams in, then as `"resolved"` or
114
+ * `"rejected"`. Readable before `hydrate()` runs and after hydration has
115
+ * ended. Server: `undefined`.
116
+ *
117
+ * The page's values live on `globalThis._$HY.r`; a test seeds them with
118
+ * `globalThis._$HY = { r: { "sq:key": value } }`.
119
+ */
120
+ export declare function takeHydrationValue<T = unknown>(key: string): HydrationValue<T> | undefined;
106
121
  /**
107
122
  * Client stub — the trace a request belongs to is a server-side reading
108
123
  * (the incoming `traceparent`, the render's origination); the browser SDK
@@ -144,6 +159,26 @@ export declare function registerDelegatedRoot(root: MountableElement): void;
144
159
  export declare function unregisterDelegatedRoot(root: MountableElement): void;
145
160
  export declare function registerDelegatedContainer(container: MountableElement, owner?: MountableElement): void;
146
161
  export declare function unregisterDelegatedContainer(container: MountableElement, owner?: MountableElement): void;
162
+ /**
163
+ * Runs `fn` as a handler of the DOM event `e`, inside the interaction frame
164
+ * the runtime opens for `e` — the one its own listeners for `e` run in. A
165
+ * listener the runtime did not attach (a router's `document` click handler,
166
+ * analytics, drag-and-drop) wraps its body in this, so its work joins the
167
+ * same interaction record as the component handlers for the same event
168
+ * instead of running outside one. In production builds this is `fn()`.
169
+ *
170
+ * Use it for listeners that respond to the user (`click`, `submit`,
171
+ * `keydown`), not for passive ones (`mousemove`, `focusin` preloads), which
172
+ * would each record an interaction.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * document.addEventListener("click", e =>
177
+ * dispatchAsInteraction(e, () => handleAnchorClick(e))
178
+ * );
179
+ * ```
180
+ */
181
+ export declare function dispatchAsInteraction<T>(e: Event, fn: () => T): T;
147
182
  export declare function getDelegatedRoot(node: MountableElement): MountableElement | undefined;
148
183
  export declare function setProperty(node: Element, name: string, value: any): void;
149
184
  export declare function registerElementClaim(handler: (element: Element) => void): () => void;
@@ -17,4 +17,5 @@ declare const RawTextElements: Set<string>;
17
17
  declare const DOMElements: Set<string>;
18
18
  declare const COMPOSED_BODY_FRAMING: ReadonlySet<string>;
19
19
  declare function isHttpNavigationTarget(target: string): boolean;
20
- export { DOMWithState, ChildProperties, DelegatedEvents, SVGElements, MathMLElements, VoidElements, RawTextElements, Namespaces, DOMElements, $$SLOT, $$HOST, COMPOSED_BODY_FRAMING, isHttpNavigationTarget };
20
+ declare function isEventName(name: string): boolean;
21
+ export { DOMWithState, ChildProperties, DelegatedEvents, SVGElements, MathMLElements, VoidElements, RawTextElements, Namespaces, DOMElements, $$SLOT, $$HOST, COMPOSED_BODY_FRAMING, isHttpNavigationTarget, isEventName };
@@ -52,5 +52,13 @@ export declare function unscopedHoleAllocatedIds(before: string, after: string,
52
52
  hole?: number;
53
53
  registered?: string;
54
54
  }, subject?: unknown): void;
55
+ /**
56
+ * Dev CHECK: a function reached an attribute whose name starts with `on` but
57
+ * is not an event handler — a lowercase `onclick`, or a 1.x `on:click`. Only
58
+ * `on` + an uppercase letter (`onClick`) binds an event in 2.0; anything else
59
+ * is a plain attribute, so the function is stringified into the attribute's
60
+ * text. Reported once per attribute name so a row template reports once.
61
+ */
62
+ export declare function lowercaseEventAttribute(name: string, node: Element): void;
55
63
  /** `Name: message` for an Error, `String(value)` otherwise. */
56
64
  export declare function errorText(error: unknown): string;