effect-atom-svelte 0.5.0 → 0.5.2

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.
package/README.md CHANGED
@@ -8,14 +8,14 @@ This is a community project by Jarred Norris. It is not part of Effect, and the
8
8
 
9
9
  ## Requirements
10
10
 
11
- - `effect` 4.1.x. The peer range is `~4.1.0`, not `^4.1.0`: the bindings use parts of the atom registry that aren't public API, which a minor release of `effect` can change.
12
- - Svelte 5.57.2 or later. `experimental.async` is needed for `useAtomSuspense`, `useAtomResult` and server rendering.
11
+ - `effect` 4.1.x or 4.2.x. The peer range is `~4.1.0 || ~4.2.0`, not `^4.1.0`: the bindings use parts of the atom registry that aren't public API, which a minor release of `effect` can change. A daily CI run tests each new minor release, and a release of effect-atom-svelte adds it to the range once the tests pass. For `effect` 4.0, use effect-atom-svelte 0.4 (and effect-atom-svelte-devtools 0.3).
12
+ - Svelte 5.57.2 or later. The async hooks (`useAtomSuspense`, `useAtomResult`) depend on Svelte's experimental async support. `RegistryProvider`, `useAtom`, `useAtomValue` and the other hooks work without it, on the server too. `HydrationBoundary` works without it but can't update atoms that already exist while the page hydrates.
13
13
  - SvelteKit is optional. The docs site and its tests run on SvelteKit 3. On SvelteKit 2, the error hooks in `effect-atom-svelte/sveltekit` work with less detail, and reach `<svelte:boundary>` only with `kit.experimental.handleRenderingErrors` turned on. `remoteQueryAtom` needs SvelteKit 3 with `experimental.remoteFunctions`.
14
14
 
15
15
  ## Installation
16
16
 
17
17
  ```sh
18
- npm install effect-atom-svelte "effect@~4.1.0"
18
+ npm install effect-atom-svelte "effect@~4.2.0"
19
19
  ```
20
20
 
21
21
  Turn on Svelte's async mode. In SvelteKit 3, pass it to `sveltekit()` in `vite.config.ts`:
@@ -64,9 +64,8 @@ On the server, the provider creates a registry for each request, so visitors nev
64
64
  const greeting = useAtomSuspense(greetingAtom);
65
65
  </script>
66
66
 
67
- <button onclick={() => (count.current += 1)}
68
- >{count.current} × 2 = {doubled.current}</button
69
- >
67
+ <button onclick={() => (count.current += 1)}>Add one</button>
68
+ <p>{count.current} × 2 = {doubled.current}</p>
70
69
 
71
70
  <svelte:boundary>
72
71
  <p>{await greeting.current}</p>
