@thomasfosterau/effect-sveltekit 0.4.1 → 0.6.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.
Files changed (66) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +183 -85
  3. package/dist/Hooks.d.ts +1 -1
  4. package/dist/Hooks.js.map +1 -1
  5. package/dist/Navigation.d.ts +83 -19
  6. package/dist/Navigation.js +93 -20
  7. package/dist/Navigation.js.map +1 -1
  8. package/dist/Remote.d.ts +37 -19
  9. package/dist/Remote.js +20 -7
  10. package/dist/Remote.js.map +1 -1
  11. package/dist/State.d.ts +77 -8
  12. package/dist/State.js +116 -27
  13. package/dist/State.js.map +1 -1
  14. package/dist/adapter/handler.d.ts +14 -12
  15. package/dist/adapter/handler.js +5 -7
  16. package/dist/adapter/handler.js.map +1 -1
  17. package/dist/adapter/index.js +25 -21
  18. package/dist/adapter/index.js.map +1 -1
  19. package/dist/api-client.js +1 -1
  20. package/dist/api-client.js.map +1 -1
  21. package/dist/app-runtime.d.ts +7 -6
  22. package/dist/app-runtime.js +5 -5
  23. package/dist/app-runtime.js.map +1 -1
  24. package/dist/client/Hooks.d.ts +1 -1
  25. package/dist/client/Hooks.js.map +1 -1
  26. package/dist/errors.js +3 -2
  27. package/dist/errors.js.map +1 -1
  28. package/dist/forms.d.ts +72 -9
  29. package/dist/forms.js +66 -5
  30. package/dist/forms.js.map +1 -1
  31. package/dist/internal/app-state.d.ts +38 -3
  32. package/dist/internal/app-state.js +58 -15
  33. package/dist/internal/app-state.js.map +1 -1
  34. package/dist/internal/auto.d.ts +2 -1
  35. package/dist/internal/auto.js.map +1 -1
  36. package/dist/internal/enhance.d.ts +107 -9
  37. package/dist/internal/enhance.js +30 -6
  38. package/dist/internal/enhance.js.map +1 -1
  39. package/dist/internal/error.js +23 -2
  40. package/dist/internal/error.js.map +1 -1
  41. package/dist/internal/remote-run.d.ts +3 -3
  42. package/dist/internal/remote-run.js.map +1 -1
  43. package/dist/internal/watch.svelte.js +33 -0
  44. package/dist/internal/watch.svelte.js.map +1 -0
  45. package/dist/kit.js +3 -3
  46. package/dist/kit.js.map +1 -1
  47. package/dist/realtime.d.ts +28 -7
  48. package/dist/realtime.js +68 -43
  49. package/dist/realtime.js.map +1 -1
  50. package/dist/remote-functions.d.ts +4 -4
  51. package/dist/remote-functions.js.map +1 -1
  52. package/dist/remote-reactive.d.ts +1 -1
  53. package/dist/remote-reactive.js.map +1 -1
  54. package/dist/response-headers.d.ts +1 -1
  55. package/dist/response-headers.js.map +1 -1
  56. package/dist/server/Endpoint.d.ts +2 -2
  57. package/dist/server/Endpoint.js +2 -2
  58. package/dist/server/Endpoint.js.map +1 -1
  59. package/dist/server/Hooks.d.ts +1 -1
  60. package/dist/server/Hooks.js.map +1 -1
  61. package/dist/transport.d.ts +1 -1
  62. package/dist/transport.js.map +1 -1
  63. package/dist/vite.d.ts +2 -2
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +10 -8
  66. package/LICENSE +0 -21
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ # MIT License
2
+
3
+ Copyright © 2026 [Thomas Foster](https://thomasfoster.au/)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -10,14 +10,14 @@ for the Svelte runes hooks.
10
10
  ## Install
11
11
 
12
12
  ```bash
13
- pnpm add @thomasfosterau/effect-sveltekit effect@rc svelte @sveltejs/kit
13
+ pnpm add @thomasfosterau/effect-sveltekit effect svelte @sveltejs/kit
14
14
  # the Effect deployment adapter additionally needs:
15
- pnpm add @effect/platform-node@rc
15
+ pnpm add @effect/platform-node
16
16
  ```
17
17
 
18
- `effect` (`>=4.0.0-rc.118`) and `svelte` (`^5.40.0`) are required peers;
19
- `@sveltejs/kit` (`^2.0.0 || ^3.0.0-next.0`), `vite` (for `./vite`) and
20
- `@effect/platform-node` (`>=4.0.0-rc.118`, for `./adapter`) are optional. The
18
+ `effect` (`>=4.0.2`) and `svelte` (`^5.40.0`) are required peers;
19
+ `@sveltejs/kit` (`^3.0.0`), `vite` (for `./vite`) and
20
+ `@effect/platform-node` (`>=4.0.2`, for `./adapter`) are optional. The
21
21
  HTTP modules that lived in `@effect/platform` in v3 are part of `effect` itself
22
22
  in v4 (`effect/http`), so no other Effect package is needed. Keep a single copy
23
23
  of `effect`, and keep `effect` and `@effect/platform-node` on the same
@@ -38,7 +38,7 @@ export const load = serverLoad((event) => Effect.succeed({ id: event.params.id }
38
38
  The same wrappers exist for actions, endpoints and hooks, on the default
39
39
  per-request runtime or on your own services (see
40
40
  [App-wide runtime](#app-wide-runtime-share-your-services-across-requests)); the
41
- `effectKit()` Vite plugin lets route files export bare Effects instead.
41
+ optional `effectKit()` Vite plugin lets route files export bare Effects instead.
42
42
 
43
43
  ## API
44
44
 
@@ -46,7 +46,7 @@ per-request runtime or on your own services (see
46
46
  | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
47
47
  | `@thomasfosterau/effect-sveltekit` | Universal helpers: `load` / `makeUniversalRuntime`, the `Remote` call namespace, `Hooks` (`reroute`, `transport`), `ResponseHeaders`, `sveltekitConfig` / `readConfig`, `apiClient` |
48
48
  | `…/server` | Server wrappers (`serverLoad`, `action`, `actions`, `endpoint`), `Hooks`, `Endpoint`, `makeServerRuntime`, the per-request runtime seam (`makeRuntimeAdapter` / `RequestRuntime`), `Errors`, `RemoteFunction`, request decoding (`decodeParams`, `decodeJson`, …) |
49
- | `…/client` | Browser-only `Navigation`, `State`, `Remote`, `Realtime`, `Forms` and `Hooks` namespaces, and `useRemoteQuery` |
49
+ | `…/client` | Browser-only `Navigation`, `State` (incl. the `CurrentPage` service), `Remote`, `Realtime`, `Forms` and `Hooks` namespaces, and `useRemoteQuery` |
50
50
  | `…/vite` | The `effectKit()` Vite plugin (auto-wraps bare-Effect route exports) |
51
51
  | `…/adapter` | The Effect HTTP deployment adapter (`effectAdapter`) |
52
52
  | `…/adapter/handler` | The SvelteKit app as an Effect HTTP app (`makeHandler`, `makeHandlerWith`, `AssetSource`, `toWebHandler`) |
@@ -57,7 +57,7 @@ per-request runtime or on your own services (see
57
57
  ### At a glance
58
58
 
59
59
  - **Effects as route exports** — explicit wrappers, app-wide runtimes (services
60
- built once per process), or the `effectKit()` plugin.
60
+ built once per process), or, optionally, the `effectKit()` plugin.
61
61
  - **Bring-your-own per-request runtime** — `makeRuntimeAdapter(provider, opts)`
62
62
  binds the server wrappers to a `RequestRuntime` provider, so the handler
63
63
  effect's services are your own application catalogue (not `SvelteKitServices`).
@@ -81,8 +81,9 @@ per-request runtime or on your own services (see
81
81
  `Hooks.markerTransporter` for non-round-tripping wrappers) and **`$env` ⇄
82
82
  Effect `Config`**.
83
83
  - **Client navigation/state** — the `Navigation` (`goto`/`invalidate`/… plus
84
- `beforeNavigate`/`afterNavigate`/`onNavigate` streams) and `State` (`page`)
85
- namespaces.
84
+ `beforeNavigate`/`afterNavigate`/`onNavigate` streams) and `State` (`page`,
85
+ `navigating` and `updated` streams, `checkForUpdate`, and the `CurrentPage`
86
+ service) namespaces.
86
87
  - **Effect deployment adapter** — the generated app is a platform-neutral
87
88
  Effect `HttpApp` (`makeHandlerWith`): serve it as a production Node HTTP server
88
89
  (`effect/http` + `@effect/platform-node`, the default) or as a Web
@@ -91,51 +92,6 @@ per-request runtime or on your own services (see
91
92
  (`AssetSource.fileSystem` for Node, `AssetSource.cloudflareAssets(env.ASSETS)`
92
93
  for Workers, or any custom source — R2, KV, a CDN passthrough).
93
94
 
94
- ### SvelteKit Vite plugin (recommended)
95
-
96
- ```ts
97
- // vite.config.ts
98
- import { sveltekit } from "@sveltejs/kit/vite";
99
- import { effectKit } from "@thomasfosterau/effect-sveltekit/vite";
100
-
101
- export default {
102
- plugins: [effectKit(), sveltekit()],
103
- };
104
- ```
105
-
106
- With the plugin installed, you can return an Effect (or a function returning
107
- an Effect) directly from any standard SvelteKit route file (`+page.ts`,
108
- `+page.server.ts`, `+layout(.server).ts`, `+server.ts`,
109
- `hooks.(server|client).ts`):
110
-
111
- ```ts
112
- // +page.server.ts
113
- import { Effect } from "effect";
114
-
115
- export const load = (event) => Effect.succeed({ id: event.params.id });
116
- ```
117
-
118
- The plugin rewrites the export so it goes through the same runtime as the
119
- explicit wrappers below; plain promise/value-returning functions pass through
120
- unchanged.
121
-
122
- #### Supported exports
123
-
124
- | File | Exports auto-wrapped |
125
- | ------------------- | ---------------------------------------------------------------------- |
126
- | `+page.ts` | `load` |
127
- | `+page.server.ts` | `load`, `actions` |
128
- | `+layout.ts` | `load` |
129
- | `+layout.server.ts` | `load` |
130
- | `+server.ts` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`, `HEAD`, `fallback` |
131
- | `hooks.ts` | `reroute` |
132
- | `hooks.server.ts` | `handle`, `handleFetch`, `handleError`, `init` |
133
- | `hooks.client.ts` | `handleError`, `init` |
134
-
135
- Config exports like `prerender`, `ssr`, `csr`, and `trailingSlash` — and the
136
- universal `transport` hook (which is plain data, not a function) — are never
137
- touched.
138
-
139
95
  ### App-wide runtime (share your services across requests)
140
96
 
141
97
  Define your application's Effect services once as a `Layer`; the layer is
@@ -153,9 +109,9 @@ export const runtime = makeServerRuntime(Database.layer);
153
109
 
154
110
  ```ts
155
111
  // src/routes/items/+page.server.ts
156
- import { runtime } from "$lib/server/runtime";
112
+ import { runtime } from "#lib/server/runtime.ts";
157
113
  import { Effect } from "effect";
158
- import { Database } from "$lib/server/database";
114
+ import { Database } from "#lib/server/database.ts";
159
115
 
160
116
  export const load = runtime.serverLoad((event) =>
161
117
  Effect.gen(function* () {
@@ -170,24 +126,17 @@ The runtime exposes `serverLoad`, `action`, `actions`, `handle`, `handleFetch`,
170
126
  For universal `load` functions there is a browser-safe counterpart,
171
127
  `makeUniversalRuntime`, in `@thomasfosterau/effect-sveltekit`.
172
128
 
173
- To make the same services available to bare-Effect exports handled by the
174
- Vite plugin, point the plugin at the runtime module:
175
-
176
- ```ts
177
- // vite.config.ts
178
- effectKit({ serverRuntime: "$lib/server/runtime" });
179
- ```
180
-
181
129
  #### One runtime per request
182
130
 
183
- Wire the runtime's `handle` hook (or the auto-wrapped `handle` from the Vite
184
- plugin) in `src/hooks.server.ts`. It creates a **per-request runtime** — the
185
- application layer's services plus the request's `HttpClient`/`SvelteKitRequestEvent`,
186
- built once and sharing a single request scope — and stores it on `event.locals`:
131
+ Wire the runtime's `handle` hook (or the auto-wrapped `handle` from the
132
+ [Vite plugin](#sveltekit-vite-plugin-optional)) in `src/hooks.server.ts`. It
133
+ creates a **per-request runtime** — the application layer's services plus the
134
+ request's `HttpClient`/`SvelteKitRequestEvent`, built once and sharing a single
135
+ request scope — and stores it on `event.locals`:
187
136
 
188
137
  ```ts
189
138
  // src/hooks.server.ts
190
- import { runtime } from "$lib/server/runtime";
139
+ import { runtime } from "#lib/server/runtime.ts";
191
140
  import { Effect } from "effect";
192
141
 
193
142
  export const handle = runtime.handle(({ event, resolve }) =>
@@ -215,6 +164,64 @@ export const handle = runtime.handle(({ event, resolve }) =>
215
164
  Wrappers from a _different_ runtime, or requests without `handle` wired, fall
216
165
  back to building the request services per call, so this is backward compatible.
217
166
 
167
+ ### SvelteKit Vite plugin (optional)
168
+
169
+ The explicit wrappers above are the primary API. The `effectKit()` Vite plugin
170
+ is an optional convenience on top of them:
171
+
172
+ ```ts
173
+ // vite.config.ts
174
+ import { sveltekit } from "@sveltejs/kit/vite";
175
+ import { effectKit } from "@thomasfosterau/effect-sveltekit/vite";
176
+
177
+ export default {
178
+ plugins: [effectKit(), sveltekit()],
179
+ };
180
+ ```
181
+
182
+ With the plugin installed, you can return an Effect (or a function returning
183
+ an Effect) directly from any standard SvelteKit route file (`+page.ts`,
184
+ `+page.server.ts`, `+layout(.server).ts`, `+server.ts`,
185
+ `hooks.(server|client).ts`):
186
+
187
+ ```ts
188
+ // +page.server.ts
189
+ import { Effect } from "effect";
190
+
191
+ export const load = (event) => Effect.succeed({ id: event.params.id });
192
+ ```
193
+
194
+ The plugin rewrites the export so it goes through the same runtime as the
195
+ explicit wrappers; plain promise/value-returning functions pass through
196
+ unchanged. SvelteKit's generated `$types` cannot see through the rewrite, so
197
+ type a plugin-wrapped route's `data` prop yourself; explicit wrappers return
198
+ real SvelteKit functions, so route `$types` work as usual.
199
+
200
+ To make an app-wide runtime's services available to bare-Effect exports, point
201
+ the plugin at the runtime module:
202
+
203
+ ```ts
204
+ // vite.config.ts
205
+ effectKit({ serverRuntime: "#lib/server/runtime.ts" });
206
+ ```
207
+
208
+ #### Supported exports
209
+
210
+ | File | Exports auto-wrapped |
211
+ | ------------------- | ---------------------------------------------------------------------- |
212
+ | `+page.ts` | `load` |
213
+ | `+page.server.ts` | `load`, `actions` |
214
+ | `+layout.ts` | `load` |
215
+ | `+layout.server.ts` | `load` |
216
+ | `+server.ts` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`, `HEAD`, `fallback` |
217
+ | `hooks.ts` | `reroute` |
218
+ | `hooks.server.ts` | `handle`, `handleFetch`, `handleError`, `init` |
219
+ | `hooks.client.ts` | `handleError`, `init` |
220
+
221
+ Config exports like `prerender`, `ssr`, `csr`, and `trailingSlash` — and the
222
+ universal `transport` hook (which is plain data, not a function) — are never
223
+ touched.
224
+
218
225
  ### Effect deployment adapter
219
226
 
220
227
  A SvelteKit [adapter](https://svelte.dev/docs/kit/adapters) (like
@@ -223,13 +230,15 @@ A SvelteKit [adapter](https://svelte.dev/docs/kit/adapters) (like
223
230
  configuration, request tracing spans, and graceful shutdown through Effect
224
231
  scopes:
225
232
 
226
- ```js
227
- // svelte.config.js
233
+ ```ts
234
+ // vite.config.ts
235
+ import { sveltekit } from "@sveltejs/kit/vite";
228
236
  import adapter from "@thomasfosterau/effect-sveltekit/adapter";
237
+ import { defineConfig } from "vite";
229
238
 
230
- export default {
231
- kit: { adapter: adapter() },
232
- };
239
+ export default defineConfig({
240
+ plugins: [sveltekit({ adapter: adapter() })],
241
+ });
233
242
  ```
234
243
 
235
244
  ```bash
@@ -260,6 +269,10 @@ together with `package.json` and production `node_modules` (which must
260
269
  include `@thomasfosterau/effect-sveltekit`, `effect`, and
261
270
  `@effect/platform-node`).
262
271
 
272
+ The adapter's optional `@effect/platform-node` peer pulls in `undici`, which
273
+ needs Node `>=22.19`, so the production server needs Node `>=22.19` even
274
+ though the package itself (like SvelteKit 3) declares `>=22.17`.
275
+
263
276
  ### SvelteKit universal load
264
277
 
265
278
  ```ts
@@ -297,7 +310,7 @@ import {
297
310
  RequestRuntime,
298
311
  } from "@thomasfosterau/effect-sveltekit/server";
299
312
  import { error } from "@sveltejs/kit";
300
- import type { AppError } from "$lib/errors"; // NotFound | Unauthorized | Forbidden | Redirect | HttpError | JsonapiError
313
+ import type { AppError } from "#lib/errors.ts"; // NotFound | Unauthorized | Forbidden | Redirect | HttpError | JsonapiError
301
314
 
302
315
  export const { serverLoad, endpoint } = makeRuntimeAdapter(
303
316
  RequestRuntime.fromLocals((event) => event.locals.runtime),
@@ -334,8 +347,8 @@ paths line up:
334
347
  ```ts
335
348
  // src/routes/api/[...path]/+server.ts
336
349
  import { Endpoint } from "@thomasfosterau/effect-sveltekit/server";
337
- import { api } from "$lib/server/api";
338
- import { ApiLive } from "$lib/server/handlers"; // HttpApiBuilder.group(...) + your services
350
+ import { api } from "#lib/server/api.ts";
351
+ import { ApiLive } from "#lib/server/handlers.ts"; // HttpApiBuilder.group(...) + your services
339
352
 
340
353
  export const fallback = Endpoint.fromApi(api, ApiLive, { prefix: "/api" });
341
354
  ```
@@ -357,7 +370,8 @@ import {
357
370
  // $app/navigation: promise wrappers (goto, invalidate, ...) and lifecycle
358
371
  // events as Effect Streams (beforeNavigate/afterNavigate/onNavigate)
359
372
  Navigation,
360
- // $app/state: the current page as a Stream of snapshots
373
+ // $app/state: page / navigating / updated as Streams, plus the
374
+ // CurrentPage service
361
375
  State,
362
376
  // remote-function helpers (callQuery, callCommand, liveQueryStream, ...)
363
377
  Remote,
@@ -367,10 +381,18 @@ import {
367
381
  Hooks,
368
382
  } from "@thomasfosterau/effect-sveltekit/client";
369
383
 
370
- // e.g. Navigation.goto('/done'), Navigation.invalidateAll(),
384
+ // e.g. Navigation.goto('/done'), Navigation.refreshAll(),
371
385
  // Remote.callQuery(getTodos), State.page()
372
386
  ```
373
387
 
388
+ `Navigation.goto`, `invalidate`, `invalidateAll`, `refreshAll`, `preloadData`
389
+ and `preloadCode` fail with `Navigation.NavigationError` when SvelteKit rejects
390
+ or throws: for example, `goto` to a URL outside the app, `preloadData` for an
391
+ `href` outside the app, a navigation whose `beforeNavigate` / `onNavigate`
392
+ callback throws, or any of them run during server rendering. The error's
393
+ `operation` names the wrapper and its `cause` is SvelteKit's original reason;
394
+ recover with `Effect.catchTag("NavigationError", ...)`.
395
+
374
396
  `Navigation.beforeNavigate()` / `Navigation.afterNavigate()` bridge
375
397
  `$app/navigation`'s callback-registration functions to `Stream`s,
376
398
  `Navigation.onNavigate(fn => Effect)` runs an Effect per navigation (forwarding
@@ -379,6 +401,31 @@ any cleanup the Effect yields), and `State.page()` emits a shallow snapshot of
379
401
  SvelteKit functions they wrap, these must be called during component
380
402
  initialization (at the top of `<script>`).
381
403
 
404
+ The rest of `State` watches `$app/state` directly, so it works anywhere on the
405
+ client (not only during component initialization):
406
+
407
+ | Export | What it is |
408
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
409
+ | `State.navigating()` | `Stream<Option<NavigatingSnapshot>>` — `Some` while a navigation is in flight (`type`, `from`, `to`, `willUnload`, `delta`, `complete`), `None` when idle |
410
+ | `State.updated()` | `Stream<boolean>` — `updated.current`: whether a new app version has been deployed |
411
+ | `State.checkForUpdate()` | `Effect<boolean, UpdateCheckError>` — `updated.check()` now; fails with `UpdateCheckError` if the check rejects |
412
+ | `State.CurrentPage` | A `Context` service: `get` (snapshot the page now) and `changes` (a stream that also emits on shallow routing and form results); provide `CurrentPage.layer` |
413
+
414
+ Each stream emits the current value on the next Svelte flush, then on every
415
+ change, and stops watching when it ends or is interrupted. None of them fail.
416
+
417
+ ```ts
418
+ import { State } from "@thomasfosterau/effect-sveltekit/client";
419
+ import { Effect } from "effect";
420
+
421
+ // Any client Effect can read the page once CurrentPage.layer is provided
422
+ // (e.g. in the layer behind your client runtime).
423
+ const logPath = Effect.gen(function* () {
424
+ const page = yield* (yield* State.CurrentPage).get;
425
+ yield* Effect.logInfo(`at ${page.url.pathname}`);
426
+ }).pipe(Effect.provide(State.CurrentPage.layer));
427
+ ```
428
+
382
429
  ### `transport` hook from Effect Schema
383
430
 
384
431
  Move custom types (`Option`, `DateTime`, branded types, `Schema.Class`
@@ -423,7 +470,7 @@ export const transport = Hooks.transport({ ResponseHeaders: Hooks.responseHeader
423
470
 
424
471
  // src/hooks.server.ts
425
472
  import { ResponseHeaders } from "@thomasfosterau/effect-sveltekit";
426
- import type { Handle } from "@sveltejs/kit";
473
+ import type { Handle } from "@sveltejs/kit/hooks";
427
474
 
428
475
  export const handle: Handle = async ({ event, resolve }) => {
429
476
  event.locals.headers = new ResponseHeaders();
@@ -522,10 +569,61 @@ Effects (no explicit wrapper) when the `effectKit()` Vite plugin is enabled.
522
569
 
523
570
  For SvelteKit page `actions`, the `Forms` namespace
524
571
  (`@thomasfosterau/effect-sveltekit/client`) expresses progressive enhancement
525
- with Effects: `Forms.enhance({ onSubmit, onResult })` builds a `SubmitFunction`
526
- for `use:enhance`, and `Forms.applyAction` / `Forms.deserialize` wrap the
527
- `$app/forms` helpers. (This complements `Remote.submitForm`, which covers remote
528
- forms.)
572
+ with Effects: `Forms.enhance({ onSubmit, onResult, onError }, { runtime })`
573
+ builds a `SubmitFunction` for `use:enhance`, and `Forms.applyAction` /
574
+ `Forms.deserialize` wrap the `$app/forms` helpers. `Forms.applyAction` fails
575
+ with `Forms.ApplyActionError` (SvelteKit's original reason as its `cause`) when
576
+ SvelteKit rejects or throws: for example, when the navigation that follows a
577
+ `redirect` result fails, or when it runs during server rendering.
578
+
579
+ The handlers (and `onError`) run on `runtime`, a `Context` or `ManagedRuntime`.
580
+ It is required, and checked to provide every service they require, as soon as
581
+ any handler requires one: there is no ambient runtime to fall back on, so such a
582
+ call without it does not type-check. Each handler may require different
583
+ services; the runtime must provide all of them. A missing runtime is reported on
584
+ the `Forms.enhance` call, and one that lacks a service on the runtime, never on
585
+ a handler. The message may at first name only the services of the handlers
586
+ TypeScript types first (such as an `onError` passed by name, before handlers
587
+ whose parameters are not annotated), and the rest once the runtime provides
588
+ those. Handlers that require no services run on the default runtime, and the
589
+ options may be omitted; an effect typed as requiring `any` or `unknown` is
590
+ treated as requiring no services, so no runtime is demanded. A function that
591
+ wraps `Forms.enhance` for handlers requiring any `R` forwards its options as
592
+ `...options: Forms.EnhanceOptionsArgs<R>`, which keeps them optional exactly
593
+ when `R` is `never` (an `EnhanceOptions<R>`, whose runtime is optional, does not
594
+ type-check there).
595
+
596
+ `onSubmit` and `onResult` may fail. The `onError` handler receives the error,
597
+ typed as the union of their error types, and runs on the same runtime; it must
598
+ not fail itself. Write `onError` after the other handlers: written before one
599
+ whose parameters are not annotated, it still type-checks, but its `error`
600
+ parameter is `unknown`. A failed `onSubmit` also cancels the submission, and a
601
+ failed `onResult` does not fall back to SvelteKit's default behaviour. Without
602
+ `onError`, a failure is treated like a defect: the promise SvelteKit awaits
603
+ rejects with the error, SvelteKit sends no request after a failed `onSubmit`
604
+ and applies no default result after a failed `onResult`, and the browser
605
+ reports an unhandled rejection. Defects and interruptions always take that path
606
+ rather than reaching `onError`.
607
+
608
+ ```ts
609
+ const submit = Forms.enhance({
610
+ onResult: ({ result }) => Forms.applyAction(result),
611
+ // error: ApplyActionError
612
+ onError: (error) => Effect.logWarning("applyAction failed", error.cause),
613
+ });
614
+
615
+ const submitAndRecover = Forms.enhance({
616
+ // Or recover inside the handler, so onResult cannot fail.
617
+ onResult: ({ result }) =>
618
+ Forms.applyAction(result).pipe(
619
+ Effect.catchTag("ApplyActionError", (error) =>
620
+ Effect.logWarning("applyAction failed", error.cause),
621
+ ),
622
+ ),
623
+ });
624
+ ```
625
+
626
+ (This complements `Remote.submitForm`, which covers remote forms.)
529
627
 
530
628
  ## Recipes
531
629
 
package/dist/Hooks.d.ts CHANGED
@@ -2,7 +2,7 @@ import { MarkerTransporterOptions, TransportEntry, markerTransporter, transport,
2
2
  import { responseHeadersTransporter } from "./response-headers.js";
3
3
  import { Effect } from "effect";
4
4
  import * as HttpClient from "effect/http/HttpClient";
5
- import { Reroute } from "@sveltejs/kit";
5
+ import { Reroute } from "@sveltejs/kit/hooks";
6
6
  declare namespace Hooks_d_exports {
7
7
  export { MarkerTransporterOptions, TransportEntry, markerTransporter, reroute, responseHeadersTransporter, transport, transporter };
8
8
  }
package/dist/Hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Hooks.js","names":[],"sources":["../src/Hooks.ts"],"sourcesContent":["/**\n * Effect helpers for SvelteKit's universal hooks (`src/hooks.ts`), exposed as\n * the `Hooks` namespace of `@thomasfosterau/effect-sveltekit`.\n *\n * The `reroute` hook is expressed as an Effect (running on the universal\n * runtime, with an `HttpClient` backed by the event's `fetch`), and the\n * universal `transport` hook is built from Effect schemas via {@link transport}\n * / {@link transporter}.\n *\n * @example\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit';\n * import { Effect, Schema } from 'effect';\n *\n * export const reroute = Hooks.reroute((event) =>\n * Effect.succeed(event.url.pathname === '/old' ? '/new' : undefined),\n * );\n *\n * export const transport = Hooks.transport({\n * Option: Schema.Option(Schema.Number),\n * Date: Schema.Date,\n * });\n * ```\n */\n\nimport type { Reroute } from \"@sveltejs/kit\";\nimport { Effect } from \"effect\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport { defaultUniversalRuntime } from \"./internal/default-runtime.js\";\n\n/**\n * Wraps an Effect-based function as the SvelteKit universal\n * [`reroute`](https://svelte.dev/docs/kit/hooks#Universal-hooks-reroute) hook,\n * which rewrites the URL before routing. The effect runs on both the server and\n * the client and gets an `HttpClient` backed by the event's `fetch`.\n *\n * @example\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit';\n * import { Effect } from 'effect';\n *\n * export const reroute = Hooks.reroute((event) =>\n * Effect.succeed(event.url.pathname === '/old' ? '/new' : undefined),\n * );\n * ```\n */\nexport function reroute(\n fn: (event: {\n url: URL;\n fetch: typeof globalThis.fetch;\n }) => Effect.Effect<string | void, unknown, HttpClient.HttpClient>,\n): Reroute {\n return (event) => defaultUniversalRuntime().runPromise(event.fetch, fn(event));\n}\n\n/**\n * The universal `transport` hook built from Effect schemas: `transport`\n * assembles a whole `transport` object from a record of entries, `transporter`\n * builds a single round-tripping entry from a `Schema.Codec`, and\n * `markerTransporter` builds a deliberately-lossy entry for a non-POJO wrapper\n * whose contents should not round-trip. See {@link transport} for details.\n */\nexport {\n transport,\n transporter,\n markerTransporter,\n type MarkerTransporterOptions,\n type TransportEntry,\n} from \"./transport.js\";\n\n/**\n * The `transport` entry for the {@link ResponseHeaders} response-headers buffer\n * (`Hooks.transport({ ResponseHeaders: Hooks.responseHeadersTransporter })`).\n */\nexport { responseHeadersTransporter } from \"./response-headers.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,QACd,IAIS;CACT,QAAQ,UAAU,wBAAwB,CAAC,CAAC,WAAW,MAAM,OAAO,GAAG,KAAK,CAAC;AAC/E"}
1
+ {"version":3,"file":"Hooks.js","names":[],"sources":["../src/Hooks.ts"],"sourcesContent":["/**\n * Effect helpers for SvelteKit's universal hooks (`src/hooks.ts`), exposed as\n * the `Hooks` namespace of `@thomasfosterau/effect-sveltekit`.\n *\n * The `reroute` hook is expressed as an Effect (running on the universal\n * runtime, with an `HttpClient` backed by the event's `fetch`), and the\n * universal `transport` hook is built from Effect schemas via {@link transport}\n * / {@link transporter}.\n *\n * @example\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit';\n * import { Effect, Schema } from 'effect';\n *\n * export const reroute = Hooks.reroute((event) =>\n * Effect.succeed(event.url.pathname === '/old' ? '/new' : undefined),\n * );\n *\n * export const transport = Hooks.transport({\n * Option: Schema.Option(Schema.Number),\n * Date: Schema.Date,\n * });\n * ```\n */\n\nimport type { Reroute } from \"@sveltejs/kit/hooks\";\nimport { Effect } from \"effect\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport { defaultUniversalRuntime } from \"./internal/default-runtime.js\";\n\n/**\n * Wraps an Effect-based function as the SvelteKit universal\n * [`reroute`](https://svelte.dev/docs/kit/hooks#Universal-hooks-reroute) hook,\n * which rewrites the URL before routing. The effect runs on both the server and\n * the client and gets an `HttpClient` backed by the event's `fetch`.\n *\n * @example\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit';\n * import { Effect } from 'effect';\n *\n * export const reroute = Hooks.reroute((event) =>\n * Effect.succeed(event.url.pathname === '/old' ? '/new' : undefined),\n * );\n * ```\n */\nexport function reroute(\n fn: (event: {\n url: URL;\n fetch: typeof globalThis.fetch;\n }) => Effect.Effect<string | void, unknown, HttpClient.HttpClient>,\n): Reroute {\n return (event) => defaultUniversalRuntime().runPromise(event.fetch, fn(event));\n}\n\n/**\n * The universal `transport` hook built from Effect schemas: `transport`\n * assembles a whole `transport` object from a record of entries, `transporter`\n * builds a single round-tripping entry from a `Schema.Codec`, and\n * `markerTransporter` builds a deliberately-lossy entry for a non-POJO wrapper\n * whose contents should not round-trip. See {@link transport} for details.\n */\nexport {\n transport,\n transporter,\n markerTransporter,\n type MarkerTransporterOptions,\n type TransportEntry,\n} from \"./transport.js\";\n\n/**\n * The `transport` entry for the {@link ResponseHeaders} response-headers buffer\n * (`Hooks.transport({ ResponseHeaders: Hooks.responseHeadersTransporter })`).\n */\nexport { responseHeadersTransporter } from \"./response-headers.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,QACd,IAIS;CACT,QAAQ,UAAU,wBAAwB,CAAC,CAAC,WAAW,MAAM,OAAO,GAAG,KAAK,CAAC;AAC/E"}
@@ -1,21 +1,85 @@
1
1
  import { Effect, Stream } from "effect";
2
- import { AfterNavigate, BeforeNavigate, OnNavigate } from "@sveltejs/kit";
3
- import { goto, invalidate, preloadData, refreshAll } from "$app/navigation";
2
+ import { AfterNavigate, BeforeNavigate, OnNavigate, goto, invalidate, preloadCode, preloadData, refreshAll } from "$app/navigation";
4
3
  declare namespace Navigation_d_exports {
5
- export { afterNavigate$1 as afterNavigate, beforeNavigate$1 as beforeNavigate, goto$1 as goto, invalidate$1 as invalidate, invalidateAll$1 as invalidateAll, onNavigate$1 as onNavigate, preloadCode$1 as preloadCode, preloadData$1 as preloadData, refreshAll$1 as refreshAll };
4
+ export { NavigationError, afterNavigate$1 as afterNavigate, beforeNavigate$1 as beforeNavigate, goto$1 as goto, invalidate$1 as invalidate, invalidateAll$1 as invalidateAll, onNavigate$1 as onNavigate, preloadCode$1 as preloadCode, preloadData$1 as preloadData, refreshAll$1 as refreshAll };
6
5
  }
7
- /** Navigate to `url`. Wraps `$app/navigation`'s `goto`. */
8
- declare const goto$1: (...args: Parameters<typeof goto>) => Effect.Effect<void>;
9
- /** Re-run `load` functions that depend on `resource`. Wraps `invalidate`. */
10
- declare const invalidate$1: (...args: Parameters<typeof invalidate>) => Effect.Effect<void>;
11
- /** Re-run every `load` function for the active page. Wraps `invalidateAll`. */
12
- declare const invalidateAll$1: () => Effect.Effect<void>;
13
- /** Refresh active remote functions (and, by default, `load`s). Wraps `refreshAll`. */
14
- declare const refreshAll$1: (...args: Parameters<typeof refreshAll>) => Effect.Effect<void>;
15
- /** Preload the data for `href`. Wraps `preloadData`. */
16
- declare const preloadData$1: (href: string) => Effect.Effect<Awaited<ReturnType<typeof preloadData>>>;
17
- /** Preload the code for routes matching `pathname`. Wraps `preloadCode`. */
18
- declare const preloadCode$1: (pathname: string) => Effect.Effect<void>;
6
+ declare const NavigationError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
7
+ readonly _tag: "NavigationError";
8
+ } & Readonly<A>;
9
+ /**
10
+ * A `$app/navigation` promise wrapper ({@link goto}, {@link invalidate},
11
+ * {@link invalidateAll}, {@link refreshAll}, {@link preloadData},
12
+ * {@link preloadCode}) rejected or threw. `operation` names the wrapper and
13
+ * `cause` is SvelteKit's original reason, unchanged.
14
+ *
15
+ * SvelteKit 3 rejects `goto` with a URL outside the app (external, or matching
16
+ * no route) and `preloadData` with a URL outside the app; `invalidate` throws on
17
+ * a `resource` that cannot be parsed even relative to the current URL;
18
+ * `preloadCode` rejects when a route's code fails to load; a navigation (including one that follows a `load` redirect during
19
+ * `invalidate` / `refreshAll`) rejects when a `beforeNavigate` / `onNavigate`
20
+ * callback throws; and every one of them throws when called during server
21
+ * rendering. Recover with `Effect.catchTag("NavigationError", ...)`.
22
+ */
23
+ declare class NavigationError extends NavigationError_base<{
24
+ /** The wrapper whose SvelteKit call failed. */
25
+ readonly operation: "goto" | "invalidate" | "invalidateAll" | "refreshAll" | "preloadData" | "preloadCode";
26
+ /** The rejection reason, or the value thrown, as SvelteKit produced it. */
27
+ readonly cause: unknown;
28
+ }> {}
29
+ /**
30
+ * Navigate to `url`. Wraps `$app/navigation`'s `goto`.
31
+ *
32
+ * Fails with a {@link NavigationError} if SvelteKit rejects: a URL outside the
33
+ * app (external, or not matching a route) rejects, as does a navigation whose
34
+ * `beforeNavigate` / `onNavigate` callback throws, or a call during server
35
+ * rendering. For an external URL, set `window.location` instead.
36
+ */
37
+ declare const goto$1: (...args: Parameters<typeof goto>) => Effect.Effect<void, NavigationError>;
38
+ /**
39
+ * Re-run `load` functions that depend on `resource`. Wraps `invalidate`.
40
+ *
41
+ * Fails with a {@link NavigationError} if SvelteKit rejects or throws: a
42
+ * `resource` string that cannot be parsed even relative to the current URL
43
+ * throws, as does a call during server rendering, and the navigation that
44
+ * follows a `load` redirect can reject.
45
+ */
46
+ declare const invalidate$1: (...args: Parameters<typeof invalidate>) => Effect.Effect<void, NavigationError>;
47
+ /**
48
+ * Re-run every `load` function for the active page. Wraps `invalidateAll`.
49
+ *
50
+ * Fails with a {@link NavigationError} if SvelteKit rejects or throws: for
51
+ * example, when the navigation that follows a `load` redirect fails, or when
52
+ * called during server rendering.
53
+ *
54
+ * @deprecated SvelteKit 3 deprecates `invalidateAll`; use {@link refreshAll},
55
+ * which also refreshes active remote functions and keeps `page.state`.
56
+ */
57
+ declare const invalidateAll$1: () => Effect.Effect<void, NavigationError>;
58
+ /**
59
+ * Refresh active remote functions (and, by default, `load`s). Wraps `refreshAll`.
60
+ *
61
+ * Fails with a {@link NavigationError} if SvelteKit rejects or throws: for
62
+ * example, when the navigation that follows a `load` redirect fails, or when
63
+ * called during server rendering.
64
+ */
65
+ declare const refreshAll$1: (...args: Parameters<typeof refreshAll>) => Effect.Effect<void, NavigationError>;
66
+ /**
67
+ * Preload the data for `href`. Wraps `preloadData`, succeeding with SvelteKit's
68
+ * result (`loaded`, `redirect`, or `error` when a `load` fails).
69
+ *
70
+ * Fails with a {@link NavigationError} if SvelteKit rejects: an `href` outside
71
+ * the app rejects, as does a call during server rendering.
72
+ */
73
+ declare const preloadData$1: (href: string) => Effect.Effect<Awaited<ReturnType<typeof preloadData>>, NavigationError>;
74
+ /**
75
+ * Preload the code for the route `id` (e.g. `/blog/[slug]`, without
76
+ * `paths.base`). Wraps `preloadCode`.
77
+ *
78
+ * Fails with a {@link NavigationError} if SvelteKit rejects: a route module
79
+ * that fails to load rejects, as does a call during server rendering (and, in
80
+ * development, an `id` not starting with `/`).
81
+ */
82
+ declare const preloadCode$1: (...args: Parameters<typeof preloadCode>) => Effect.Effect<void, NavigationError>;
19
83
  /**
20
84
  * Registers a `beforeNavigate` callback and exposes every navigation about to
21
85
  * happen as an Effect `Stream`. Call during component initialization.
@@ -23,9 +87,9 @@ declare const preloadCode$1: (pathname: string) => Effect.Effect<void>;
23
87
  * Unlike the promise-returning navigation functions above, this is a
24
88
  * **callback-registration** function: it must be called *synchronously during
25
89
  * component initialization* (SvelteKit wires it to the component's lifecycle).
26
- * It registers its callback eagerly and feeds an internal `Queue`, returning a
27
- * `Stream` backed by that queue — the same push-based bridge as `SignalEmitter`
28
- * in `@thomasfosterau/effect-svelte`. Call it at the top level of `<script>`,
90
+ * It registers its callback eagerly and feeds an internal unbounded `Queue`,
91
+ * returning a `Stream` backed by that queue: a push-based bridge that buffers
92
+ * every event for its single consumer. Call it at the top level of `<script>`,
29
93
  * exactly where you'd call the bare `beforeNavigate`.
30
94
  *
31
95
  * @example
@@ -104,5 +168,5 @@ declare function afterNavigate$1(): Stream.Stream<AfterNavigate>;
104
168
  */
105
169
  declare function onNavigate$1(fn: (navigation: OnNavigate) => Effect.Effect<(() => void) | void>, runEffect?: <X>(effect: Effect.Effect<X>) => Promise<X>): void;
106
170
  //#endregion
107
- export { Navigation_d_exports, afterNavigate$1 as afterNavigate, beforeNavigate$1 as beforeNavigate, goto$1 as goto, invalidate$1 as invalidate, invalidateAll$1 as invalidateAll, onNavigate$1 as onNavigate, preloadCode$1 as preloadCode, preloadData$1 as preloadData, refreshAll$1 as refreshAll };
171
+ export { NavigationError, Navigation_d_exports, afterNavigate$1 as afterNavigate, beforeNavigate$1 as beforeNavigate, goto$1 as goto, invalidate$1 as invalidate, invalidateAll$1 as invalidateAll, onNavigate$1 as onNavigate, preloadCode$1 as preloadCode, preloadData$1 as preloadData, refreshAll$1 as refreshAll };
108
172
  //# sourceMappingURL=Navigation.d.ts.map