effect-atom-svelte 0.4.1 → 0.5.0

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/dist/SvelteKit.js CHANGED
@@ -10,11 +10,20 @@
10
10
  *
11
11
  * `useUnsavedChangesGuard` asks before leaving a page with a dirty form.
12
12
  *
13
+ * `remoteQueryAtom` turns a SvelteKit remote `query` or `query.live` into an atom that follows it.
14
+ *
13
15
  * @since 0.1.0
14
16
  */
15
- /// <reference types="@sveltejs/kit" />
16
17
  import { beforeNavigate, goto } from "$app/navigation";
17
- import { Effect } from "effect";
18
+ import { isHttpError, VERSION } from "@sveltejs/kit";
19
+ import { Cause, Effect, Option } from "effect";
20
+ import { AsyncResult, Atom } from "effect/reactivity";
21
+ import { BROWSER } from "esm-env";
22
+ import { untrack } from "svelte";
23
+ import { follow } from "./internal/follow.svelte.js";
24
+ import { assertSupportedKit } from "./internal/kitVersion.js";
25
+ import { markRemoteQueryAtom } from "./internal/remoteQueries.js";
26
+ import { troubleshooting } from "./internal/troubleshooting.js";
18
27
  const tagOf = (error) => {
19
28
  if (typeof error !== "object" || error === null || !("_tag" in error)) {
20
29
  return undefined;
@@ -167,3 +176,160 @@ export const useUnsavedChangesGuard = (form, options) => {
167
176
  })();
168
177
  });
169
178
  };