package/dist/Form.d.ts CHANGED
@@ -86,8 +86,8 @@ export interface MakeOptions {
86
86
  /** When a field's error first shows. Defaults to `"blur"`. */
87
87
  readonly validateOn?: Timing | undefined;
88
88
  /**
89
- * When it updates after the field has shown an error, or once the form has been submitted.
90
- * Defaults to `"input"`.
89
+ * When a field's error updates once it has shown, or once the form has been submitted. Defaults
90
+ * to `"input"`.
91
91
  */
92
92
  readonly revalidateOn?: Timing | undefined;
93
93
  /** How long to wait after a change before validating. Defaults to none. */
@@ -139,7 +139,6 @@ export interface MakeOptionsWithRuntime<R, ER> extends MakeOptions {
139
139
  * );
140
140
  * ```
141
141
  *
142
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
143
142
  * @stability unstable
144
143
  * @since 0.4.0
145
144
  * @category constructors
@@ -196,12 +195,17 @@ type ItemOf<V> = NonNullable<V> extends readonly (infer Item)[] ? Item : never;
196
195
  */
197
196
  export type AnyPath = readonly (string | number)[];
198
197
  /**
199
- * HTML input constraints read from a field's Schema checks: `minlength` from `isMinLength` and
200
- * `isNonEmpty`, `maxlength` from `isMaxLength`, both from `isBetweenLength`, `min` and `max` from
201
- * `isGreaterThanOrEqualTo`, `isLessThanOrEqualTo` and `isBetween`, `pattern` from an `isPattern`
202
- * anchored with `^` and `$`, with no flags but `u` or `v` (an HTML pattern must match the whole value, a
203
- * Schema pattern anywhere in it), and `required`
204
- * where the Schema rejects an empty string. Other checks set nothing.
198
+ * HTML input constraints read from a field's Schema checks. Other checks set nothing, and neither
199
+ * do exclusive bounds.
200
+ *
201
+ * - `required`: where the Schema rejects an empty string, from a `minlength` of 1 or more on a key
202
+ * that isn't optional.
203
+ * - `minlength`: from `isMinLength`, `isNonEmpty` and `isBetweenLength`.
204
+ * - `maxlength`: from `isMaxLength` and `isBetweenLength`.
205
+ * - `min`: from `isGreaterThanOrEqualTo` and `isBetween`.
206
+ * - `max`: from `isLessThanOrEqualTo` and `isBetween`.
207
+ * - `pattern`: from an `isPattern` anchored with `^` and `$`, without `|`, and with no flags but
208
+ * `u` or `v`: an HTML pattern must match the whole value, a Schema pattern anywhere in it.
205
209
  *
206
210
  * @stability unstable
207
211
  * @since 0.4.0
@@ -225,7 +229,7 @@ export interface FieldAttrs {
225
229
  /**
226
230
  * One field of a form instance. Every property is reactive in a component. `value` can be
227
231
  * assigned, so `bind:value={field.value}` works; an assignment counts as input for validation
228
- * timing, and a change clears a server or manual error on the field and the form-level error.
232
+ * timing. Errors from `mapError` or `setErrors` clear as `setErrors` describes.
229
233
  *
230
234
  * @stability unstable
231
235
  * @since 0.4.0
@@ -268,6 +272,11 @@ export interface Field<V> {
268
272
  * touched.
269
273
  */
270
274
  readonly attrs: FieldAttrs;
275
+ /**
276
+ * HTML constraints read from the field's Schema checks, such as `maxlength`, kept out of `attrs`:
277
+ * spread them on a native input, `<input {...field.attrs} {...field.constraints} />`, for the
278
+ * browser's own limits too. `Constraints` lists the checks that set each.
279
+ */
271
280
  readonly constraints: Constraints;
272
281
  /** What leaving the field does, for a custom control that has no blur event. */
273
282
  readonly blur: () => void;
@@ -385,6 +394,9 @@ export type ValidationError = FormValidationError;
385
394
  * never compete with the form's errors, and an `onsubmit` that prevents the browser's submit,
386
395
  * submits the form, and moves focus to the first field with an error when validation fails.
387
396
  *
397
+ * `attrs.onsubmit` calls `submit()` with no arguments. A form whose `payload` takes arguments needs
398
+ * its own `onsubmit`.
399
+ *
388
400
  * @stability unstable
389
401
  * @since 0.4.0
390
402
  * @category models
@@ -431,9 +443,15 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
431
443
  */
432
444
  readonly submitResult: AsyncResult.AsyncResult<A, E>;
433
445
  /**
434
- * A form-level error, on no field: `mapError`'s or `setErrors`' `form`, which shows at once and
435
- * clears on any change to the values, at the next submit or on reset; or an error from a check on the whole Struct
436
- * that gives no `path`, which shows only after `submit` or a `validate()` of the whole form.
446
+ * A form-level error, on no field, from one of two sources:
447
+ *
448
+ * - **`form` from `mapError` or `setErrors`.** It shows at once, and clears as `setErrors`
449
+ * describes.
450
+ * - **A check on the whole Struct that gives no `path`.** It shows only after `submit` or a
451
+ * `validate()` of the whole form. From then on it follows the latest check, clearing once the
452
+ * values pass it, or on reset.
453
+ *
454
+ * While both are set, the first shows.
437
455
  */
438
456
  readonly rootError: string | undefined;
439
457
  /**
@@ -452,7 +470,10 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
452
470
  }>;
453
471
  /** Whether the values differ from the last successful submit's. */
454
472
  readonly dirtySinceSubmit: boolean;
455
- /** Attributes to spread on the `<form>` element: see `FormAttrs`. */
473
+ /**
474
+ * Attributes to spread on the `<form>` element: see `FormAttrs`. `attrs.onsubmit` calls
475
+ * `submit()` with no arguments. A form whose `payload` takes arguments needs its own `onsubmit`.
476
+ */
456
477
  readonly attrs: FormAttrs;
457
478
  /**
458
479
  * Decodes the values and, when they decode, writes the submit atom and waits for its result. A
@@ -460,7 +481,8 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
460
481
  * touch the fresh form. Instances that submit to the same `Atom.fn` share its one result: if
461
482
  * another instance writes it while this submit runs, this submit resolves with the other's
462
483
  * result, so give each instance its own atom. When the `RegistryProvider` that holds the form
463
- * is destroyed mid-submit, the submit resolves as interrupted.
484
+ * is destroyed mid-submit, the submit resolves as interrupted. `attrs.onsubmit` calls `submit()`
485
+ * with no arguments. A form whose `payload` takes arguments needs its own `onsubmit`.
464
486
  */
465
487
  readonly submit: (...args: [Args] extends [undefined] ? [] : [args: Args]) => Promise<Exit.Exit<A, E | ValidationError>>;
466
488
  /**
@@ -494,8 +516,9 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
494
516
  /**
495
517
  * Puts errors on fields or on the form; they show at once, and keep `valid` false while set. A
496
518
  * field's error clears when the value at its path changes, including from a change to a parent or
497
- * a child path. The form-level error (`form`) clears on any change to the values, and at the
498
- * next submit. Both clear on reset; blur, `validate` and a write of the same values leave them.
519
+ * a child path, and stays across a submit. The form-level error (`form`) clears on any change to
520
+ * the values, and at the next submit. Both clear on reset; blur, `validate` and a write of the
521
+ * same values leave them.
499
522
  * They don't stop a submit: it checks only the Schema, and the server checks the values again.
500
523
  */
501
524
  readonly setErrors: (errors: Errors<T>) => void;
@@ -541,8 +564,9 @@ export interface BaseInstanceOptions<T> {
541
564
  readonly initialValues: T | (() => T);
542
565
  /**
543
566
  * Storage for the values that you own, such as an `Atom.kvs` draft that survives a reload. A
544
- * write to it from code counts as a change made in code, not as typing. So does a field's write
545
- * that the atom hands back changed (trimmed, say): the field loses its own timing for that change.
567
+ * write to it from code counts as a change made in code, not as input, as with `setValues`. So
568
+ * does a field write that the atom stores differently, such as trimmed: if the field is already
569
+ * touched, a broken check shows at once instead of waiting for its own timing.
546
570
  */
547
571
  readonly values?: Atom.Writable<T> | undefined;
548
572
  /**
@@ -563,9 +587,8 @@ export interface InstanceOptions<T, D, A, E, W, Args> extends BaseInstanceOption
563
587
  /**
564
588
  * Claims a typed failure: return errors to put on fields or the form, or `undefined` to leave
565
589
  * the failure in `submitResult`. Defects and interruptions are never passed here. The errors
566
- * show at once and keep `valid` false while set. A field's error clears when the value at its
567
- * path changes; the form-level one (`form`) on any change to the values. All of them clear at the
568
- * next submit and on reset.
590
+ * show at once and keep `valid` false while set. They clear as `setErrors` describes, and all of
591
+ * `mapError`'s errors, field errors included, also clear at the next submit.
569
592
  */
570
593
  readonly mapError?: ((error: E) => Errors<T> | undefined) | undefined;
571
594
  /** Submit after each change that validates. Only for a submit that takes no arguments. */
@@ -56,8 +56,9 @@ export interface WriteOptions {
56
56
  readonly signal?: AbortSignal | undefined;
57
57
  }
58
58
  /**
59
- * Reads an atom, optionally through a transform. The atom stays mounted while something reactive
60
- * reads `.current`, and unmounted when nothing does. The transform runs again only when the atom,
59
+ * Reads an atom, optionally through a transform. The hook
60
+ * [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom while something reactive
61
+ * reads `.current`, and lets it go when nothing does. The transform runs again only when the atom,
61
62
  * or state the transform reads, changes, so a transform that builds an object returns the same
62
63
  * object until then. A read outside a reactive context, such as in an event handler, runs it again.
63
64
  *
@@ -96,11 +97,12 @@ export declare function useAtomValue<A, B>(input: AtomInput<Atom.Atom<A>>, f: (v
96
97
  */
97
98
  export declare const useAtom: <R, W>(input: AtomInput<Atom.Writable<R, W>>) => AtomState<R, W>;
98
99
  /**
99
- * Keeps an atom alive for as long as this component is mounted, even when no component reads
100
- * it. Use it in a component that outlives the readers, such as a layout, so the atom keeps its
101
- * value while they come and go. Mounting an atom that hasn't been computed also computes it.
100
+ * [Holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) an atom while the component lives,
101
+ * even when no component reads it. Use it in a component that outlives the readers, such as a
102
+ * layout, so the atom keeps its value while they come and go. Holding an atom that hasn't been
103
+ * computed also computes it.
102
104
  *
103
- * **Example** (Keeping a connection open while a component is mounted)
105
+ * **Example** (Keeping a connection open while a component lives)
104
106
  *
105
107
  * ```ts
106
108
  * import { useAtomMount } from "effect-atom-svelte";
@@ -116,24 +118,34 @@ export declare const useAtom: <R, W>(input: AtomInput<Atom.Writable<R, W>>) => A
116
118
  */
117
119
  export declare const useAtomMount: (input: AtomInput<Atom.Atom<unknown>>) => void;
118
120
  /**
119
- * Returns a setter. The atom is mounted for the component's lifetime, so an `Atom.fn` keeps its
120
- * state between calls and is not disposed between set and read.
121
+ * Returns a setter. The hook [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom
122
+ * while the component lives, so an `Atom.fn` keeps its state between calls and is not disposed
123
+ * between set and read.
121
124
  *
122
125
  * In `value` mode a function passed to the setter is an updater, called with the current value. To
123
126
  * store a function in an atom, wrap it: `set(() => handler)`.
124
127
  *
125
- * In `promise` and `promiseExit` modes the setter waits for the atom's next settled result. The
126
- * wait holds the atom, so a call still in flight keeps it running after the component is
127
- * destroyed, until it settles, unless the `RegistryProvider` that created the registry is
128
- * destroyed: that interrupts the call and settles it as interrupted. The call's `signal` cancels only the wait: an `Atom.fn` already
129
- * running keeps going (send `Atom.Interrupt` to stop it). A signal that is already aborted settles
130
- * the call as interrupted without writing, as `fetch` does. Calls on one `Atom.fn` share its single
131
- * result, so a new call supersedes one in flight and every pending call resolves with the latest
132
- * call's result. A write that throws, as an `Atom.fn` that throws before returning its Effect does,
133
- * settles the call as that defect: `promiseExit` resolves with `Exit.die`, `promise` rejects with
134
- * the error. `Atom.Reset` has no result to wait for, so these modes leave it out of their
135
- * types and reject it; reset with a `value` mode setter. A reset written while a promise-mode call
136
- * is pending settles that promise as interrupted. To cancel a call, send `Atom.Interrupt`.
128
+ * In `promise` and `promiseExit` modes the setter returns a promise that settles with the atom's
129
+ * next settled result:
130
+ *
131
+ * - **After the component is destroyed.** The wait holds the atom, so a call still in flight keeps
132
+ * running until it settles, unless the `RegistryProvider` that created the registry is destroyed:
133
+ * that interrupts the call and settles it as interrupted.
134
+ * - **`signal`.** Aborting `signal` settles the promise as interrupted; a signal that is already
135
+ * aborted settles without writing, as `fetch` does. The call itself runs on while something holds
136
+ * the atom; write `Atom.Interrupt` to stop it. Neither `Atom.Interrupt` nor `Atom.Reset` stops a
137
+ * `concurrent` `Atom.fn`'s calls: they run until it is disposed, and a later call waits on them
138
+ * too.
139
+ * - **Shared result.** Calls on one `Atom.fn` share its single result. By default a new call
140
+ * interrupts the one in flight, and every pending call settles with the newest call's result. With
141
+ * `concurrent: true`, calls run together and settle with the oldest running call's success once
142
+ * all have finished, or with the first failure at once.
143
+ * - **A write that throws.** As an `Atom.fn` that throws before returning its Effect does, it
144
+ * settles the call as that defect: `promiseExit` resolves with `Exit.die`, `promise` rejects with
145
+ * the error.
146
+ * - **`Atom.Reset`.** It has no result to wait for, so these modes leave it out of their types and
147
+ * reject it; reset with a `value` mode setter. A reset written while a promise-mode call is pending
148
+ * settles that promise as interrupted.
137
149
  *
138
150
  * **Example** (Updating an atom from its current value)
139
151
  *
@@ -162,7 +174,9 @@ export declare function useAtomSet<A, E, W>(input: AtomInput<Atom.Writable<Async
162
174
  readonly mode?: WriteMode | undefined;
163
175
  }): (value: W, options?: WriteOptions) => undefined | Promise<A> | Promise<Exit.Exit<A, E>>;
164
176
  /**
165
- * Returns a function that runs the atom again. The atom is mounted so the refresh is not lost.
177
+ * Returns a function that runs the atom again. It also
178
+ * [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom while the component lives,
179
+ * so the refreshed result is kept even when nothing on screen reads it.
166
180
  *
167
181
  * **Example** (Running an atom again on click)
168
182
  *
@@ -181,15 +195,19 @@ export declare function useAtomSet<A, E, W>(input: AtomInput<Atom.Writable<Async
181
195
  export declare const useAtomRefresh: (input: AtomInput<Atom.Atom<unknown>>) => (() => void);
182
196
  /**
183
197
  * Calls `f` on every change while the component lives, and with the current value first when
184
- * `immediate` is set. The atom is computed once the component mounts, and never on the server, so a
185
- * derived or effect atom that nothing else reads still runs and reports its changes. If that first
186
- * computation throws, the error is left to the atom's readers and `f` hears the atom once it
187
- * recovers; with `immediate`, it throws in the component, as there is no value to call `f` with.
198
+ * `immediate` is set. The hook [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom
199
+ * and computes it once the component mounts, never on the server, so a derived or effect atom that
200
+ * nothing else reads still runs and reports its changes.
201
+ *
188
202
  * A change raised while another component is reading an atom reaches `f` on a microtask, so `f` can
189
203
  * write `$state` (Svelte forbids that during a read). Changes after it wait their turn, so `f` sees
190
204
  * every change in order; any other change reaches it synchronously. Nothing reaches `f` once the
191
205
  * component is destroyed, not even a change still waiting for its microtask.
192
206
  *
207
+ * If the atom's first computation throws, the error is left to the atom's readers and `f` hears the
208
+ * atom once it recovers; with `immediate`, it throws in the component, as there is no value to call
209
+ * `f` with.
210
+ *
193
211
  * **Example** (Saving every change)
194
212
  *
195
213
  * ```ts
@@ -207,25 +225,30 @@ export declare const useAtomSubscribe: <A>(input: AtomInput<Atom.Atom<A>>, f: (v
207
225
  readonly immediate?: boolean | undefined;
208
226
  }) => void;
209
227
  /**
210
- * Sets starting values as `AtomRegistry.make({ initialValues })` would: on the atom that receives it
211
- * (a wrapper such as `withRefresh` passes it to its source), kept as the value of the atom's first
212
- * build, which still reads and follows the atom's sources. The atoms are not computed here: each
213
- * keeps its value, uncomputed, while this component lives, and the first component to read it
214
- * computes it from there, so a value set in a layout is still there when a page reads it later, and
215
- * an atom that can only compute in the browser can start from a value on the server.
216
- *
217
- * A value applies once while the atom is held, so a component mounted later, or a second
218
- * component with its own value, does not overwrite a value the atom has moved on from since the
219
- * first applied one. An atom that is already in use without one, read by another component, is set
220
- * to the value, as `@effect/atom-react` does. Once nothing holds the atom and the registry disposes
221
- * it, the next component to start it applies its value again. On the server a value lasts one render, so each request against a shared registry applies
222
- * its own; requests rendering at the same time share the registry's atoms, and with them the value
223
- * the first one applied.
224
- *
225
- * An effect or stream atom given a value still runs on mount, as with `AtomRegistry.make`. To keep
226
- * the value instead, as for data a `load` function already fetched, pass the entry as
227
- * `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then runs once
228
- * it is refreshed, or once an atom its factory reads before returning the effect changes.
228
+ * Sets starting values from a component, as `AtomRegistry.make({ initialValues })` would.
229
+ *
230
+ * - **Once while the atom is held.** Each atom takes the first value a component gives it. Another
231
+ * call while something still holds the atom, as from a component mounting again or a second
232
+ * component with its own value, doesn't set it again; once the atom has been disposed, the next
233
+ * component to start it sets it again. An atom already in use without a value, read by another
234
+ * component, is set to it, as `@effect/atom-react` does.
235
+ * - **Held while the component lives.** The hook
236
+ * [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) its atoms without computing them:
237
+ * the first component to read an atom computes it, starting from the value, so a value set in a
238
+ * layout is still there when a page reads it later.
239
+ * - **Once per render on the server.** Each server render sets its values again and renders them
240
+ * without running the atom, so an atom that can only compute in the browser can start from a
241
+ * value on the server. Renders at the same time on a shared registry share the value the first
242
+ * one applied, until the last of them ends.
243
+ * - **Wrapped and derived atoms.** A wrapper such as `Atom.withRefresh`, `Atom.swr` or
244
+ * `Atom.debounce` passes the value to its source. The atom starts from the value and still reads
245
+ * its sources, so a derived atom computes again when one of them changes.
246
+ * - **Effect and stream atoms.** In the browser, an atom that runs an effect or a stream still runs
247
+ * it when it is first read, as with `AtomRegistry.make`, and shows the value until the run
248
+ * finishes. To keep the value instead, as for data a `load` function already fetched, pass the
249
+ * entry as `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then
250
+ * runs once it is refreshed, or once an atom its function reads before returning the effect
251
+ * changes.
229
252
  *
230
253
  * **Example** (Starting an atom from a prop)
231
254
  *
@@ -252,7 +275,7 @@ export declare const useAtomInitialValues: (initialValues: Iterable<readonly [At
252
275
  *
253
276
  * A ref has no registry. On the server, one created at module level is shared by every request,
254
277
  * so don't write a visitor's data to it there: see
255
- * https://atom.jarrednorris.dev/server-rendering#module-state-is-shared-between-visitors
278
+ * [Module state is shared between visitors](https://atom.jarrednorris.dev/server-rendering#module-state-is-shared-between-visitors).
256
279
  *
257
280
  * **Example** (Reading a ref)
258
281
  *
@@ -260,8 +283,8 @@ export declare const useAtomInitialValues: (initialValues: Iterable<readonly [At
260
283
  * import { useAtomRef } from "effect-atom-svelte";
261
284
  * import { profile } from "./refs.ts";
262
285
  *
263
- * const current = useAtomRef(profile);
264
- * // In the markup: {current.current.name}
286
+ * const user = useAtomRef(profile);
287
+ * // In the markup: {user.current.name}
265
288
  * ```
266
289
  *
267
290
  * @stability unstable
@@ -318,7 +341,10 @@ export declare const useAtomRefPropValue: <A, K extends keyof A>(input: AtomInpu
318
341
  * @category models
319
342
  */
320
343
  export interface ResultOptions {
321
- /** Treat a refreshing result as pending, so the first await also waits for the refresh. */
344
+ /**
345
+ * Treat a refreshing result as pending, so the await waits for the refresh instead of resolving
346
+ * with the current value.
347
+ */
322
348
  readonly suspendOnWaiting?: boolean | undefined;
323
349
  /**
324
350
  * Run a server-rendered atom again once the page has hydrated. Overrides `RegistryProvider`'s
@@ -328,11 +354,18 @@ export interface ResultOptions {
328
354
  }
329
355
  /**
330
356
  * Awaits an async atom's first result, then returns a live handle to its `AsyncResult`. Use it as
331
- * a top-level `await` in a component script; server rendering waits for it, and with a
332
- * serialization key the browser starts from the server's result instead of running the atom
333
- * again. With a getter, only the first atom is awaited: when the getter picks another atom the
334
- * handle follows it, starting from that atom's current result (often `Initial`), and the
335
- * component's await does not run again. On the server, an atom with a `withServerValue` override
357
+ * a top-level `await` in a component script; server rendering waits for it. With a serialization
358
+ * key the browser starts from the server's result instead of running the atom again, unless
359
+ * `revalidateOnHydrate` is set, the server's result was still `waiting`, or the atom is a
360
+ * `staleTime` (`Atom.swr`) query that is stale or failed with no earlier success.
361
+ *
362
+ * Call it before the script's first `await` (for several atoms, in one `Promise.all`); an atom
363
+ * read after that `await` runs again in the browser. See
364
+ * [Call hooks before the first await](https://atom.jarrednorris.dev/hydration#call-hooks-before-the-first-await).
365
+ *
366
+ * With a getter, only the first atom is awaited: when the getter picks another atom the handle
367
+ * follows it, starting from that atom's current result (often `Initial`), and the component's
368
+ * await does not run again. On the server, an atom with a `withServerValue` override
336
369
  * reads as that value and is never computed. An atom that has not started, whose result is
337
370
  * `Initial` with nothing running, as an `Atom.fn` nothing has called, keeps the await pending in the
338
371
  * browser until something writes it; on the server, where nothing will during the render, the
@@ -363,12 +396,15 @@ export declare const useAtomResult: <A, E>(input: AtomInput<Atom.Atom<AsyncResul
363
396
  */
364
397
  export interface SuspenseOptions {
365
398
  /**
366
- * Treat a refreshing result as pending, so `await` waits for the refreshed value instead of
367
- * resolving with the current one. The boundary keeps showing its content meanwhile; use
399
+ * Treat a refreshing result as pending, so the await waits for the refresh instead of resolving
400
+ * with the current value. The boundary keeps showing its content meanwhile; use
368
401
  * `$effect.pending()` to show progress.
369
402
  */
370
403
  readonly suspendOnWaiting?: boolean | undefined;
371
- /** Resolve with the Success or Failure result instead of the value, rather than rejecting. */
404
+ /**
405
+ * Resolve with the whole `Success` or `Failure` result instead of the value, rather than
406
+ * rejecting when the atom fails.
407
+ */
372
408
  readonly includeFailure?: boolean | undefined;
373
409
  /**
374
410
  * Run a server-rendered atom again once the page has hydrated. Overrides `RegistryProvider`'s
@@ -379,14 +415,26 @@ export interface SuspenseOptions {
379
415
  /**
380
416
  * Exposes an async atom as a promise for `await` in markup or `$derived(await ...)`. The promise is
381
417
  * stable while the result is unchanged, and a new one is issued when the result changes, so Svelte
382
- * re-runs dependents only on real updates. Unchanged means the same atom and the same result
383
- * object: a refresh issues a new promise even if its value is equal, and so does a read after
384
- * every reader of a pending promise went away, as that wait was interrupted. Failures reject with the squashed cause, or resolve with
385
- * the `Failure` when `includeFailure` is set. On the server, an atom with a `withServerValue`
386
- * override resolves from that value and is never computed; if the value is `Initial`, the promise
387
- * rejects, so read it inside a `<svelte:boundary>` with a `pending` snippet. An atom that has not
388
- * started, whose result is `Initial` with nothing running, as an `Atom.fn` nothing has called,
389
- * stays pending in the browser until something writes it, and rejects on the server.
418
+ * re-runs dependents only on real updates. With a serialization key the browser starts from the
419
+ * server's result instead of running the atom again, unless `revalidateOnHydrate` is set, the
420
+ * server's result was still `waiting`, or the atom is a `staleTime` (`Atom.swr`) query that is
421
+ * stale or failed with no earlier success.
422
+ *
423
+ * Call it before the script's first `await`; an atom read after that `await` runs again in the
424
+ * browser. See
425
+ * [Call hooks before the first await](https://atom.jarrednorris.dev/hydration#call-hooks-before-the-first-await).
426
+ *
427
+ * - **A new promise.** Unchanged means the same atom and the same result object: a refresh issues
428
+ * a new promise even if its value is equal, and so does a read after every reader of a pending
429
+ * promise went away, as that wait was interrupted.
430
+ * - **Failures.** The promise rejects with `Cause.squash` of the cause, or resolves with the
431
+ * `Failure` when `includeFailure` is set.
432
+ * - **On the server.** An atom with a `withServerValue` override resolves from that value and is
433
+ * never computed; if the value is `Initial`, the promise rejects, so read it inside a
434
+ * `<svelte:boundary>` with a `pending` snippet.
435
+ * - **An atom nothing has started.** One whose result is `Initial` with nothing running, as an
436
+ * `Atom.fn` nothing has called, stays pending in the browser until something writes it, and
437
+ * rejects on the server.
390
438
  *
391
439
  * **Example** (Awaiting an atom in the markup)
392
440
  *
@@ -456,7 +504,6 @@ export declare function useAtomSuspense<A, E>(input: AtomInput<Atom.Atom<AsyncRe
456
504
  * </form>
457
505
  * ```
458
506
  *
459
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
460
507
  * @stability unstable
461
508
  * @since 0.4.0
462
509
  * @category hooks
@@ -64,7 +64,7 @@ class AtomCell {
64
64
  }
65
65
  }
66
66
  const readOnly = () => {
67
- throw new Error(`This atom value is read-only: useAtomValue and useAtomSuspense only read, as does useAtomRef for a ref without set, such as one from map. Write an atom with useAtom or useAtomSet, and a writable ref by assigning useAtomRef's current. ${troubleshooting("this-atom-value-is-read-only")}`);
67
+ throw new Error(`This atom value is read-only: useAtomValue, useAtomResult and useAtomSuspense only read, as does useAtomRef for a ref without set, such as one from map. Write an atom with useAtom or useAtomSet, and a writable ref by assigning useAtomRef's current. ${troubleshooting("this-atom-value-is-read-only")}`);
68
68
  };
69
69
  const valueOrThrow = (exit) => {
70
70
  if (Exit.isSuccess(exit)) {
@@ -152,18 +152,35 @@ const dropInitialValueMark = (registry, atom) => {
152
152
  current = current.initialValueTarget;
153
153
  }
154
154
  };
155
+ /** Whether a hook stops waiting at a result: it has left `Initial`, and isn't refreshing if asked. */
156
+ const settles = (result, suspendOnWaiting) => result._tag !== "Initial" && !(suspendOnWaiting && result.waiting);
157
+ /**
158
+ * Whether the atom's own node holds a value a `HydrationBoundary` brought that the server builds
159
+ * and waits for rather than rendering. Since Effect 4.1, a value a boundary queued for the atom's
160
+ * own node is applied as an initial value, as it always was for a wrapper's source. A settled one
161
+ * is rendered as is, like any initial value: building the node would run the effect again, after
162
+ * `load` ran it (#103). An `Initial` isn't: the hooks wait for it, as they did when Effect applied
163
+ * it as the node's value (4.0), since it may be promise-encoded, with a result that lands during
164
+ * the render. Nor, for a reader with `suspendOnWaiting`, is a `Success` still waiting, as `load`
165
+ * sends for a running stream: that reader asked to wait for the refresh, so the stream runs again.
166
+ */
167
+ const boundaryWaitedFor = (registry, atom, value, suspendOnWaiting) => Atom.isSerializable(atom) &&
168
+ queuedByBoundary(registry, atom[Atom.SerializableTypeId].key) &&
169
+ AsyncResult.isAsyncResult(value) &&
170
+ !settles(value, suspendOnWaiting);
155
171
  /**
156
- * On the server, the node holding a value from `useAtomInitialValues` for an atom: its own, or its
157
- * source's for a wrapper such as `withRefresh`, which passes the value on and reads as its source.
158
- * The server renders that value: mounting, reading or waiting for the atom would build it, and a
159
- * build runs the atom's read, the source's included, even when it keeps the value. That read may be
160
- * browser-only or start a request the value was there to save.
172
+ * On the server, the node holding an initial value for an atom, from `useAtomInitialValues` or a
173
+ * `HydrationBoundary`: its own, or its source's for a wrapper such as `withRefresh`, which passes
174
+ * the value on and reads as its source. The server renders that value: mounting, reading or waiting
175
+ * for the atom would build it, and a build runs the atom's read, the source's included, even when it
176
+ * keeps the value. That read may be browser-only or start a request the value was there to save.
177
+ * `suspendOnWaiting` is the reader's option: with it, a boundary's waiting value is waited for.
161
178
  *
162
179
  * For a wrapper, this assumes it reads as its source, as every wrapper Effect makes with
163
180
  * `initialValueTarget` does. A user's `Atom.transform` given `initialValueTarget` that changes the
164
181
  * value would render its source's value on the server, where Effect computes the transform.
165
182
  */
166
- const initialNodeOnServer = (registry, atom) => {
183
+ const initialNodeOnServer = (registry, atom, suspendOnWaiting = false) => {
167
184
  if (BROWSER) {
168
185
  return undefined;
169
186
  }
@@ -172,19 +189,13 @@ const initialNodeOnServer = (registry, atom) => {
172
189
  if (!node.preserveInitialValueOnBuild) {
173
190
  return undefined;
174
191
  }
175
- // Since Effect 4.1, a value a HydrationBoundary queued for the atom's own node is applied as an
176
- // initial value too. It isn't one of these: it may be a promise-encoded Initial whose result lands
177
- // during the render, which the hooks wait for, as they did when Effect applied it as the node's
178
- // value (4.0). Only a wrapper's source received it as an initial value then, and still does.
179
- if (target === atom &&
180
- Atom.isSerializable(atom) &&
181
- queuedByBoundary(registry, atom[Atom.SerializableTypeId].key)) {
182
- return undefined;
183
- }
184
- return node;
192
+ return target === atom &&
193
+ boundaryWaitedFor(registry, atom, node._value, suspendOnWaiting)
194
+ ? undefined
195
+ : node;
185
196
  };
186
- /** Whether, on the server, an atom renders a value from `useAtomInitialValues`. */
187
- const initialOnServer = (registry, atom) => initialNodeOnServer(registry, atom) !== undefined;
197
+ /** Whether, on the server, an atom renders an initial value (see `initialNodeOnServer`). */
198
+ const initialOnServer = (registry, atom, suspendOnWaiting = false) => initialNodeOnServer(registry, atom, suspendOnWaiting) !== undefined;
188
199
  /** Keeps an atom for the server render: a node with an initial value is held, not mounted. */
189
200
  const serverMount = (registry, atom) => {
190
201
  const node = initialNodeOnServer(registry, atom);
@@ -198,8 +209,6 @@ const serverGet = (registry, atom) => {
198
209
  const awaitResult = (registry, atom, options, signal) => Effect.runPromiseExit(AtomRegistry.getResult(registry, atom, options), {
199
210
  signal,
200
211
  });
201
- /** Whether a hook stops waiting at a result: it has left `Initial`, and isn't refreshing if asked. */
202
- const settles = (result, suspendOnWaiting) => result._tag !== "Initial" && !(suspendOnWaiting && result.waiting);
203
212
  /**
204
213
  * Waits for an async atom to settle, as `awaitResult` does, but resolves with the atom's own result
205
214
  * rather than an `Exit` rebuilt from it, which would drop a `Failure`'s `previousSuccess`.
@@ -298,8 +307,9 @@ const subscribedReader = (registry, getAtom, plainRead) => {
298
307
  // await, keeps it for the request. The mounts are released when the server render ends,
299
308
  // because a registry passed in by the caller outlives the request (JND-17).
300
309
  // An atom with a withServerValue override is never computed on the server, so it is not mounted:
301
- // mounting would run its real read, which is often browser-only. One with a value from
302
- // useAtomInitialValues is held and read without building it (see initialNodeOnServer).
310
+ // mounting would run its real read, which is often browser-only. One with an initial value, from
311
+ // useAtomInitialValues or a HydrationBoundary, is held and read without building it (see
312
+ // initialNodeOnServer).
303
313
  // Once the render has ended, a read that switches atoms, as from a reader kept past the render,
304
314
  // takes no mount: nothing would release it.
305
315
  let ended = false;
@@ -511,11 +521,12 @@ const mountWhileAlive = (input, kind) => {
511
521
  });
512
522
  };
513
523
  /**
514
- * Keeps an atom alive for as long as this component is mounted, even when no component reads
515
- * it. Use it in a component that outlives the readers, such as a layout, so the atom keeps its
516
- * value while they come and go. Mounting an atom that hasn't been computed also computes it.
524
+ * [Holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) an atom while the component lives,
525
+ * even when no component reads it. Use it in a component that outlives the readers, such as a
526
+ * layout, so the atom keeps its value while they come and go. Holding an atom that hasn't been
527
+ * computed also computes it.
517
528
  *
518
- * **Example** (Keeping a connection open while a component is mounted)
529
+ * **Example** (Keeping a connection open while a component lives)
519
530
  *
520
531
  * ```ts
521
532
  * import { useAtomMount } from "effect-atom-svelte";
@@ -598,7 +609,9 @@ export function useAtomSet(input, options) {
598
609
  };
599
610
  }
600
611
  /**
601
- * Returns a function that runs the atom again. The atom is mounted so the refresh is not lost.
612
+ * Returns a function that runs the atom again. It also
613
+ * [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom while the component lives,
614
+ * so the refreshed result is kept even when nothing on screen reads it.
602
615
  *
603
616
  * **Example** (Running an atom again on click)
604
617
  *
@@ -671,15 +684,19 @@ const orderedDelivery = (f) => {
671
684
  };
672
685
  /**
673
686
  * Calls `f` on every change while the component lives, and with the current value first when
674
- * `immediate` is set. The atom is computed once the component mounts, and never on the server, so a
675
- * derived or effect atom that nothing else reads still runs and reports its changes. If that first
676
- * computation throws, the error is left to the atom's readers and `f` hears the atom once it
677
- * recovers; with `immediate`, it throws in the component, as there is no value to call `f` with.
687
+ * `immediate` is set. The hook [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom
688
+ * and computes it once the component mounts, never on the server, so a derived or effect atom that
689
+ * nothing else reads still runs and reports its changes.
690
+ *
678
691
  * A change raised while another component is reading an atom reaches `f` on a microtask, so `f` can
679
692
  * write `$state` (Svelte forbids that during a read). Changes after it wait their turn, so `f` sees
680
693
  * every change in order; any other change reaches it synchronously. Nothing reaches `f` once the
681
694
  * component is destroyed, not even a change still waiting for its microtask.
682
695
  *
696
+ * If the atom's first computation throws, the error is left to the atom's readers and `f` hears the
697
+ * atom once it recovers; with `immediate`, it throws in the component, as there is no value to call
698
+ * `f` with.
699
+ *
683
700
  * **Example** (Saving every change)
684
701
  *
685
702
  * ```ts
@@ -736,25 +753,30 @@ const initialValuesApplied = new WeakSet();
736
753
  // does, so a request ending doesn't let a request starting overwrite the value another still renders.
737
754
  const serverHolders = new WeakMap();
738
755
  /**
739
- * Sets starting values as `AtomRegistry.make({ initialValues })` would: on the atom that receives it
740
- * (a wrapper such as `withRefresh` passes it to its source), kept as the value of the atom's first
741
- * build, which still reads and follows the atom's sources. The atoms are not computed here: each
742
- * keeps its value, uncomputed, while this component lives, and the first component to read it
743
- * computes it from there, so a value set in a layout is still there when a page reads it later, and
744
- * an atom that can only compute in the browser can start from a value on the server.
745
- *
746
- * A value applies once while the atom is held, so a component mounted later, or a second
747
- * component with its own value, does not overwrite a value the atom has moved on from since the
748
- * first applied one. An atom that is already in use without one, read by another component, is set
749
- * to the value, as `@effect/atom-react` does. Once nothing holds the atom and the registry disposes
750
- * it, the next component to start it applies its value again. On the server a value lasts one render, so each request against a shared registry applies
751
- * its own; requests rendering at the same time share the registry's atoms, and with them the value
752
- * the first one applied.
756
+ * Sets starting values from a component, as `AtomRegistry.make({ initialValues })` would.
753
757
  *
754
- * An effect or stream atom given a value still runs on mount, as with `AtomRegistry.make`. To keep
755
- * the value instead, as for data a `load` function already fetched, pass the entry as
756
- * `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then runs once
757
- * it is refreshed, or once an atom its factory reads before returning the effect changes.
758
+ * - **Once while the atom is held.** Each atom takes the first value a component gives it. Another
759
+ * call while something still holds the atom, as from a component mounting again or a second
760
+ * component with its own value, doesn't set it again; once the atom has been disposed, the next
761
+ * component to start it sets it again. An atom already in use without a value, read by another
762
+ * component, is set to it, as `@effect/atom-react` does.
763
+ * - **Held while the component lives.** The hook
764
+ * [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) its atoms without computing them:
765
+ * the first component to read an atom computes it, starting from the value, so a value set in a
766
+ * layout is still there when a page reads it later.
767
+ * - **Once per render on the server.** Each server render sets its values again and renders them
768
+ * without running the atom, so an atom that can only compute in the browser can start from a
769
+ * value on the server. Renders at the same time on a shared registry share the value the first
770
+ * one applied, until the last of them ends.
771
+ * - **Wrapped and derived atoms.** A wrapper such as `Atom.withRefresh`, `Atom.swr` or
772
+ * `Atom.debounce` passes the value to its source. The atom starts from the value and still reads
773
+ * its sources, so a derived atom computes again when one of them changes.
774
+ * - **Effect and stream atoms.** In the browser, an atom that runs an effect or a stream still runs
775
+ * it when it is first read, as with `AtomRegistry.make`, and shows the value until the run
776
+ * finishes. To keep the value instead, as for data a `load` function already fetched, pass the
777
+ * entry as `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then
778
+ * runs once it is refreshed, or once an atom its function reads before returning the effect
779
+ * changes.
758
780
  *
759
781
  * **Example** (Starting an atom from a prop)
760
782
  *
@@ -932,8 +954,12 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
932
954
  // Not waited for if nothing has started it: the hook rejects once seeded. Waited for as the hook
933
955
  // waits, so with suspendOnWaiting the seed is the settled result the render shows, not one the
934
956
  // browser would run again because it was still waiting.
935
- if (!initialOnServer(registry, atom) && !notStarted(registry.get(atom))) {
936
- let settled = suspendOnWaiting;
957
+ // A later reader of the key that has already asked for the settled result counts too: a
958
+ // HydrationBoundary's waiting value is waited for only then (see initialNodeOnServer).
959
+ let settled = suspendOnWaiting ||
960
+ (claim.first !== undefined && settledSeeds.has(claim.first));
961
+ if (!initialOnServer(registry, atom, settled) &&
962
+ !notStarted(registry.get(atom))) {
937
963
  await awaitResult(registry, atom, { suspendOnWaiting: settled });
938
964
  // A later reader of the key may want the settled result once this one's wait has begun.
939
965
  if (!settled && claim.first && settledSeeds.has(claim.first)) {
@@ -1145,11 +1171,18 @@ revalidateOption, suspendOnWaiting = false) => {
1145
1171
  };
1146
1172
  /**
1147
1173
  * Awaits an async atom's first result, then returns a live handle to its `AsyncResult`. Use it as
1148
- * a top-level `await` in a component script; server rendering waits for it, and with a
1149
- * serialization key the browser starts from the server's result instead of running the atom
1150
- * again. With a getter, only the first atom is awaited: when the getter picks another atom the
1151
- * handle follows it, starting from that atom's current result (often `Initial`), and the
1152
- * component's await does not run again. On the server, an atom with a `withServerValue` override
1174
+ * a top-level `await` in a component script; server rendering waits for it. With a serialization
1175
+ * key the browser starts from the server's result instead of running the atom again, unless
1176
+ * `revalidateOnHydrate` is set, the server's result was still `waiting`, or the atom is a
1177
+ * `staleTime` (`Atom.swr`) query that is stale or failed with no earlier success.
1178
+ *
1179
+ * Call it before the script's first `await` (for several atoms, in one `Promise.all`); an atom
1180
+ * read after that `await` runs again in the browser. See
1181
+ * [Call hooks before the first await](https://atom.jarrednorris.dev/hydration#call-hooks-before-the-first-await).
1182
+ *
1183
+ * With a getter, only the first atom is awaited: when the getter picks another atom the handle
1184
+ * follows it, starting from that atom's current result (often `Initial`), and the component's
1185
+ * await does not run again. On the server, an atom with a `withServerValue` override
1153
1186
  * reads as that value and is never computed. An atom that has not started, whose result is
1154
1187
  * `Initial` with nothing running, as an `Atom.fn` nothing has called, keeps the await pending in the
1155
1188
  * browser until something writes it; on the server, where nothing will during the render, the
@@ -1202,7 +1235,7 @@ export const useAtomResult = async (input, options) => {
1202
1235
  return value;
1203
1236
  }
1204
1237
  // On the server, an initial value is what the render shows, with nothing to wait for.
1205
- if (initialOnServer(registry, atom)) {
1238
+ if (initialOnServer(registry, atom, options?.suspendOnWaiting)) {
1206
1239
  release = serverMount(registry, atom);
1207
1240
  return value;
1208
1241
  }
@@ -1257,11 +1290,19 @@ const fromServerValue = (current, options) => {
1257
1290
  }
1258
1291
  };
1259
1292
  const suspend = async (registry, atom, current, options, signal) => {
1260
- if (isPending(current, options)) {
1293
+ // On the server, an initial value is what the render shows, as for useAtomResult: a waiting one
1294
+ // isn't waited for, even with suspendOnWaiting. Waiting would build the atom, running its read,
1295
+ // and the build keeps the initial value, so a synchronous result would be dropped and the wait
1296
+ // would never end (#106). A HydrationBoundary's waiting value isn't an initial value here (see
1297
+ // initialNodeOnServer).
1298
+ const waits = !BROWSER && initialOnServer(registry, atom, options.suspendOnWaiting)
1299
+ ? { ...options, suspendOnWaiting: false }
1300
+ : options;
1301
+ if (isPending(current, waits)) {
1261
1302
  if (!BROWSER && notStarted(current)) {
1262
1303
  throw notStartedError("useAtomSuspense");
1263
1304
  }
1264
- const exit = await awaitSettled(registry, atom, { suspendOnWaiting: options.suspendOnWaiting }, signal);
1305
+ const exit = await awaitSettled(registry, atom, { suspendOnWaiting: waits.suspendOnWaiting }, signal);
1265
1306
  // Abandoned: rejects with the reason its last reader's signal was aborted with. For a re-run
1266
1307
  // that is Svelte's STALE_REACTION, which it ignores, so a pending render that still awaits this
1267
1308
  // wait keeps waiting for its next run instead of showing the interruption (JND-22).
@@ -1,22 +1,10 @@
1
1
  <!--
2
2
  @component
3
- Hydrates dehydrated atom state, for example from `Hydration.dehydrate` returned by a remote
4
- function. Atoms new to the registry, or holding only an initial value nobody has read yet, are
5
- hydrated before children render; in the browser, atoms that already exist are updated after
6
- render, so current UI does not jump to the incoming data mid-render. On the server, where nothing
7
- renders again, and in the browser while it hydrates the server's markup, they are updated at once.
8
- That needs Svelte's `experimental.async`: without it, the browser can't tell that it is hydrating,
9
- and atoms that already exist, as one read above the boundary, are updated after the first render.
10
-
11
- With `experimental.async` on, custom server rendering must `await render(...)`, as SvelteKit does,
12
- so the boundary's `hydratable` entry is written into the page. Otherwise a production build of
13
- Svelte logs `hydratable_missing_but_expected` once per boundary as the page hydrates.
14
-
15
- A value for an atom nobody reads waits in the registry until something does. When the boundary
16
- is destroyed, as at the end of a server render, the values it brought that are still unread are
17
- dropped, as is a promise-encoded value that lands afterwards, so a registry that outlives the
18
- boundary doesn't hand them to a later reader. In the browser, a reader that already held the atom
19
- when the boundary ended and still holds it, as a layout's reader above it, gets the late value.
3
+ Puts the state from `Hydration.dehydrate` (returned by a `load` or remote function) into the
4
+ registry, for the components inside it.
5
+
6
+ Unlike the hooks, an effect or stream atom it hydrates runs again in the browser once read; set
7
+ `skipInitialRun: true` in `Atom.serializable` to keep the hydrated result.
20
8
 
21
9
  **Example** (Hydrating the state a load function dehydrated)
22
10
 
@@ -34,6 +22,25 @@
34
22
  <TodoList />
35
23
  </HydrationBoundary>
36
24
  ```
25
+
26
+ - **When atoms are updated.** Atoms new to the registry, or holding only an initial value nobody
27
+ has read yet, are hydrated before children render. In the browser, atoms that already exist are
28
+ updated after render, so current UI does not jump to the incoming data mid-render. On the
29
+ server, where nothing renders again, and in the browser while it hydrates the server's markup,
30
+ they are updated at once.
31
+ - **Without `experimental.async`.** The boundary still works, but can't update atoms that already
32
+ exist while the page hydrates: the browser can't tell that it is hydrating, so an atom that
33
+ already exists, as one read above the boundary, is updated after the first render.
34
+ - **Custom server rendering.** With `experimental.async` on, a server that renders the page
35
+ itself must `await render(...)`, as SvelteKit does, so the boundary's `hydratable` entry is
36
+ written into the page. Otherwise a production build of Svelte logs
37
+ `hydratable_missing_but_expected` once per boundary as the page hydrates.
38
+ - **Values nobody reads.** A value for an atom nobody reads waits in the registry until something
39
+ does. When the boundary is destroyed, as at the end of a server render, the values it brought
40
+ that are still unread are dropped, as is a promise-encoded value that lands afterwards, so a
41
+ registry that outlives the boundary doesn't hand them to a later reader. In the browser, a
42
+ reader that already held the atom when the boundary ended and still holds it, as a layout's
43
+ reader above it, gets the late value.
37
44
  -->
38
45
  <script lang="ts">
39
46
  import { Hydration } from "effect/reactivity";
@@ -5,23 +5,11 @@ interface Props {
5
5
  readonly children: Snippet;
6
6
  }
7
7
  /**
8
- * Hydrates dehydrated atom state, for example from `Hydration.dehydrate` returned by a remote
9
- * function. Atoms new to the registry, or holding only an initial value nobody has read yet, are
10
- * hydrated before children render; in the browser, atoms that already exist are updated after
11
- * render, so current UI does not jump to the incoming data mid-render. On the server, where nothing
12
- * renders again, and in the browser while it hydrates the server's markup, they are updated at once.
13
- * That needs Svelte's `experimental.async`: without it, the browser can't tell that it is hydrating,
14
- * and atoms that already exist, as one read above the boundary, are updated after the first render.
8
+ * Puts the state from `Hydration.dehydrate` (returned by a `load` or remote function) into the
9
+ * registry, for the components inside it.
15
10
  *
16
- * With `experimental.async` on, custom server rendering must `await render(...)`, as SvelteKit does,
17
- * so the boundary's `hydratable` entry is written into the page. Otherwise a production build of
18
- * Svelte logs `hydratable_missing_but_expected` once per boundary as the page hydrates.
19
- *
20
- * A value for an atom nobody reads waits in the registry until something does. When the boundary
21
- * is destroyed, as at the end of a server render, the values it brought that are still unread are
22
- * dropped, as is a promise-encoded value that lands afterwards, so a registry that outlives the
23
- * boundary doesn't hand them to a later reader. In the browser, a reader that already held the atom
24
- * when the boundary ended and still holds it, as a layout's reader above it, gets the late value.
11
+ * Unlike the hooks, an effect or stream atom it hydrates runs again in the browser once read; set
12
+ * `skipInitialRun: true` in `Atom.serializable` to keep the hydrated result.
25
13
  *
26
14
  * **Example** (Hydrating the state a load function dehydrated)
27
15
  *
@@ -39,6 +27,25 @@ interface Props {
39
27
  * <TodoList />
40
28
  * </HydrationBoundary>
41
29
  * ```
30
+ *
31
+ * - **When atoms are updated.** Atoms new to the registry, or holding only an initial value nobody
32
+ * has read yet, are hydrated before children render. In the browser, atoms that already exist are
33
+ * updated after render, so current UI does not jump to the incoming data mid-render. On the
34
+ * server, where nothing renders again, and in the browser while it hydrates the server's markup,
35
+ * they are updated at once.
36
+ * - **Without `experimental.async`.** The boundary still works, but can't update atoms that already
37
+ * exist while the page hydrates: the browser can't tell that it is hydrating, so an atom that
38
+ * already exists, as one read above the boundary, is updated after the first render.
39
+ * - **Custom server rendering.** With `experimental.async` on, a server that renders the page
40
+ * itself must `await render(...)`, as SvelteKit does, so the boundary's `hydratable` entry is
41
+ * written into the page. Otherwise a production build of Svelte logs
42
+ * `hydratable_missing_but_expected` once per boundary as the page hydrates.
43
+ * - **Values nobody reads.** A value for an atom nobody reads waits in the registry until something
44
+ * does. When the boundary is destroyed, as at the end of a server render, the values it brought
45
+ * that are still unread are dropped, as is a promise-encoded value that lands afterwards, so a
46
+ * registry that outlives the boundary doesn't hand them to a later reader. In the browser, a
47
+ * reader that already held the atom when the boundary ended and still holds it, as a layout's
48
+ * reader above it, gets the late value.
42
49
  */
43
50
  declare const HydrationBoundary: import("svelte").Component<Props, {}, "">;
44
51
  type HydrationBoundary = ReturnType<typeof HydrationBoundary>;
@@ -140,16 +140,28 @@ export interface Inspector {
140
140
  * ```ts
141
141
  * import { getRegistry } from "effect-atom-svelte";
142
142
  * import { inspect } from "effect-atom-svelte/inspector";
143
+ * import type { Event } from "effect-atom-svelte/inspector";
144
+ * import { onMount } from "svelte";
143
145
  *
144
- * const events = [];
145
- * inspect(getRegistry()).subscribe((event) => events.push(event));
146
- * setInterval(() => {
147
- * for (const event of events.splice(0)) {
148
- * if (event._tag === "Built") {
149
- * console.log(event.node.atom.label?.[0], event.cause._tag);
146
+ * const registry = getRegistry();
147
+ *
148
+ * // In onMount, so the server's registries aren't watched.
149
+ * onMount(() => {
150
+ * const inspector = inspect(registry);
151
+ * const queued: Event[] = [];
152
+ * const stop = inspector.subscribe((event) => queued.push(event));
153
+ * const timer = setInterval(() => {
154
+ * for (const event of queued.splice(0)) {
155
+ * if (event._tag === "Built") {
156
+ * console.log(event.node.atom.label?.[0], event.cause._tag);
157
+ * }
150
158
  * }
151
- * }
152
- * }, 1000);
159
+ * }, 1000);
160
+ * return () => {
161
+ * stop();
162
+ * clearInterval(timer);
163
+ * };
164
+ * });
153
165
  * ```
154
166
  *
155
167
  * @stability unstable
@@ -256,8 +268,9 @@ export interface ScopeSnapshot {
256
268
  /**
257
269
  * An event a scope passes on: the inspector's `Event` for a node in the scope, with the node's
258
270
  * `id`, or `ScopeChanged` once its atoms, edges or hooks have changed, after the registry's work,
259
- * to take a new `snapshot()`. A node's `NodeAdded` arrives before the node is linked into the
260
- * scope, so it isn't passed on; the `ScopeChanged` that follows is.
271
+ * to take a new `snapshot()`. Calling `snapshot()` in the listener is safe on a `ScopeChanged`;
272
+ * the other events arrive while the registry is still updating. A node's `NodeAdded` arrives before
273
+ * the node is linked into the scope, so it isn't passed on; the `ScopeChanged` that follows is.
261
274
  *
262
275
  * @stability unstable
263
276
  * @since 0.2.0
@@ -307,11 +320,14 @@ export interface InspectorScope {
307
320
  * const scope = provideInspectorScope();
308
321
  * $effect(() =>
309
322
  * scope.subscribe((event) => {
310
- * if (event._tag === "ScopeChanged") {
311
- * draw(scope.snapshot());
312
- * } else if (event._tag === "Updated") {
313
- * pulse(event.id);
314
- * }
323
+ * // Draw on the next frame: a listener mustn't write Svelte state.
324
+ * requestAnimationFrame(() => {
325
+ * if (event._tag === "ScopeChanged") {
326
+ * draw(scope.snapshot());
327
+ * } else if (event._tag === "Updated") {
328
+ * pulse(event.id);
329
+ * }
330
+ * });
315
331
  * })
316
332
  * );
317
333
  * ```
package/dist/Inspector.js CHANGED
@@ -252,16 +252,28 @@ const inspectors = new WeakMap();
252
252
  * ```ts
253
253
  * import { getRegistry } from "effect-atom-svelte";
254
254
  * import { inspect } from "effect-atom-svelte/inspector";
255
+ * import type { Event } from "effect-atom-svelte/inspector";
256
+ * import { onMount } from "svelte";
255
257
  *
256
- * const events = [];
257
- * inspect(getRegistry()).subscribe((event) => events.push(event));
258
- * setInterval(() => {
259
- * for (const event of events.splice(0)) {
260
- * if (event._tag === "Built") {
261
- * console.log(event.node.atom.label?.[0], event.cause._tag);
258
+ * const registry = getRegistry();
259
+ *
260
+ * // In onMount, so the server's registries aren't watched.
261
+ * onMount(() => {
262
+ * const inspector = inspect(registry);
263
+ * const queued: Event[] = [];
264
+ * const stop = inspector.subscribe((event) => queued.push(event));
265
+ * const timer = setInterval(() => {
266
+ * for (const event of queued.splice(0)) {
267
+ * if (event._tag === "Built") {
268
+ * console.log(event.node.atom.label?.[0], event.cause._tag);
269
+ * }
262
270
  * }
263
- * }
264
- * }, 1000);
271
+ * }, 1000);
272
+ * return () => {
273
+ * stop();
274
+ * clearInterval(timer);
275
+ * };
276
+ * });
265
277
  * ```
266
278
  *
267
279
  * @stability unstable
@@ -538,11 +550,14 @@ class Scope {
538
550
  * const scope = provideInspectorScope();
539
551
  * $effect(() =>
540
552
  * scope.subscribe((event) => {
541
- * if (event._tag === "ScopeChanged") {
542
- * draw(scope.snapshot());
543
- * } else if (event._tag === "Updated") {
544
- * pulse(event.id);
545
- * }
553
+ * // Draw on the next frame: a listener mustn't write Svelte state.
554
+ * requestAnimationFrame(() => {
555
+ * if (event._tag === "ScopeChanged") {
556
+ * draw(scope.snapshot());
557
+ * } else if (event._tag === "Updated") {
558
+ * pulse(event.id);
559
+ * }
560
+ * });
546
561
  * })
547
562
  * );
548
563
  * ```
@@ -11,7 +11,8 @@ import { AtomRegistry } from "effect/reactivity";
11
11
  * - `initialValues`: pairs of an atom and its starting value, such as `[[tokenAtom, token]]`. An
12
12
  * entry can take options as a third element, as `Atom.initialValue(atom, value, options)` makes:
13
13
  * `{ skipInitialRun: true }` keeps an effect or stream atom's value instead of running it on
14
- * mount.
14
+ * mount. The registry disposes of an atom nothing reads, starting value included, so give an
15
+ * atom that is read later `Atom.keepAlive`.
15
16
  * - `scheduleTask`: schedules the registry's deferred work, such as disposing of atoms nobody
16
17
  * reads. It takes a task and returns a function that cancels it.
17
18
  * - `defaultIdleTTL`: in milliseconds, how long an atom nobody reads is kept before it is disposed
@@ -26,7 +27,9 @@ import { AtomRegistry } from "effect/reactivity";
26
27
  */
27
28
  export type RegistryOptions = NonNullable<Parameters<typeof AtomRegistry.make>[0]>;
28
29
  /**
29
- * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`.
30
+ * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`. Call it while a
31
+ * component initializes, as Svelte reads context only then, and keep the registry it returns for
32
+ * later, such as for an event handler.
30
33
  *
31
34
  * In the browser a shared default registry is used when none is provided. On the server there is
32
35
  * no default: one module-level registry would share atom state between concurrent requests.
@@ -56,9 +59,11 @@ export declare const getRegistry: () => AtomRegistry.AtomRegistry;
56
59
  */
57
60
  export interface ProvideRegistryCommon {
58
61
  /**
59
- * Run server-rendered async atoms again once the page has hydrated. Defaults to `false`: the
60
- * server's value is milliseconds old. Children inherit it; the async hooks' own option overrides
61
- * it. `@effect/atom-react` runs every hydrated effect or stream atom again unless the atom sets
62
+ * Run server-rendered async atoms again once the page has hydrated. Defaults to `false`: on a
63
+ * page rendered per request the server's result is milliseconds old. Set it on a prerendered
64
+ * page, whose results are as old as the build. It applies to atoms the hooks hydrate, not to a
65
+ * `HydrationBoundary`'s. Children inherit it; the async hooks' own option overrides it.
66
+ * `@effect/atom-react` runs every hydrated effect or stream atom again unless the atom sets
62
67
  * `skipInitialRun`.
63
68
  */
64
69
  readonly revalidateOnHydrate?: boolean | undefined;
@@ -14,7 +14,9 @@ import { troubleshooting } from "./internal/troubleshooting.js";
14
14
  const [getContextRegistry, setContextRegistry, hasContextRegistry] = createContext();
15
15
  let browserRegistry;
16
16
  /**
17
- * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`.
17
+ * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`. Call it while a
18
+ * component initializes, as Svelte reads context only then, and keep the registry it returns for
19
+ * later, such as for an event handler.
18
20
  *
19
21
  * In the browser a shared default registry is used when none is provided. On the server there is
20
22
  * no default: one module-level registry would share atom state between concurrent requests.
@@ -4,7 +4,8 @@
4
4
  browser one per mount of the provider, disposed of when it unmounts. A root layout's provider
5
5
  stays mounted, so its registry lasts the whole visit. Takes the AtomRegistry.make options, or an
6
6
  existing `registry`, and `revalidateOnHydrate` to run server-rendered async atoms again once the
7
- page has hydrated.
7
+ page has hydrated. `revalidateOnHydrate` applies to atoms the hooks hydrate, not to a
8
+ `HydrationBoundary`'s.
8
9
 
9
10
  The props are read once, when the provider sets up: changing them later doesn't change the
10
11
  registry or create a new one. Development builds warn when `registry` or `revalidateOnHydrate`
@@ -8,7 +8,8 @@ type Props = ProvideRegistryOptions & {
8
8
  * browser one per mount of the provider, disposed of when it unmounts. A root layout's provider
9
9
  * stays mounted, so its registry lasts the whole visit. Takes the AtomRegistry.make options, or an
10
10
  * existing `registry`, and `revalidateOnHydrate` to run server-rendered async atoms again once the
11
- * page has hydrated.
11
+ * page has hydrated. `revalidateOnHydrate` applies to atoms the hooks hydrate, not to a
12
+ * `HydrationBoundary`'s.
12
13
  *
13
14
  * The props are read once, when the provider sets up: changing them later doesn't change the
14
15
  * registry or create a new one. Development builds warn when `registry` or `revalidateOnHydrate`
@@ -50,8 +50,9 @@ export interface MakeOptions {
50
50
  * Creates a scoped atom from a factory, which runs once per providing component.
51
51
  *
52
52
  * Each provider gets its own atom, so a factory that makes a serializable atom gives every copy of
53
- * one input the same key, and two such providers on a server-rendered page make the render throw:
54
- * two different atoms share the serialization key. For a value from the server, return a family's
53
+ * one input the same key: two providers given the same input make two atoms with one key, and the
54
+ * server render throws once both are read with `useAtomResult` or `useAtomSuspense`. For a value
55
+ * from the server, return a family's
55
56
  * atom instead, `ScopedAtom.make((id: string) => userAtom(id))`, so every provider of one input
56
57
  * holds the same atom.
57
58
  *
@@ -13,8 +13,9 @@ export const TypeId = "~effect-atom-svelte/ScopedAtom";
13
13
  * Creates a scoped atom from a factory, which runs once per providing component.
14
14
  *
15
15
  * Each provider gets its own atom, so a factory that makes a serializable atom gives every copy of
16
- * one input the same key, and two such providers on a server-rendered page make the render throw:
17
- * two different atoms share the serialization key. For a value from the server, return a family's
16
+ * one input the same key: two providers given the same input make two atoms with one key, and the
17
+ * server render throws once both are read with `useAtomResult` or `useAtomSuspense`. For a value
18
+ * from the server, return a family's
18
19
  * atom instead, `ScopedAtom.make((id: string) => userAtom(id))`, so every provider of one input
19
20
  * holds the same atom.
20
21
  *
@@ -32,6 +32,11 @@ export interface EffectErrorBody {
32
32
  /**
33
33
  * SvelteKit 2's `handleError` input: no `kind`, and always a message, which the hooks fall back on.
34
34
  *
35
+ * The hooks take the fields of SvelteKit's input they read and return the fields they set, so they
36
+ * type-check against `HandleClientError` and `HandleServerError` once `App.Error` declares
37
+ * `tag?: string`. In SvelteKit 2, whose `App.Error` requires a message, they are typed to return
38
+ * one for this input, as they then always set one.
39
+ *
35
40
  * @stability unstable
36
41
  * @since 0.2.1
37
42
  * @category models
@@ -73,8 +78,8 @@ export declare function handleClientError(input: CaughtError): EffectErrorBody |
73
78
  /**
74
79
  * A server `handleError` hook (`src/hooks.server.ts`) that keeps the `_tag` of errors thrown by
75
80
  * your code but not their message, which could expose details of the server to users: the
76
- * message stays SvelteKit's `"Internal Error"`. It logs errors with `console.error`.
77
- * Server errors reach a boundary's `failed` snippet when it renders on the server. Made for
81
+ * message stays SvelteKit's `"Internal Error"`. It logs each error with `console.error`, and the
82
+ * error reaches a boundary's `failed` snippet when that boundary renders on the server. Made for
78
83
  * SvelteKit 3: SvelteKit 2 doesn't say which errors are its own, so there every error is logged.
79
84
  *
80
85
  * **Example** (Using it as the server hook)
@@ -128,7 +133,6 @@ export interface UnsavedChangesGuardOptions {
128
133
  * });
129
134
  * ```
130
135
  *
131
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
132
136
  * @stability unstable
133
137
  * @since 0.4.0
134
138
  * @category forms
@@ -217,7 +221,6 @@ export type RemoteLiveQueryLike<A> = PromiseLike<A> & RemoteQueryState<A> & {
217
221
  * </script>
218
222
  * ```
219
223
  *
220
- * @see {@link https://atom.jarrednorris.dev/sveltekit#remote-queries-as-atoms | Remote queries as atoms}
221
224
  * @stability unstable
222
225
  * @since 0.5.0
223
226
  * @category remote functions
package/dist/SvelteKit.js CHANGED
@@ -2,11 +2,7 @@
2
2
  * SvelteKit helpers. Import them from `effect-atom-svelte/sveltekit`.
3
3
  *
4
4
  * `handleClientError` and `handleServerError` are `handleError` hooks that keep an Effect error's
5
- * `_tag`, so a `<svelte:boundary>` `failed` snippet can tell typed errors apart. They take the
6
- * fields of SvelteKit's input they read and return the fields they set, so they type-check against
7
- * `HandleClientError` and `HandleServerError` once `App.Error` declares `tag?: string`. In
8
- * SvelteKit 2, whose `App.Error` requires a message, they are typed to return one when there is no
9
- * `kind`, as they then always set one.
5
+ * `_tag`, so a `<svelte:boundary>` `failed` snippet can tell typed errors apart.
10
6
  *
11
7
  * `useUnsavedChangesGuard` asks before leaving a page with a dirty form.
12
8
  *
@@ -112,7 +108,6 @@ const bypassFor = 2000;
112
108
  * });
113
109
  * ```
114
110
  *
115
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
116
111
  * @stability unstable
117
112
  * @since 0.4.0
118
113
  * @category forms
@@ -280,7 +275,6 @@ const refreshQuery = (resource) => {
280
275
  * </script>
281
276
  * ```
282
277
  *
283
- * @see {@link https://atom.jarrednorris.dev/sveltekit#remote-queries-as-atoms | Remote queries as atoms}
284
278
  * @stability unstable
285
279
  * @since 0.5.0
286
280
  * @category remote functions
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, scoped atoms,
3
- * and Effect Atom's own modules.
2
+ * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, forms, scoped
3
+ * atoms, and Effect Atom's own modules.
4
4
  *
5
5
  * @since 0.1.0
6
6
  */
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, scoped atoms,
3
- * and Effect Atom's own modules.
2
+ * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, forms, scoped
3
+ * atoms, and Effect Atom's own modules.
4
4
  *
5
5
  * @since 0.1.0
6
6
  */
@@ -1,6 +1,6 @@
1
1
  // The one place the inspector (../Inspector.ts) relies on how Effect implements AtomRegistry rather
2
- // than on its public API. Written against effect 4.0.1 and checked against 4.1.7 (effect/src/reactivity/AtomRegistry.ts);
3
- // the peer range is ~4.1.0 because of code like this.
2
+ // than on its public API. Written against effect 4.0.1 and checked against 4.1.7 and 4.2.0 (effect/src/reactivity/AtomRegistry.ts);
3
+ // the peer range lists each minor (~4.1.0 || ~4.2.0) because of code like this.
4
4
  //
5
5
  // The public `AtomRegistry` announces nodes added and removed (`onNodeAdded`, `onNodeRemoved`), and
6
6
  // a `Node` shows its parents, children and listeners. It says nothing when a node's value changes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-atom-svelte",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Community-built Svelte 5 bindings for Effect Atom (not affiliated with the Effect team)",
5
5
  "keywords": [
6
6
  "effect",
@@ -59,7 +59,7 @@
59
59
  "@types/bun": "^1.4.2",
60
60
  "@vitest/browser": "^5.0.5",
61
61
  "@vitest/browser-playwright": "^5.0.5",
62
- "effect": "4.1.7",
62
+ "effect": "4.2.0",
63
63
  "playwright": "^1.57.0",
64
64
  "svelte": "^5.59.2",
65
65
  "svelte-check": "^4.7.8",
@@ -70,7 +70,7 @@
70
70
  },
71
71
  "peerDependencies": {
72
72
  "@sveltejs/kit": "^2.0.0 || ^3.0.0",
73
- "effect": "~4.1.0",
73
+ "effect": "~4.1.0 || ~4.2.0",
74
74
  "svelte": "^5.57.2"
75
75
  },
76
76
  "peerDependenciesMeta": {