179
+ const notAQuery = (value) => {
180
+ const returned = typeof value === "object" && value !== null && "ready" in value
181
+ ? "a resource without refresh or reconnect, as from a prerender function"
182
+ : Object.prototype.toString.call(value);
183
+ return new Error(`remoteQueryAtom's function must return a remote query or query.live, as in remoteQueryAtom(() => getTodos()), and it returned ${returned}. ${troubleshooting("remotequeryatoms-function-must-return-a-remote-query")}`);
184
+ };
185
+ // A remote query or query.live has its state fields and a way to fetch again; a prerender
186
+ // function's result has no refresh.
187
+ const isRemoteResource = (value) => {
188
+ if (typeof value !== "object" || value === null) {
189
+ return false;
190
+ }
191
+ return "ready" in value && ("refresh" in value || "reconnect" in value);
192
+ };
193
+ const checked = (value) => {
194
+ if (!isRemoteResource(value)) {
195
+ throw notAQuery(value);
196
+ }
197
+ return value;
198
+ };
199
+ // SvelteKit's own body for an error, when its `handleError` hook adds nothing: an `error(...)`'s
200
+ // body, or a 500. The hook can't be run from here, so this is what the server render holds.
201
+ const defaultBody = (error) => isHttpError(error) ? error.body : { message: "Internal Error", status: 500 };
202
+ // The query's state, as a result. An error wins over a value: SvelteKit keeps the last value when a
203
+ // refresh fails, and that value becomes the failure's previous success.
204
+ const toResult = (resource) => {
205
+ const { error, loading } = resource;
206
+ if (error !== undefined) {
207
+ return AsyncResult.fail(error, {
208
+ previousSuccess: resource.ready
209
+ ? Option.some(AsyncResult.success(resource.current))
210
+ : Option.none(),
211
+ waiting: loading,
212
+ });
213
+ }
214
+ if (!resource.ready) {
215
+ return AsyncResult.initial(loading);
216
+ }
217
+ return AsyncResult.success(resource.current, { waiting: loading });
218
+ };
219
+ // Whether two results show the same state, so a run of the effect that changed nothing the atom
220
+ // holds doesn't notify its readers.
221
+ const sameResult = (a, b) => {
222
+ if (a._tag !== b._tag || a.waiting !== b.waiting) {
223
+ return false;
224
+ }
225
+ if (a._tag === "Success" && b._tag === "Success") {
226
+ return a.value === b.value;
227
+ }
228
+ if (a._tag === "Failure" && b._tag === "Failure") {
229
+ return (Cause.squash(a.cause) === Cause.squash(b.cause) &&
230
+ Option.getOrUndefined(a.previousSuccess)?.value ===
231
+ Option.getOrUndefined(b.previousSuccess)?.value);
232
+ }
233
+ return true;
234
+ };
235
+ const refreshQuery = (resource) => {
236
+ if ("refresh" in resource) {
237
+ void resource.refresh();
238
+ }
239
+ else {
240
+ void resource.reconnect();
241
+ }
242
+ };
243
+ /**
244
+ * Turns a SvelteKit remote `query` or `query.live` into an atom of its result, which follows every
245
+ * change SvelteKit makes to the query: a refresh, a `.set()`, a command's single-flight update, an
246
+ * optimistic `withOverride` and a live push. Pass a function that calls the query, so the atom calls
247
+ * it in each server render and in the browser. Needs SvelteKit 3 with
248
+ * `experimental.remoteFunctions`.
249
+ *
250
+ * - *Server.* The render calls the query, so SvelteKit sends its result with the page and the
251
+ * browser starts from it without fetching again. Read the atom with `await useAtomResult` or
252
+ * `useAtomSuspense`: `useAtomValue` renders `Initial` on the server, and warns in development.
253
+ * Under a `<svelte:boundary>` with a `pending` snippet, the server renders that, and the browser
254
+ * fetches the query.
255
+ * - *Refresh.* `useAtomRefresh` and `registry.refresh` call the query's `refresh()`, or
256
+ * `reconnect()` for a live query, and the atom is `waiting` until the new value arrives.
257
+ * - *Failure.* A failure holds SvelteKit's `App.Error`, as `handleError` returned it in the
258
+ * browser. On the server it holds SvelteKit's default body, as the library can't run your hook,
259
+ * so a hook that adds fields to it changes the failure between the server's HTML and the browser.
260
+ * - *Arguments.* For a query that takes one, make a family:
261
+ * `Atom.family((id: string) => remoteQueryAtom(() => getTodo(id)))`.
262
+ *
263
+ * **Example** (A todo list from a remote query)
264
+ *
265
+ * ```ts
266
+ * // src/routes/todos/atoms.ts
267
+ * import { remoteQueryAtom } from "effect-atom-svelte/sveltekit";
268
+ * import { getTodos } from "./todos.remote.ts";
269
+ *
270
+ * export const todosAtom = remoteQueryAtom(() => getTodos());
271
+ * ```
272
+ *
273
+ * ```svelte
274
+ * <script lang="ts">
275
+ * import { useAtomRefresh, useAtomResult } from "effect-atom-svelte";
276
+ * import { todosAtom } from "./atoms.ts";
277
+ *
278
+ * const todos = await useAtomResult(todosAtom);
279
+ * const refresh = useAtomRefresh(todosAtom);
280
+ * </script>
281
+ * ```
282
+ *
283
+ * @see {@link https://atom.jarrednorris.dev/sveltekit#remote-queries-as-atoms | Remote queries as atoms}
284
+ * @stability unstable
285
+ * @since 0.5.0
286
+ * @category remote functions
287
+ */
288
+ export const remoteQueryAtom = (query) => {
289
+ assertSupportedKit(VERSION);
290
+ const atom = BROWSER
291
+ ? Atom.readable((get) => {
292
+ const resource = checked(query());
293
+ // Read untracked, so a reactive context the registry reads this in doesn't follow the query.
294
+ let last = untrack(() => toResult(resource));
295
+ let live = true;
296
+ const sync = () => {
297
+ if (!live) {
298
+ return;
299
+ }
300
+ const next = untrack(() => toResult(resource));
301
+ if (!sameResult(last, next)) {
302
+ last = next;
303
+ get.setSelf(next);
304
+ }
305
+ };
306
+ const stop = follow(() => toResult(resource), sync);
307
+ // A navigation renders the next page in a fork, whose effects wait for it to commit, while
308
+ // the fork waits for this atom: settle a pending first result through the query's promise.
309
+ if (last._tag === "Initial" || last.waiting) {
310
+ // A failed fetch is in the query's state too, so either way sync reads it from there.
311
+ Effect.runFork(Effect.promise(() => Promise.resolve(resource)).pipe(Effect.exit, Effect.andThen(Effect.sync(sync))));
312
+ }
313
+ get.addFinalizer(() => {
314
+ live = false;
315
+ stop();
316
+ });
317
+ return last;
318
+ },
319
+ // Asks SvelteKit to fetch again, rather than building the atom again.
320
+ () => {
321
+ refreshQuery(checked(query()));
322
+ })
323
+ : Atom.make(
324
+ // Called as the render reads the atom, so SvelteKit sends the result with the page. A
325
+ // function that returns no query is a defect, not the query's failure.
326
+ Effect.suspend(() => {
327
+ const resource = checked(query());
328
+ return Effect.tryPromise({
329
+ catch: defaultBody,
330
+ try: () => Promise.resolve(resource),
331
+ });
332
+ }));
333
+ markRemoteQueryAtom(atom);
334
+ return atom;
335
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Runs `read` in a pre effect of its own root, so it is owned by no component, and calls `changed`
3
+ * after every run, untracked. Returns the function that stops it. The effect's first run waits for
4
+ * Svelte's next flush, and during a navigation's fork for the fork to commit, so a caller that needs
5
+ * a value sooner reads it itself.
6
+ */
7
+ export declare const follow: (read: () => void, changed: () => void) => (() => void);
@@ -0,0 +1,15 @@
1
+ // Follows Svelte state that lives outside any component, such as a SvelteKit remote query's.
2
+ // Internal: not exported from the package.
3
+ import { untrack } from "svelte";
4
+ /**
5
+ * Runs `read` in a pre effect of its own root, so it is owned by no component, and calls `changed`
6
+ * after every run, untracked. Returns the function that stops it. The effect's first run waits for
7
+ * Svelte's next flush, and during a navigation's fork for the fork to commit, so a caller that needs
8
+ * a value sooner reads it itself.
9
+ */
10
+ export const follow = (read, changed) => $effect.root(() => {
11
+ $effect.pre(() => {
12
+ read();
13
+ untrack(changed);
14
+ });
15
+ });
@@ -15,15 +15,18 @@ import { equals, fromPathId, getIn, idSuffix, isLive, pathId, reconcileKeys, set
15
15
  import { FormValidationError } from "./validationError.js";
16
16
  const ROOT = pathId([]);
17
17
  const notChecked = Symbol("notChecked");
18
- const freshState = (initial, keys) => ({
18
+ const freshState = (initial, keys, initialKeys = keys) => ({
19
19
  checked: notChecked,
20
+ checkedKeys: new Map(),
20
21
  decoded: Option.none(),
21
22
  external: new Map(),
22
23
  failure: undefined,
23
24
  initial,
25
+ initialKeys,
24
26
  issues: new Map(),
25
27
  keys,
26
28
  lastSubmitted: Option.none(),
29
+ lastSubmittedKeys: new Map(),
27
30
  revealed: new Set(),
28
31
  shown: new Set(),
29
32
  submitCount: 0,
@@ -65,6 +68,7 @@ export class Engine {
65
68
  #original;
66
69
  // The values the latest validation run decodes.
67
70
  #runValues;
71
+ #runKeys = new Map();
68
72
  #readState;
69
73
  #readValues;
70
74
  #nextKey = 0;
@@ -102,7 +106,9 @@ export class Engine {
102
106
  Atom.make(options.initialValues).pipe(Atom.withLabel(`${name}.values`));
103
107
  const values = registry.get(this.valuesAtom);
104
108
  const keys = reconcileKeys(values, new Map(), () => this.#key());
105
- this.stateAtom = Atom.make(freshState(options.initialValues, keys)).pipe(Atom.withLabel(`${name}.state`));
109
+ // Paired with the values' items by position: the same keys when they are the initial values.
110
+ const initialKeys = reconcileKeys(options.initialValues, keys, () => this.#key());
111
+ this.stateAtom = Atom.make(freshState(options.initialValues, keys, initialKeys)).pipe(Atom.withLabel(`${name}.state`));
106
112
  this.#seen = { keys, values };
107
113
  const decode = Schema.decodeUnknownEffect(codecOf(definition));
108
114
  const run = (input) => decode(input.values, { errors: "all" }).pipe(Effect.map((decoded) => ({ _tag: "Valid", decoded, input })), Effect.catchTag("SchemaError", (failure) => Effect.succeed({
@@ -119,6 +125,8 @@ export class Engine {
119
125
  this.#readValues = () => registry.get(this.valuesAtom);
120
126
  this.#releases.push(registry.mount(this.stateAtom), registry.subscribe(this.valuesAtom, (next) => {
121
127
  this.#onValues(next);
128
+ }), onDispose(registry, () => {
129
+ this.#registryDisposed();
122
130
  }));
123
131
  if (options.validates) {
124
132
  this.#releases.push(registry.subscribe(this.#validateAtom, (result) => {
@@ -189,7 +197,8 @@ export class Engine {
189
197
  }
190
198
  const live = (ids) => new Set([...ids].filter((id) => id === ROOT || isLive(keys, fromPathId(id))));
191
199
  this.#seen = { keys, values: next };
192
- // Fields of items that are gone can't come back: their keys are never reused.
200
+ // Fields of items that are gone are dropped. Only a revert brings an item's key back, and its
201
+ // fields are made again.
193
202
  for (const cache of [this.#fields, this.#groups, this.#arrays]) {
194
203
  for (const id of cache.keys()) {
195
204
  if (!isLive(keys, fromPathId(id))) {
@@ -271,10 +280,26 @@ export class Engine {
271
280
  }
272
281
  const clean = equals(this.#currentValues(), state.initial);
273
282
  this.#original = initial;
274
- this.#update((latest) => ({ ...latest, initial }));
275
283
  if (clean) {
284
+ // The values become the new initial values, item for item: both take the current keys,
285
+ // set before the values as `updateArray` does, so the write keeps them.
286
+ const keys = reconcileKeys(initial, state.keys, () => this.#key());
287
+ this.#update((latest) => ({
288
+ ...latest,
289
+ initial,
290
+ initialKeys: keys,
291
+ keys,
292
+ }));
276
293
  this.registry.set(this.valuesAtom, initial);
294
+ return;
277
295
  }
296
+ // The edits stay: each new initial item replaces the old one at its position, so an item the
297
+ // user moved or kept compares with its new initial value.
298
+ this.#update((latest) => ({
299
+ ...latest,
300
+ initial,
301
+ initialKeys: reconcileKeys(initial, latest.initialKeys, () => this.#key()),
302
+ }));
278
303
  }
279
304
  reset(values) {
280
305
  if (values !== undefined) {
@@ -298,6 +323,7 @@ export class Engine {
298
323
  ? {
299
324
  ...fresh,
300
325
  lastSubmitted: state.lastSubmitted,
326
+ lastSubmittedKeys: state.lastSubmittedKeys,
301
327
  submitResult: state.submitResult,
302
328
  }
303
329
  : fresh);
@@ -308,10 +334,21 @@ export class Engine {
308
334
  revertToLastSubmit() {
309
335
  this.#editing = undefined;
310
336
  const state = this.#current();
311
- this.registry.set(this.valuesAtom, Option.match(state.lastSubmitted, {
312
- onNone: () => state.initial,
313
- onSome: ({ encoded }) => encoded,
314
- }));
337
+ const [values, keys] = Option.match(state.lastSubmitted, {
338
+ onNone: () => [state.initial, state.initialKeys],
339
+ onSome: ({ encoded }) => [encoded, state.lastSubmittedKeys],
340
+ });
341
+ // The items come back with the keys they had, set before the values as `updateArray` does: an
342
+ // item still there keeps its key and touched state, and each compares with its own initial
343
+ // value again. Paired by position instead, a remove or move before it left every item dirty.
344
+ this.#update((latest) => ({ ...latest, keys }));
345
+ const seen = this.#seen;
346
+ this.registry.set(this.valuesAtom, values);
347
+ // The registry drops a write of the values already there, but the keys changed: the checks
348
+ // and touched state must follow them all the same.
349
+ if (this.#seen === seen) {
350
+ this.#onValues(this.#currentValues());
351
+ }
315
352
  }
316
353
  setErrors(errors, source) {
317
354
  const state = this.#current();
@@ -373,8 +410,9 @@ export class Engine {
373
410
  }
374
411
  this.#token += 1;
375
412
  this.#runValues = this.#currentValues();
413
+ this.#runKeys = this.#current().keys;
376
414
  this.registry.set(this.#validateAtom, {
377
- keys: this.#current().keys,
415
+ keys: this.#runKeys,
378
416
  token: this.#token,
379
417
  values: this.#runValues,
380
418
  });
@@ -388,9 +426,11 @@ export class Engine {
388
426
  // field is unchecked, so the form isn't valid.
389
427
  console.error("effect-atom-svelte: a form's validation failed", Cause.pretty(result.cause));
390
428
  const values = this.#runValues;
429
+ const keys = this.#runKeys;
391
430
  this.#update((state) => ({
392
431
  ...state,
393
432
  checked: values,
433
+ checkedKeys: keys,
394
434
  decoded: Option.none(),
395
435
  failure: result.cause,
396
436
  validating: false,
@@ -420,6 +460,7 @@ export class Engine {
420
460
  this.#update((state) => ({
421
461
  ...state,
422
462
  checked: run.input.values,
463
+ checkedKeys: run.input.keys,
423
464
  decoded: run._tag === "Valid" ? Option.some(run.decoded) : Option.none(),
424
465
  failure: undefined,
425
466
  issues,
@@ -530,6 +571,9 @@ export class Engine {
530
571
  */
531
572
  // oxlint-disable-next-line effecttsgo/async-function -- the form's validate, part of the library's Promise-facing API for Svelte handlers
532
573
  async validate(paths) {
574
+ if (this.#disposed) {
575
+ return false;
576
+ }
533
577
  const state = this.#current();
534
578
  const keyPaths = paths === undefined
535
579
  ? undefined
@@ -549,6 +593,9 @@ export class Engine {
549
593
  }));
550
594
  this.#retryFailed();
551
595
  await this.#settled();
596
+ if (this.#disposed) {
597
+ return false;
598
+ }
552
599
  if (this.#isCurrent()) {
553
600
  this.#reveal(true);
554
601
  }
@@ -610,7 +657,8 @@ export class Engine {
610
657
  }));
611
658
  this.#retryFailed();
612
659
  await this.#settled();
613
- if (session !== this.#session) {
660
+ // A reset let go of this submit, or the registry is gone: nothing is sent.
661
+ if (session !== this.#session || this.#disposed) {
614
662
  return Exit.interrupt();
615
663
  }
616
664
  if (this.options.validates) {
@@ -621,18 +669,14 @@ export class Engine {
621
669
  const encoded = this.options.validates
622
670
  ? state.checked
623
671
  : this.#currentValues();
672
+ const encodedKeys = this.options.validates ? state.checkedKeys : state.keys;
624
673
  let decoded;
625
674
  if (this.options.validates) {
626
675
  // The decode couldn't run at all: there is nothing to send.
627
676
  if (state.failure !== undefined) {
628
677
  // Not the user's input, and nothing claims it: a defect, as the error a runtime failed with
629
678
  // isn't in the submit's error type. The app shows it, as for any defect.
630
- const cause = Cause.die(Cause.squash(state.failure));
631
- this.#update((latest) => ({
632
- ...latest,
633
- submitResult: AsyncResult.failure(cause),
634
- }));
635
- return Exit.failCause(cause);
679
+ return this.#failed(session, Cause.die(Cause.squash(state.failure)));
636
680
  }
637
681
  if (state.issues.size > 0 || Option.isNone(state.decoded)) {
638
682
  return Exit.fail(new FormValidationError({ errors: this.root.errors }));
@@ -651,43 +695,42 @@ export class Engine {
651
695
  }
652
696
  const target = this.options.submit;
653
697
  if (target === undefined) {
654
- this.#succeeded(session, encoded, decoded, decoded);
698
+ this.#succeeded(session, { encoded, encodedKeys }, decoded, decoded);
655
699
  return Exit.succeed(decoded);
656
700
  }
657
- const atom = target.atom();
658
- const value = target.payload ? target.payload(decoded, args) : decoded;
659
- this.#update((latest) => ({
660
- ...latest,
661
- submitResult: AsyncResult.waiting(latest.submitResult),
662
- submitting: true,
663
- }));
664
- // oxlint-disable-next-line effecttsgo/global-date -- compared with an AsyncResult's timestamp, which Effect takes from Date.now
665
- const start = Date.now();
666
- this.registry.set(atom, value);
667
- // The wait holds the atom, so the call finishes after the component is gone, unless the
668
- // registry itself is disposed of, which ends it as interrupted.
669
- const controller = new AbortController();
670
- const cancel = onDispose(this.registry, () => {
671
- controller.abort();
672
- });
673
701
  let exit;
674
702
  try {
675
- exit = await awaitWrite(this.registry, atom, start, controller.signal);
703
+ exit = await this.#send(target, decoded, args);
676
704
  }
677
- finally {
678
- cancel();
705
+ catch (error) {
706
+ // The payload, or the atom's write (as for an Atom.fn that throws before returning its
707
+ // Effect), threw: a defect, which ends the submit as a failed save does.
708
+ return this.#failed(session, Cause.die(error));
679
709
  }
680
- if (session !== this.#session) {
710
+ if (session !== this.#session || this.#disposed) {
681
711
  return exit;
682
712
  }
683
713
  if (Exit.isSuccess(exit)) {
684
- this.#succeeded(session, encoded, decoded, exit.value);
714
+ this.#succeeded(session, { encoded, encodedKeys }, decoded, exit.value);
685
715
  return exit;
686
716
  }
687
- const error = Cause.findErrorOption(exit.cause);
688
- const claimed = Option.isSome(error) && this.options.mapError
689
- ? this.options.mapError(error.value)
690
- : undefined;
717
+ return this.#saveFailed(session, exit);
718
+ }
719
+ // A failed save: mapError may claim its error onto fields or the form; otherwise it shows in
720
+ // submitResult.
721
+ #saveFailed(session, exit) {
722
+ const failure = Cause.findErrorOption(exit.cause);
723
+ let claimed;
724
+ try {
725
+ claimed =
726
+ Option.isSome(failure) && this.options.mapError
727
+ ? this.options.mapError(failure.value)
728
+ : undefined;
729
+ }
730
+ catch (error) {
731
+ // The save's failure stays, with the throw beside it as a defect.
732
+ return this.#failed(session, Cause.combine(exit.cause, Cause.die(error)));
733
+ }
691
734
  if (claimed !== undefined) {
692
735
  this.setErrors(claimed, "submit");
693
736
  }
@@ -707,15 +750,58 @@ export class Engine {
707
750
  }
708
751
  return exit;
709
752
  }
710
- #succeeded(session, encoded, decoded, value) {
711
- if (session !== this.#session) {
753
+ // Writes the payload to the submit's atom and waits for the save's result.
754
+ // oxlint-disable-next-line effecttsgo/async-function -- behind the form's submit, part of the library's Promise-facing API for Svelte handlers
755
+ async #send(target, decoded, args) {
756
+ const atom = target.atom();
757
+ const value = target.payload ? target.payload(decoded, args) : decoded;
758
+ this.#update((latest) => ({
759
+ ...latest,
760
+ submitResult: AsyncResult.waiting(latest.submitResult),
761
+ submitting: true,
762
+ }));
763
+ // oxlint-disable-next-line effecttsgo/global-date -- compared with an AsyncResult's timestamp, which Effect takes from Date.now
764
+ const start = Date.now();
765
+ this.registry.set(atom, value);
766
+ // The wait holds the atom, so the call finishes after the component is gone, unless the
767
+ // registry itself is disposed of, which ends it as interrupted.
768
+ const controller = new AbortController();
769
+ const cancel = onDispose(this.registry, () => {
770
+ controller.abort();
771
+ });
772
+ try {
773
+ return await awaitWrite(this.registry, atom, start, controller.signal);
774
+ }
775
+ finally {
776
+ cancel();
777
+ }
778
+ }
779
+ // Ends a submit with a failure nothing claims: it shows in submitResult.
780
+ #failed(session, cause) {
781
+ if (session === this.#session) {
782
+ this.#update((latest) => ({
783
+ ...latest,
784
+ submitResult: AsyncResult.failure(cause),
785
+ submitting: false,
786
+ }));
787
+ }
788
+ return Exit.failCause(cause);
789
+ }
790
+ #succeeded(session, submitted, decoded, value) {
791
+ if (session !== this.#session || this.#disposed) {
712
792
  return;
713
793
  }
794
+ const { encoded, encodedKeys } = submitted;
714
795
  const lastSubmitted = Option.some({ decoded, encoded });
796
+ const adopt = this.options.resetOnSuccess !== true;
715
797
  this.#update((latest) => ({
716
798
  ...latest,
717
- initial: this.options.resetOnSuccess === true ? latest.initial : encoded,
799
+ // The submitted values become the initial ones, with the keys their items had: the items
800
+ // may have moved since.
801
+ initial: adopt ? encoded : latest.initial,
802
+ initialKeys: adopt ? encodedKeys : latest.initialKeys,
718
803
  lastSubmitted,
804
+ lastSubmittedKeys: encodedKeys,
719
805
  submitResult: AsyncResult.success(value),
720
806
  submitting: false,
721
807
  }));
@@ -835,4 +921,13 @@ export class Engine {
835
921
  }
836
922
  this.#releases = [];
837
923
  }
924
+ // The provider that owns the registry disposed of it, which drops the instance's atoms without
925
+ // telling them: the instance is done at once, even mid-submit, and what waited on a validation
926
+ // run stops waiting. There is nothing left to release.
927
+ #registryDisposed() {
928
+ this.#disposed = true;
929
+ clearTimeout(this.#timer);
930
+ this.#releases = [];
931
+ this.#release();
932
+ }
838
933
  }
@@ -1,4 +1,4 @@
1
- import { equals, getIn, nameOf, pathId } from "./paths.js";
1
+ import { equals, getIn, nameOf, pathId, toIndexPath } from "./paths.js";
2
2
  export class FieldImpl {
3
3
  #engine;
4
4
  keyPath;
@@ -32,9 +32,16 @@ export class FieldImpl {
32
32
  this.#engine.setTouched(this.keyPath, touched);
33
33
  }
34
34
  get dirty() {
35
- const index = this.#engine.indexPath(this.keyPath);
36
- return (index !== undefined &&
37
- !equals(getIn(this.#engine.values, index), getIn(this.#engine.state.initial, index)));
35
+ const { state } = this.#engine;
36
+ const index = toIndexPath(state.keys, this.keyPath);
37
+ if (index === undefined) {
38
+ return false;
39
+ }
40
+ // Under an array item, the initial value is that item's, wherever it was: by key, not index.
41
+ const initialIndex = toIndexPath(state.initialKeys, this.keyPath);
42
+ // An item added since (by append or replace) has no initial value.
43
+ return (initialIndex === undefined ||
44
+ !equals(getIn(this.#engine.values, index), getIn(state.initial, initialIndex)));
38
45
  }
39
46
  get validating() {
40
47
  return this.#engine.state.validating;
@@ -55,6 +55,11 @@ export interface ExternalError {
55
55
  export interface State {
56
56
  readonly initial: unknown;
57
57
  readonly keys: Keys;
58
+ /**
59
+ * Item keys for `initial`'s arrays, shared with `keys` for the items that are still there: a
60
+ * field compares with its own item's initial value, wherever the item has moved.
61
+ */
62
+ readonly initialKeys: Keys;
58
63
  readonly touched: ReadonlySet<string>;
59
64
  /** Schema errors on show, by path. A path drops out once its check passes. */
60
65
  readonly revealed: ReadonlySet<string>;
@@ -64,6 +69,8 @@ export interface State {
64
69
  readonly issues: ReadonlyMap<string, string>;
65
70
  /** The values that run decoded, to tell whether its result is current. */
66
71
  readonly checked: unknown;
72
+ /** The item keys of `checked`. */
73
+ readonly checkedKeys: Keys;
67
74
  readonly decoded: Option.Option<unknown>;
68
75
  /** Why the latest run couldn't decode at all (a defect, a runtime that failed), if it couldn't. */
69
76
  readonly failure: Cause.Cause<unknown> | undefined;
@@ -77,4 +84,6 @@ export interface State {
77
84
  readonly encoded: unknown;
78
85
  readonly decoded: unknown;
79
86
  }>;
87
+ /** The item keys of `lastSubmitted`'s encoded values. */
88
+ readonly lastSubmittedKeys: Keys;
80
89
  }
@@ -1,3 +1,4 @@
1
+ import { Schema } from "effect";
1
2
  import { AsyncResult } from "effect/reactivity";
2
3
  /** Sets the default for this component's children. Call during component init. */
3
4
  export declare const setRevalidateOnHydrate: (value: boolean) => void;
@@ -27,7 +28,7 @@ export declare const encodeSeed: (key: string, encode: (value: AsyncResult.Async
27
28
  * the browser's schema: the browser then computes the atom itself, as for a result the server
28
29
  * couldn't encode. Development builds warn.
29
30
  */
30
- export declare const decodeSeed: (key: string, value: unknown, decode: (value: unknown) => unknown) => unknown;
31
+ export declare const decodeSeed: (key: string, value: unknown, decode: (value: Schema.Json) => unknown) => unknown;
31
32
  /**
32
33
  * Whether a seed is still waiting, as a stream's result is between its values. The browser runs
33
34
  * the atom again from it, as the server's run ended with the render.
@@ -5,6 +5,7 @@ import { Cause, Schema } from "effect";
5
5
  import { AsyncResult } from "effect/reactivity";
6
6
  import { DEV } from "esm-env";
7
7
  import { createContext } from "svelte";
8
+ import { troubleshooting } from "./troubleshooting.js";
8
9
  const [getDefault, setDefault, hasDefault] = createContext();
9
10
  /** Sets the default for this component's children. Call during component init. */
10
11
  export const setRevalidateOnHydrate = (value) => {
@@ -45,7 +46,7 @@ export const encodeSeed = (key, encode, result) => {
45
46
  throw error;
46
47
  }
47
48
  if (DEV) {
48
- console.warn(`effect-atom-svelte: the result of the serializable atom "${key}" doesn't encode with its schema, so it isn't sent to the browser, which computes the atom again.`, error);
49
+ console.warn(`effect-atom-svelte: the result of the serializable atom "${key}" doesn't encode with its schema, so it isn't sent to the browser, which computes the atom again. ${troubleshooting("doesnt-encode-with-its-schema-so-it-isnt-sent-to-the-browser")}`, error);
49
50
  }
50
51
  return noSeed;
51
52
  }
@@ -60,6 +61,9 @@ export const decodeSeed = (key, value, decode) => {
60
61
  return undefined;
61
62
  }
62
63
  try {
64
+ // SAFETY: what the server's encode returned, sent through `hydratable`; decode checks it against
65
+ // the schema, and throws a schema error, handled below, for anything else.
66
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- hydratable types the value it returns as unknown
63
67
  return decode(value);
64
68
  }
65
69
  catch (error) {
@@ -67,7 +71,7 @@ export const decodeSeed = (key, value, decode) => {
67
71
  throw error;
68
72
  }
69
73
  if (DEV) {
70
- console.warn(`effect-atom-svelte: the server's result for the serializable atom "${key}" doesn't decode with its schema, so the browser computes the atom again.`, error);
74
+ console.warn(`effect-atom-svelte: the server's result for the serializable atom "${key}" doesn't decode with its schema, so the browser computes the atom again. ${troubleshooting("doesnt-decode-with-its-schema-so-the-browser-computes-the-atom-again")}`, error);
71
75
  }
72
76
  return undefined;
73
77
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Throws unless `version` is SvelteKit 3. Remote queries keep the state fields and promise that
3
+ * remoteQueryAtom follows from SvelteKit 3.0.0, and SvelteKit 4 may change them.
4
+ */
5
+ export declare const assertSupportedKit: (version: string) => void;