@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.
- package/LICENSE.md +9 -0
- package/README.md +183 -85
- package/dist/Hooks.d.ts +1 -1
- package/dist/Hooks.js.map +1 -1
- package/dist/Navigation.d.ts +83 -19
- package/dist/Navigation.js +93 -20
- package/dist/Navigation.js.map +1 -1
- package/dist/Remote.d.ts +37 -19
- package/dist/Remote.js +20 -7
- package/dist/Remote.js.map +1 -1
- package/dist/State.d.ts +77 -8
- package/dist/State.js +116 -27
- package/dist/State.js.map +1 -1
- package/dist/adapter/handler.d.ts +14 -12
- package/dist/adapter/handler.js +5 -7
- package/dist/adapter/handler.js.map +1 -1
- package/dist/adapter/index.js +25 -21
- package/dist/adapter/index.js.map +1 -1
- package/dist/api-client.js +1 -1
- package/dist/api-client.js.map +1 -1
- package/dist/app-runtime.d.ts +7 -6
- package/dist/app-runtime.js +5 -5
- package/dist/app-runtime.js.map +1 -1
- package/dist/client/Hooks.d.ts +1 -1
- package/dist/client/Hooks.js.map +1 -1
- package/dist/errors.js +3 -2
- package/dist/errors.js.map +1 -1
- package/dist/forms.d.ts +72 -9
- package/dist/forms.js +66 -5
- package/dist/forms.js.map +1 -1
- package/dist/internal/app-state.d.ts +38 -3
- package/dist/internal/app-state.js +58 -15
- package/dist/internal/app-state.js.map +1 -1
- package/dist/internal/auto.d.ts +2 -1
- package/dist/internal/auto.js.map +1 -1
- package/dist/internal/enhance.d.ts +107 -9
- package/dist/internal/enhance.js +30 -6
- package/dist/internal/enhance.js.map +1 -1
- package/dist/internal/error.js +23 -2
- package/dist/internal/error.js.map +1 -1
- package/dist/internal/remote-run.d.ts +3 -3
- package/dist/internal/remote-run.js.map +1 -1
- package/dist/internal/watch.svelte.js +33 -0
- package/dist/internal/watch.svelte.js.map +1 -0
- package/dist/kit.js +3 -3
- package/dist/kit.js.map +1 -1
- package/dist/realtime.d.ts +28 -7
- package/dist/realtime.js +68 -43
- package/dist/realtime.js.map +1 -1
- package/dist/remote-functions.d.ts +4 -4
- package/dist/remote-functions.js.map +1 -1
- package/dist/remote-reactive.d.ts +1 -1
- package/dist/remote-reactive.js.map +1 -1
- package/dist/response-headers.d.ts +1 -1
- package/dist/response-headers.js.map +1 -1
- package/dist/server/Endpoint.d.ts +2 -2
- package/dist/server/Endpoint.js +2 -2
- package/dist/server/Endpoint.js.map +1 -1
- package/dist/server/Hooks.d.ts +1 -1
- package/dist/server/Hooks.js.map +1 -1
- package/dist/transport.d.ts +1 -1
- package/dist/transport.js.map +1 -1
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js.map +1 -1
- package/package.json +10 -8
- package/LICENSE +0 -21
|
@@ -1,18 +1,6 @@
|
|
|
1
|
-
import { Effect, Queue, Stream } from "effect";
|
|
1
|
+
import { Data, Effect, Option, Queue, Stream } from "effect";
|
|
2
2
|
//#region src/internal/app-state.ts
|
|
3
3
|
/**
|
|
4
|
-
* Pure, `$app/*`-free core for the `$app/state` bridge in `../State.ts`.
|
|
5
|
-
*
|
|
6
|
-
* The public `page` can't be unit-tested directly because importing it
|
|
7
|
-
* pulls in `$app/navigation` and `$app/state` (SvelteKit virtual modules that
|
|
8
|
-
* only exist inside a build). The snapshotting and the "emit now, then after
|
|
9
|
-
* each navigation" plumbing live here instead, parameterised over the
|
|
10
|
-
* navigation registrar and a `readPage` thunk, so they can be driven with
|
|
11
|
-
* stand-ins in tests while the public wrapper stays a thin pass-through.
|
|
12
|
-
*
|
|
13
|
-
* @internal
|
|
14
|
-
*/
|
|
15
|
-
/**
|
|
16
4
|
* Builds a shallow snapshot of the `page` fields that matter. We copy the
|
|
17
5
|
* fields rather than forwarding the live `$app/state` proxy so downstream Effect
|
|
18
6
|
* consumers see a stable value (the proxy mutates in place on every
|
|
@@ -29,7 +17,8 @@ function snapshotPage(page) {
|
|
|
29
17
|
error: page.error,
|
|
30
18
|
data: page.data,
|
|
31
19
|
state: page.state,
|
|
32
|
-
form: page.form
|
|
20
|
+
form: page.form,
|
|
21
|
+
shallow: page.shallow
|
|
33
22
|
};
|
|
34
23
|
}
|
|
35
24
|
/**
|
|
@@ -46,7 +35,61 @@ function pageSnapshotStream(registerAfterNavigate, readPage) {
|
|
|
46
35
|
});
|
|
47
36
|
return Stream.fromQueue(queue);
|
|
48
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* A `Stream` of `read()`: the current value, then a new one each time `watch`
|
|
40
|
+
* reports a change. Cold and lazy — each run opens its own watcher and disposes
|
|
41
|
+
* it when the stream ends or is interrupted. Never fails; a throwing `watch`
|
|
42
|
+
* surfaces as a defect (the stream dies with what it threw, with no watcher
|
|
43
|
+
* left to dispose).
|
|
44
|
+
*/
|
|
45
|
+
function watchedStream(watch, read) {
|
|
46
|
+
return Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => watch(read, (value) => {
|
|
47
|
+
Queue.offerUnsafe(queue, value);
|
|
48
|
+
})), (dispose) => Effect.sync(dispose)));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Copies `navigating` into a plain {@link NavigatingSnapshot}, or `None` when
|
|
52
|
+
* no navigation is in flight (`type` is `null`). Reads every field, so a
|
|
53
|
+
* watcher tracks the whole object.
|
|
54
|
+
*/
|
|
55
|
+
function snapshotNavigating(navigating) {
|
|
56
|
+
const { type, from, to, willUnload, delta, complete } = navigating;
|
|
57
|
+
if (type === null || willUnload === null || complete === null) return Option.none();
|
|
58
|
+
return Option.some({
|
|
59
|
+
type,
|
|
60
|
+
from,
|
|
61
|
+
to,
|
|
62
|
+
willUnload,
|
|
63
|
+
delta: delta ?? null,
|
|
64
|
+
complete
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* `updated.check()` rejected. SvelteKit resolves `false` when the version
|
|
69
|
+
* request fails, so this signals misuse (e.g. calling it during server
|
|
70
|
+
* rendering, where there is no `window`) rather than a network error.
|
|
71
|
+
*/
|
|
72
|
+
var UpdateCheckError = class extends Data.TaggedError("UpdateCheckError") {};
|
|
73
|
+
/**
|
|
74
|
+
* Runs `check` (SvelteKit's `updated.check`) as an Effect that succeeds with
|
|
75
|
+
* whether a new version is available and fails with {@link UpdateCheckError}
|
|
76
|
+
* if the promise rejects (or `check` throws).
|
|
77
|
+
*/
|
|
78
|
+
function checkForUpdateWith(check) {
|
|
79
|
+
return Effect.tryPromise({
|
|
80
|
+
try: () => check(),
|
|
81
|
+
catch: (cause) => new UpdateCheckError({ cause })
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Builds a {@link CurrentPageShape} reading `readPage()` and watching it with `watch`. */
|
|
85
|
+
function makeCurrentPage(readPage, watch) {
|
|
86
|
+
const read = () => snapshotPage(readPage());
|
|
87
|
+
return {
|
|
88
|
+
get: Effect.sync(read),
|
|
89
|
+
changes: watchedStream(watch, read)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
49
92
|
//#endregion
|
|
50
|
-
export { pageSnapshotStream, snapshotPage };
|
|
93
|
+
export { UpdateCheckError, checkForUpdateWith, makeCurrentPage, pageSnapshotStream, snapshotNavigating, snapshotPage, watchedStream };
|
|
51
94
|
|
|
52
95
|
//# sourceMappingURL=app-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-state.js","names":[],"sources":["../../src/internal/app-state.ts"],"sourcesContent":["/**\n * Pure, `$app/*`-free core for the `$app/state` bridge in `../State.ts`.\n *\n * The public
|
|
1
|
+
{"version":3,"file":"app-state.js","names":[],"sources":["../../src/internal/app-state.ts"],"sourcesContent":["/**\n * Pure, `$app/*`-free core for the `$app/state` bridge in `../State.ts`.\n *\n * The public helpers can't be unit-tested in plain Node because importing them\n * pulls in `$app/navigation` and `$app/state` (SvelteKit virtual modules that\n * only exist inside a build). The snapshotting, the \"emit now, then after each\n * navigation\" plumbing and the watch-to-`Stream` bridge live here instead,\n * parameterised over the navigation registrar, a {@link Watch} function and\n * read thunks, so they can be driven with stand-ins in tests while the public\n * wrappers stay thin pass-throughs. The only runes code is `watch.svelte.ts`.\n *\n * @internal\n */\n\nimport type { NavigationTarget, NavigationType } from \"$app/navigation\";\nimport { Data, Effect, Option, Queue, Stream } from \"effect\";\n\n/**\n * The fields of SvelteKit's `page` we snapshot. Mirrors the shape of\n * `@sveltejs/kit`'s `Page`, but as a plain readonly record rather than the live\n * mutating proxy.\n */\nexport interface PageSnapshot<P extends ReadonlyPage = ReadonlyPage> {\n readonly url: P[\"url\"];\n readonly params: P[\"params\"];\n readonly route: P[\"route\"];\n readonly status: P[\"status\"];\n readonly error: P[\"error\"];\n readonly data: P[\"data\"];\n readonly state: P[\"state\"];\n readonly form: P[\"form\"];\n readonly shallow: P[\"shallow\"];\n}\n\n/**\n * The subset of `Page` fields the snapshot reads. Deliberately loose (the value\n * types are `unknown` / broad) so SvelteKit's `Page` — whose `params` / `data`\n * / `error` / `state` are app-specific — satisfies the constraint, while\n * `PageSnapshot<P>` recovers the precise field types from `P`.\n */\nexport interface ReadonlyPage {\n // SvelteKit 3 types `page.url` as an immutable `ReadonlyURL` (from\n // `$app/state`); everything but `searchParams` is enough here.\n readonly url: Readonly<Omit<URL, \"searchParams\">>;\n readonly params: Record<string, string | undefined>;\n readonly route: { readonly id: string | null };\n readonly status: number;\n readonly error: unknown;\n readonly data: Record<string, unknown>;\n readonly state: unknown;\n readonly form: unknown;\n // SvelteKit 3: the target of the current shallow navigation, or `null`.\n readonly shallow: unknown;\n}\n\n/**\n * Builds a shallow snapshot of the `page` fields that matter. We copy the\n * fields rather than forwarding the live `$app/state` proxy so downstream Effect\n * consumers see a stable value (the proxy mutates in place on every\n * navigation, which would make a captured reference unreliable). Nested values\n * (`url`, `data`, ...) are *not* deep-cloned: they're replaced wholesale on each\n * navigation, so a shallow copy is enough to distinguish snapshots.\n */\nexport function snapshotPage<P extends ReadonlyPage>(page: P): PageSnapshot<P> {\n return {\n url: page.url,\n params: page.params,\n route: page.route,\n status: page.status,\n error: page.error,\n data: page.data,\n state: page.state,\n form: page.form,\n shallow: page.shallow,\n };\n}\n\n/**\n * Emits a snapshot of `readPage()` immediately, then again every time\n * `registerAfterNavigate`'s callback fires (i.e. after each navigation). Backed\n * by an unbounded queue, exposed as a `Stream` — the same push bridge as the\n * navigation-event helpers.\n */\nexport function pageSnapshotStream<P extends ReadonlyPage>(\n registerAfterNavigate: (callback: () => void) => void,\n readPage: () => P,\n): Stream.Stream<PageSnapshot<P>> {\n const queue = Effect.runSync(Queue.unbounded<PageSnapshot<P>>());\n // Initial value: the current page, so consumers start from a known state.\n Queue.offerUnsafe(queue, snapshotPage(readPage()));\n // afterNavigate fires once on mount too, but emitting up front means a\n // late-subscribing consumer still sees the current page without waiting for a\n // navigation.\n registerAfterNavigate(() => {\n Queue.offerUnsafe(queue, snapshotPage(readPage()));\n });\n return Stream.fromQueue(queue);\n}\n\n// ─── Watching rune state ─────────────────────────────────────────────────────\n\n/**\n * Observes a reactive read: calls `onValue` with `read()` once, then again\n * whenever something `read` touched changes, until the returned disposer runs.\n * The real implementation is `watch` in `./watch.svelte.ts`.\n */\nexport type Watch = <A>(read: () => A, onValue: (value: A) => void) => () => void;\n\n/**\n * A `Stream` of `read()`: the current value, then a new one each time `watch`\n * reports a change. Cold and lazy — each run opens its own watcher and disposes\n * it when the stream ends or is interrupted. Never fails; a throwing `watch`\n * surfaces as a defect (the stream dies with what it threw, with no watcher\n * left to dispose).\n */\nexport function watchedStream<A>(watch: Watch, read: () => A): Stream.Stream<A> {\n return Stream.callback<A>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() =>\n watch(read, (value) => {\n Queue.offerUnsafe(queue, value);\n }),\n ),\n (dispose) => Effect.sync(dispose),\n ),\n );\n}\n\n// ─── navigating ──────────────────────────────────────────────────────────────\n\n/**\n * A snapshot of an in-flight SvelteKit navigation, as `$app/state`'s\n * `navigating` exposes it. `delta` is the history step count for a `popstate`\n * navigation and `null` otherwise; `complete` resolves when the navigation\n * finishes and rejects if it fails or is aborted.\n */\nexport interface NavigatingSnapshot {\n readonly type: Exclude<NavigationType, \"enter\">;\n readonly from: NavigationTarget | null;\n readonly to: NavigationTarget | null;\n readonly willUnload: boolean;\n readonly delta: number | null;\n readonly complete: Promise<void>;\n}\n\n/**\n * The shape of `$app/state`'s `navigating`: every field is `null` while no\n * navigation is in flight.\n */\nexport interface ReadonlyNavigating {\n readonly type: NavigatingSnapshot[\"type\"] | null;\n readonly from: NavigationTarget | null;\n readonly to: NavigationTarget | null;\n readonly willUnload: boolean | null;\n readonly delta?: number | null | undefined;\n readonly complete: Promise<void> | null;\n}\n\n/**\n * Copies `navigating` into a plain {@link NavigatingSnapshot}, or `None` when\n * no navigation is in flight (`type` is `null`). Reads every field, so a\n * watcher tracks the whole object.\n */\nexport function snapshotNavigating(\n navigating: ReadonlyNavigating,\n): Option.Option<NavigatingSnapshot> {\n const { type, from, to, willUnload, delta, complete } = navigating;\n if (type === null || willUnload === null || complete === null) return Option.none();\n return Option.some({ type, from, to, willUnload, delta: delta ?? null, complete });\n}\n\n// ─── updated ─────────────────────────────────────────────────────────────────\n\n/**\n * `updated.check()` rejected. SvelteKit resolves `false` when the version\n * request fails, so this signals misuse (e.g. calling it during server\n * rendering, where there is no `window`) rather than a network error.\n */\nexport class UpdateCheckError extends Data.TaggedError(\"UpdateCheckError\")<{\n readonly cause: unknown;\n}> {}\n\n/**\n * Runs `check` (SvelteKit's `updated.check`) as an Effect that succeeds with\n * whether a new version is available and fails with {@link UpdateCheckError}\n * if the promise rejects (or `check` throws).\n */\nexport function checkForUpdateWith(\n check: () => Promise<boolean>,\n): Effect.Effect<boolean, UpdateCheckError> {\n return Effect.tryPromise({\n try: () => check(),\n catch: (cause) => new UpdateCheckError({ cause }),\n });\n}\n\n// ─── CurrentPage ─────────────────────────────────────────────────────────────\n\n/** The service shape behind `State.CurrentPage`. */\nexport interface CurrentPageShape<P extends ReadonlyPage = ReadonlyPage> {\n /** Snapshots the current page when run. */\n readonly get: Effect.Effect<PageSnapshot<P>>;\n /** The current page, then a fresh snapshot whenever any of its fields changes. */\n readonly changes: Stream.Stream<PageSnapshot<P>>;\n}\n\n/** Builds a {@link CurrentPageShape} reading `readPage()` and watching it with `watch`. */\nexport function makeCurrentPage<P extends ReadonlyPage>(\n readPage: () => P,\n watch: Watch,\n): CurrentPageShape<P> {\n const read = (): PageSnapshot<P> => snapshotPage(readPage());\n return { get: Effect.sync(read), changes: watchedStream(watch, read) };\n}\n"],"mappings":";;;;;;;;;;AA+DA,SAAgB,aAAqC,MAA0B;CAC7E,OAAO;EACL,KAAK,KAAK;EACV,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,MAAM,KAAK;EACX,OAAO,KAAK;EACZ,MAAM,KAAK;EACX,SAAS,KAAK;CAChB;AACF;;;;;;;AAQA,SAAgB,mBACd,uBACA,UACgC;CAChC,MAAM,QAAQ,OAAO,QAAQ,MAAM,UAA2B,CAAC;CAE/D,MAAM,YAAY,OAAO,aAAa,SAAS,CAAC,CAAC;CAIjD,4BAA4B;EAC1B,MAAM,YAAY,OAAO,aAAa,SAAS,CAAC,CAAC;CACnD,CAAC;CACD,OAAO,OAAO,UAAU,KAAK;AAC/B;;;;;;;;AAkBA,SAAgB,cAAiB,OAAc,MAAiC;CAC9E,OAAO,OAAO,UAAa,UACzB,OAAO,eACL,OAAO,WACL,MAAM,OAAO,UAAU;EACrB,MAAM,YAAY,OAAO,KAAK;CAChC,CAAC,CACH,IACC,YAAY,OAAO,KAAK,OAAO,CAClC,CACF;AACF;;;;;;AAqCA,SAAgB,mBACd,YACmC;CACnC,MAAM,EAAE,MAAM,MAAM,IAAI,YAAY,OAAO,aAAa;CACxD,IAAI,SAAS,QAAQ,eAAe,QAAQ,aAAa,MAAM,OAAO,OAAO,KAAK;CAClF,OAAO,OAAO,KAAK;EAAE;EAAM;EAAM;EAAI;EAAY,OAAO,SAAS;EAAM;CAAS,CAAC;AACnF;;;;;;AASA,IAAa,mBAAb,cAAsC,KAAK,YAAY,kBAAkB,CAAC,CAEvE,CAAC;;;;;;AAOJ,SAAgB,mBACd,OAC0C;CAC1C,OAAO,OAAO,WAAW;EACvB,WAAW,MAAM;EACjB,QAAQ,UAAU,IAAI,iBAAiB,EAAE,MAAM,CAAC;CAClD,CAAC;AACH;;AAaA,SAAgB,gBACd,UACA,OACqB;CACrB,MAAM,aAA8B,aAAa,SAAS,CAAC;CAC3D,OAAO;EAAE,KAAK,OAAO,KAAK,IAAI;EAAG,SAAS,cAAc,OAAO,IAAI;CAAE;AACvE"}
|
package/dist/internal/auto.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ServerRuntime, UniversalRuntime } from "../app-runtime.js";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
|
-
import { Action, Actions,
|
|
3
|
+
import { Action, Actions, Load, RequestEvent, ServerLoad } from "@sveltejs/kit";
|
|
4
|
+
import { Handle, HandleClientError, HandleFetch, HandleServerError, Reroute } from "@sveltejs/kit/hooks";
|
|
4
5
|
//#region src/internal/auto.d.ts
|
|
5
6
|
type AnyEffect = Effect.Effect<unknown, unknown, never>;
|
|
6
7
|
type AnyRuntime = ServerRuntime<any, any> | UniversalRuntime<any, any>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto.js","names":[],"sources":["../../src/internal/auto.ts"],"sourcesContent":["/**\n * Runtime auto-wrappers used by the SvelteKit Vite plugin.\n *\n * The plugin replaces user-declared SvelteKit exports (`load`, `actions`,\n * `handle`, HTTP method handlers, etc.) with calls into the helpers in this\n * module. At runtime each helper detects whether the underlying value is an\n * Effect, a function returning an Effect, or a plain SvelteKit-compatible\n * function/value, and routes accordingly.\n *\n * When the plugin is configured with a `serverRuntime` / `clientRuntime`\n * module, that module's app-wide runtime (created with `makeServerRuntime` /\n * `makeUniversalRuntime`) is passed as the second argument to these helpers,\n * so plain-Effect exports get access to the application's services.\n *\n * This module is internal — the public Vite plugin generates references to it.\n */\n\nimport type {\n Action,\n Actions,\n Handle,\n HandleClientError,\n HandleFetch,\n HandleServerError,\n Load,\n RequestEvent,\n Reroute,\n ServerLoad,\n} from \"@sveltejs/kit\";\nimport { Effect, Exit } from \"effect\";\nimport {\n makeServerRuntime,\n makeUniversalRuntime,\n type ServerRuntime,\n type UniversalRuntime,\n} from \"../app-runtime.js\";\nimport { causeToThrowable } from \"./error.js\";\n\ntype AnyEffect = Effect.Effect<unknown, unknown, never>;\n\ntype AnyRuntime = ServerRuntime<any, any> | UniversalRuntime<any, any>;\n\n/**\n * Module shape accepted for the plugin's `serverRuntime` / `clientRuntime`\n * options: the runtime can be the default export or a named `runtime` export.\n */\nexport interface RuntimeModule {\n readonly runtime?: AnyRuntime;\n readonly default?: AnyRuntime;\n}\n\n// Default runtimes (no application layer), created lazily and shared across\n// all requests in the process.\nlet defaultServerRuntime: ServerRuntime<any, any> | undefined;\nlet defaultUniversalRuntime: UniversalRuntime<any, any> | undefined;\n\n/** Extract the runtime from a runtime module, if any. */\nconst runtimeOfModule = (mod?: RuntimeModule): AnyRuntime | undefined =>\n mod?.runtime ?? mod?.default;\n\n/** Distinguish a ServerRuntime from a UniversalRuntime structurally. */\nconst isServerRuntime = (runtime: AnyRuntime): runtime is ServerRuntime<any, any> =>\n \"serverLoad\" in runtime;\n\n/** The server runtime for a module, falling back to the shared default. */\nconst serverRuntimeOf = (mod?: RuntimeModule): ServerRuntime<any, any> => {\n const runtime = runtimeOfModule(mod);\n if (runtime !== undefined && isServerRuntime(runtime)) return runtime;\n return (defaultServerRuntime ??= makeServerRuntime<any, any>());\n};\n\n/** The universal runtime for a module, falling back to the shared default. */\nconst universalRuntimeOf = (mod?: RuntimeModule): UniversalRuntime<any, any> => {\n const runtime = runtimeOfModule(mod);\n if (runtime !== undefined && !isServerRuntime(runtime)) return runtime;\n return (defaultUniversalRuntime ??= makeUniversalRuntime<any, any>());\n};\n\n/** Run an effect without any request context (e.g. `init` hooks). */\nasync function runBare(effect: AnyEffect, runtime?: AnyRuntime): Promise<unknown> {\n const exit = runtime\n ? ((await runtime.runtime.runPromiseExit(effect)) as Exit.Exit<unknown, unknown>)\n : await Effect.runPromiseExit(effect);\n\n return Exit.match(exit, {\n onFailure: (cause) => {\n throw causeToThrowable(cause);\n },\n onSuccess: (value) => value,\n });\n}\n\nfunction isEffectValue(value: unknown): value is AnyEffect {\n return Effect.isEffect(value as never);\n}\n\ntype LoadLikeInput = undefined | AnyEffect | ((event: any) => unknown);\n\n/**\n * Wraps a value intended to be a SvelteKit universal `load` export.\n * Used by the Vite plugin for `+page.ts` / `+layout.ts`.\n */\nexport function wrapLoad<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Load {\n if (value === undefined) return undefined as never;\n\n return (async (event: Parameters<Load>[0]) => {\n const result = isEffectValue(value) ? value : (value as (event: unknown) => unknown)(event);\n if (!isEffectValue(result)) return result;\n\n // Reuse the universal runtime's load wrapper so client/server detection\n // and per-request services stay in one place.\n return universalRuntimeOf(runtimeMod).load(\n () => result as Effect.Effect<Record<string, unknown>, unknown, never>,\n )(event);\n }) as never;\n}\n\n/** Shared implementation for server-side, event-based wrappers. */\nfunction wrapServerEvent<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): undefined | ((event: RequestEvent) => Promise<unknown>) {\n if (value === undefined) return undefined;\n\n return async (event: RequestEvent) => {\n const result = isEffectValue(value)\n ? value\n : (value as (event: RequestEvent) => unknown)(event);\n if (!isEffectValue(result)) return result;\n\n return serverRuntimeOf(runtimeMod).runPromise(event, result);\n };\n}\n\n/**\n * Wraps a value intended to be a SvelteKit server `load` export.\n * Used by the Vite plugin for `+page.server.ts` / `+layout.server.ts`.\n */\nexport function wrapServerLoad<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : ServerLoad {\n return wrapServerEvent(value, runtimeMod) as never;\n}\n\n/**\n * Wraps a single SvelteKit action handler.\n */\nexport function wrapAction<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Action {\n return wrapServerEvent(value, runtimeMod) as never;\n}\n\n/**\n * Wraps a SvelteKit `actions` object, individually wrapping each entry.\n */\nexport function wrapActions<T extends Record<string, LoadLikeInput> | undefined>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Actions {\n if (value === undefined) return undefined as never;\n if (typeof value !== \"object\" || value === null) return value as never;\n\n const wrapped: Actions = {};\n for (const [key, fn] of Object.entries(value)) {\n const wrappedAction = wrapAction(fn as LoadLikeInput, runtimeMod);\n if (wrappedAction !== undefined) {\n wrapped[key] = wrappedAction;\n }\n }\n return wrapped as never;\n}\n\n/**\n * Wraps a SvelteKit `handle` hook export.\n */\nexport function wrapHandle<\n T extends undefined | AnyEffect | ((args: Parameters<Handle>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : Handle {\n if (value === undefined) return undefined as never;\n\n const handle: Handle = (input) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<Handle>[0]) => unknown)(input);\n if (!isEffectValue(result)) return result as Response | Promise<Response>;\n\n // Route through `handle` so the per-request runtime is installed on\n // `event.locals` for the rest of the request, like the explicit wrapper.\n return serverRuntimeOf(runtimeMod).handle(\n () => result as Effect.Effect<Response, unknown, never>,\n )(input) as Promise<Response>;\n };\n return handle as never;\n}\n\n/**\n * Wraps a SvelteKit `handleFetch` hook export.\n */\nexport function wrapHandleFetch<\n T extends undefined | AnyEffect | ((args: Parameters<HandleFetch>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : HandleFetch {\n if (value === undefined) return undefined as never;\n\n const handleFetch: HandleFetch = async (args) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<HandleFetch>[0]) => unknown)(args);\n if (!isEffectValue(result)) return result as Response | Promise<Response>;\n\n return serverRuntimeOf(runtimeMod).runPromise(args.event, result) as Promise<Response>;\n };\n return handleFetch as never;\n}\n\ntype AnyHandleError = HandleServerError | HandleClientError;\n\n/**\n * Wraps a SvelteKit `handleError` hook export.\n */\nexport function wrapHandleError<\n T extends undefined | AnyEffect | ((args: Parameters<AnyHandleError>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : AnyHandleError {\n if (value === undefined) return undefined as never;\n\n return (async (args: Parameters<AnyHandleError>[0]) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<AnyHandleError>[0]) => unknown)(args);\n if (!isEffectValue(result)) return result as ReturnType<AnyHandleError>;\n\n // Server errors carry a RequestEvent; client errors carry a NavigationEvent.\n const event = (args as { event?: RequestEvent }).event;\n const isServerEvent = event !== undefined && \"request\" in event;\n\n if (isServerEvent) {\n return serverRuntimeOf(runtimeMod).runPromise(event, result) as ReturnType<AnyHandleError>;\n }\n\n // Client-side: run on the bare app runtime (no request services).\n return runBare(result, runtimeOfModule(runtimeMod)) as ReturnType<AnyHandleError>;\n }) as never;\n}\n\n/**\n * Wraps a SvelteKit HTTP endpoint export (`GET`, `POST`, etc.).\n * Errors thrown by the underlying Effect propagate to SvelteKit's normal\n * error-handling pipeline (i.e. they are not silently swallowed). Use the\n * explicit `endpoint()` helper if you need the `exposeErrors` toggle.\n */\nexport function wrapEndpoint<T extends undefined | AnyEffect | ((event: RequestEvent) => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : (event: RequestEvent) => Response | Promise<Response> {\n return wrapServerEvent(value as LoadLikeInput, runtimeMod) as never;\n}\n\ntype RerouteEvent = Parameters<Reroute>[0];\n\n/**\n * Wraps a SvelteKit universal `reroute` hook export. The effect runs on the\n * universal runtime with an `HttpClient` backed by the event's `fetch`, on both\n * the server and the client.\n */\nexport function wrapReroute<T extends undefined | AnyEffect | ((event: RerouteEvent) => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Reroute {\n if (value === undefined) return undefined as never;\n\n return ((event: RerouteEvent) => {\n const result = isEffectValue(value)\n ? value\n : (value as (event: RerouteEvent) => unknown)(event);\n if (!isEffectValue(result)) return result as ReturnType<Reroute>;\n\n return universalRuntimeOf(runtimeMod).runPromise(event.fetch, result) as ReturnType<Reroute>;\n }) as never;\n}\n\n/**\n * Wraps a SvelteKit `init` hook export (server or client).\n * `init` runs once at startup; there is no request event available, but the\n * application runtime's services (if configured) are.\n */\nexport function wrapInit<T extends undefined | AnyEffect | (() => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : () => Promise<void> {\n if (value === undefined) return undefined as never;\n\n return (async () => {\n const result = isEffectValue(value) ? value : (value as () => unknown)();\n if (!isEffectValue(result)) {\n await result;\n return;\n }\n await runBare(result, runtimeOfModule(runtimeMod));\n }) as never;\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"auto.js","names":[],"sources":["../../src/internal/auto.ts"],"sourcesContent":["/**\n * Runtime auto-wrappers used by the SvelteKit Vite plugin.\n *\n * The plugin replaces user-declared SvelteKit exports (`load`, `actions`,\n * `handle`, HTTP method handlers, etc.) with calls into the helpers in this\n * module. At runtime each helper detects whether the underlying value is an\n * Effect, a function returning an Effect, or a plain SvelteKit-compatible\n * function/value, and routes accordingly.\n *\n * When the plugin is configured with a `serverRuntime` / `clientRuntime`\n * module, that module's app-wide runtime (created with `makeServerRuntime` /\n * `makeUniversalRuntime`) is passed as the second argument to these helpers,\n * so plain-Effect exports get access to the application's services.\n *\n * This module is internal — the public Vite plugin generates references to it.\n */\n\nimport type { Action, Actions, Load, RequestEvent, ServerLoad } from \"@sveltejs/kit\";\nimport type {\n Handle,\n HandleClientError,\n HandleFetch,\n HandleServerError,\n Reroute,\n} from \"@sveltejs/kit/hooks\";\nimport { Effect, Exit } from \"effect\";\nimport {\n makeServerRuntime,\n makeUniversalRuntime,\n type ServerRuntime,\n type UniversalRuntime,\n} from \"../app-runtime.js\";\nimport { causeToThrowable } from \"./error.js\";\n\ntype AnyEffect = Effect.Effect<unknown, unknown, never>;\n\ntype AnyRuntime = ServerRuntime<any, any> | UniversalRuntime<any, any>;\n\n/**\n * Module shape accepted for the plugin's `serverRuntime` / `clientRuntime`\n * options: the runtime can be the default export or a named `runtime` export.\n */\nexport interface RuntimeModule {\n readonly runtime?: AnyRuntime;\n readonly default?: AnyRuntime;\n}\n\n// Default runtimes (no application layer), created lazily and shared across\n// all requests in the process.\nlet defaultServerRuntime: ServerRuntime<any, any> | undefined;\nlet defaultUniversalRuntime: UniversalRuntime<any, any> | undefined;\n\n/** Extract the runtime from a runtime module, if any. */\nconst runtimeOfModule = (mod?: RuntimeModule): AnyRuntime | undefined =>\n mod?.runtime ?? mod?.default;\n\n/** Distinguish a ServerRuntime from a UniversalRuntime structurally. */\nconst isServerRuntime = (runtime: AnyRuntime): runtime is ServerRuntime<any, any> =>\n \"serverLoad\" in runtime;\n\n/** The server runtime for a module, falling back to the shared default. */\nconst serverRuntimeOf = (mod?: RuntimeModule): ServerRuntime<any, any> => {\n const runtime = runtimeOfModule(mod);\n if (runtime !== undefined && isServerRuntime(runtime)) return runtime;\n return (defaultServerRuntime ??= makeServerRuntime<any, any>());\n};\n\n/** The universal runtime for a module, falling back to the shared default. */\nconst universalRuntimeOf = (mod?: RuntimeModule): UniversalRuntime<any, any> => {\n const runtime = runtimeOfModule(mod);\n if (runtime !== undefined && !isServerRuntime(runtime)) return runtime;\n return (defaultUniversalRuntime ??= makeUniversalRuntime<any, any>());\n};\n\n/** Run an effect without any request context (e.g. `init` hooks). */\nasync function runBare(effect: AnyEffect, runtime?: AnyRuntime): Promise<unknown> {\n const exit = runtime\n ? ((await runtime.runtime.runPromiseExit(effect)) as Exit.Exit<unknown, unknown>)\n : await Effect.runPromiseExit(effect);\n\n return Exit.match(exit, {\n onFailure: (cause) => {\n throw causeToThrowable(cause);\n },\n onSuccess: (value) => value,\n });\n}\n\nfunction isEffectValue(value: unknown): value is AnyEffect {\n return Effect.isEffect(value as never);\n}\n\ntype LoadLikeInput = undefined | AnyEffect | ((event: any) => unknown);\n\n/**\n * Wraps a value intended to be a SvelteKit universal `load` export.\n * Used by the Vite plugin for `+page.ts` / `+layout.ts`.\n */\nexport function wrapLoad<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Load {\n if (value === undefined) return undefined as never;\n\n return (async (event: Parameters<Load>[0]) => {\n const result = isEffectValue(value) ? value : (value as (event: unknown) => unknown)(event);\n if (!isEffectValue(result)) return result;\n\n // Reuse the universal runtime's load wrapper so client/server detection\n // and per-request services stay in one place.\n return universalRuntimeOf(runtimeMod).load(\n () => result as Effect.Effect<Record<string, unknown>, unknown, never>,\n )(event);\n }) as never;\n}\n\n/** Shared implementation for server-side, event-based wrappers. */\nfunction wrapServerEvent<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): undefined | ((event: RequestEvent) => Promise<unknown>) {\n if (value === undefined) return undefined;\n\n return async (event: RequestEvent) => {\n const result = isEffectValue(value)\n ? value\n : (value as (event: RequestEvent) => unknown)(event);\n if (!isEffectValue(result)) return result;\n\n return serverRuntimeOf(runtimeMod).runPromise(event, result);\n };\n}\n\n/**\n * Wraps a value intended to be a SvelteKit server `load` export.\n * Used by the Vite plugin for `+page.server.ts` / `+layout.server.ts`.\n */\nexport function wrapServerLoad<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : ServerLoad {\n return wrapServerEvent(value, runtimeMod) as never;\n}\n\n/**\n * Wraps a single SvelteKit action handler.\n */\nexport function wrapAction<T extends LoadLikeInput>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Action {\n return wrapServerEvent(value, runtimeMod) as never;\n}\n\n/**\n * Wraps a SvelteKit `actions` object, individually wrapping each entry.\n */\nexport function wrapActions<T extends Record<string, LoadLikeInput> | undefined>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Actions {\n if (value === undefined) return undefined as never;\n if (typeof value !== \"object\" || value === null) return value as never;\n\n const wrapped: Actions = {};\n for (const [key, fn] of Object.entries(value)) {\n const wrappedAction = wrapAction(fn as LoadLikeInput, runtimeMod);\n if (wrappedAction !== undefined) {\n wrapped[key] = wrappedAction;\n }\n }\n return wrapped as never;\n}\n\n/**\n * Wraps a SvelteKit `handle` hook export.\n */\nexport function wrapHandle<\n T extends undefined | AnyEffect | ((args: Parameters<Handle>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : Handle {\n if (value === undefined) return undefined as never;\n\n const handle: Handle = (input) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<Handle>[0]) => unknown)(input);\n if (!isEffectValue(result)) return result as Response | Promise<Response>;\n\n // Route through `handle` so the per-request runtime is installed on\n // `event.locals` for the rest of the request, like the explicit wrapper.\n return serverRuntimeOf(runtimeMod).handle(\n () => result as Effect.Effect<Response, unknown, never>,\n )(input) as Promise<Response>;\n };\n return handle as never;\n}\n\n/**\n * Wraps a SvelteKit `handleFetch` hook export.\n */\nexport function wrapHandleFetch<\n T extends undefined | AnyEffect | ((args: Parameters<HandleFetch>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : HandleFetch {\n if (value === undefined) return undefined as never;\n\n const handleFetch: HandleFetch = async (args) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<HandleFetch>[0]) => unknown)(args);\n if (!isEffectValue(result)) return result as Response | Promise<Response>;\n\n return serverRuntimeOf(runtimeMod).runPromise(args.event, result) as Promise<Response>;\n };\n return handleFetch as never;\n}\n\ntype AnyHandleError = HandleServerError | HandleClientError;\n\n/**\n * Wraps a SvelteKit `handleError` hook export.\n */\nexport function wrapHandleError<\n T extends undefined | AnyEffect | ((args: Parameters<AnyHandleError>[0]) => unknown),\n>(value: T, runtimeMod?: RuntimeModule): T extends undefined ? undefined : AnyHandleError {\n if (value === undefined) return undefined as never;\n\n return (async (args: Parameters<AnyHandleError>[0]) => {\n const result = isEffectValue(value)\n ? value\n : (value as (args: Parameters<AnyHandleError>[0]) => unknown)(args);\n if (!isEffectValue(result)) return result as ReturnType<AnyHandleError>;\n\n // Server errors carry a RequestEvent; client errors carry a NavigationEvent.\n const event = (args as { event?: RequestEvent }).event;\n const isServerEvent = event !== undefined && \"request\" in event;\n\n if (isServerEvent) {\n return serverRuntimeOf(runtimeMod).runPromise(event, result) as ReturnType<AnyHandleError>;\n }\n\n // Client-side: run on the bare app runtime (no request services).\n return runBare(result, runtimeOfModule(runtimeMod)) as ReturnType<AnyHandleError>;\n }) as never;\n}\n\n/**\n * Wraps a SvelteKit HTTP endpoint export (`GET`, `POST`, etc.).\n * Errors thrown by the underlying Effect propagate to SvelteKit's normal\n * error-handling pipeline (i.e. they are not silently swallowed). Use the\n * explicit `endpoint()` helper if you need the `exposeErrors` toggle.\n */\nexport function wrapEndpoint<T extends undefined | AnyEffect | ((event: RequestEvent) => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : (event: RequestEvent) => Response | Promise<Response> {\n return wrapServerEvent(value as LoadLikeInput, runtimeMod) as never;\n}\n\ntype RerouteEvent = Parameters<Reroute>[0];\n\n/**\n * Wraps a SvelteKit universal `reroute` hook export. The effect runs on the\n * universal runtime with an `HttpClient` backed by the event's `fetch`, on both\n * the server and the client.\n */\nexport function wrapReroute<T extends undefined | AnyEffect | ((event: RerouteEvent) => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : Reroute {\n if (value === undefined) return undefined as never;\n\n return ((event: RerouteEvent) => {\n const result = isEffectValue(value)\n ? value\n : (value as (event: RerouteEvent) => unknown)(event);\n if (!isEffectValue(result)) return result as ReturnType<Reroute>;\n\n return universalRuntimeOf(runtimeMod).runPromise(event.fetch, result) as ReturnType<Reroute>;\n }) as never;\n}\n\n/**\n * Wraps a SvelteKit `init` hook export (server or client).\n * `init` runs once at startup; there is no request event available, but the\n * application runtime's services (if configured) are.\n */\nexport function wrapInit<T extends undefined | AnyEffect | (() => unknown)>(\n value: T,\n runtimeMod?: RuntimeModule,\n): T extends undefined ? undefined : () => Promise<void> {\n if (value === undefined) return undefined as never;\n\n return (async () => {\n const result = isEffectValue(value) ? value : (value as () => unknown)();\n if (!isEffectValue(result)) {\n await result;\n return;\n }\n await runBare(result, runtimeOfModule(runtimeMod));\n }) as never;\n}\n"],"mappings":"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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context, Effect, ManagedRuntime } from "effect";
|
|
2
|
-
import { SubmitFunction } from "
|
|
2
|
+
import { SubmitFunction } from "$app/forms";
|
|
3
3
|
//#region src/internal/enhance.d.ts
|
|
4
4
|
/** The input SvelteKit passes to a `SubmitFunction` before the request is sent. */
|
|
5
5
|
type SubmitInput = Parameters<SubmitFunction>[0];
|
|
@@ -9,30 +9,128 @@ type ResultCallback = Extract<Awaited<ReturnType<SubmitFunction>>, (...args: nev
|
|
|
9
9
|
type ResultOptions = Parameters<ResultCallback>[0];
|
|
10
10
|
/** A runtime the handler effects can run against (a `Context` or `ManagedRuntime`). */
|
|
11
11
|
type EnhanceRuntime<R> = Context.Context<R> | ManagedRuntime.ManagedRuntime<R, never>;
|
|
12
|
-
/**
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Effect-based handlers for the two phases of an enhanced form submission,
|
|
14
|
+
* plus `onError` for the errors they fail with. `ESubmit` / `EResult` are the
|
|
15
|
+
* errors `onSubmit` / `onResult` may fail with, and `E` (their union by
|
|
16
|
+
* default) the error `onError` receives. Each handler is called as a method of
|
|
17
|
+
* the handlers object, so `this` in a handler written as a method is that
|
|
18
|
+
* object.
|
|
19
|
+
*/
|
|
20
|
+
interface EnhanceHandlers<R = never, ESubmit = never, EResult = never, E = ESubmit | EResult> {
|
|
14
21
|
/**
|
|
15
22
|
* Runs before the request is sent. Call `input.cancel()` to abort the
|
|
16
23
|
* submission (the result phase then never runs). Use for optimistic UI or
|
|
17
24
|
* validation.
|
|
25
|
+
*
|
|
26
|
+
* If it fails with `ESubmit`, the submission is cancelled and the error goes
|
|
27
|
+
* to {@link EnhanceHandlers.onError | onError}.
|
|
18
28
|
*/
|
|
19
|
-
readonly onSubmit?: (input: SubmitInput) => Effect.Effect<void,
|
|
29
|
+
readonly onSubmit?: ((input: SubmitInput) => Effect.Effect<void, ESubmit, R>) | undefined;
|
|
20
30
|
/**
|
|
21
31
|
* Runs once the action responds, with the `ActionResult` and SvelteKit's
|
|
22
32
|
* `update()` (which applies the default behaviour — updating `page.form`,
|
|
23
33
|
* resetting the form, invalidating). If omitted, SvelteKit's default
|
|
24
34
|
* behaviour applies automatically.
|
|
35
|
+
*
|
|
36
|
+
* If it fails with `EResult`, the error goes to
|
|
37
|
+
* {@link EnhanceHandlers.onError | onError}; SvelteKit's default behaviour
|
|
38
|
+
* is not applied in its place.
|
|
25
39
|
*/
|
|
26
|
-
readonly onResult?: (options: ResultOptions) => Effect.Effect<void,
|
|
40
|
+
readonly onResult?: ((options: ResultOptions) => Effect.Effect<void, EResult, R>) | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Handles an error `onSubmit` or `onResult` failed with (`E`, the union of
|
|
43
|
+
* their error types), as `Effect.catch` would. It runs on the same runtime
|
|
44
|
+
* and must not fail itself.
|
|
45
|
+
*
|
|
46
|
+
* Write it after `onSubmit` / `onResult` for `error` to be inferred
|
|
47
|
+
* precisely. Written before a handler whose parameters are not annotated
|
|
48
|
+
* (such as `onResult: ({ result }) => ...`), it still type-checks, but
|
|
49
|
+
* `error` is `unknown`: TypeScript types `onError`'s parameter before it has
|
|
50
|
+
* seen that handler's error type. An annotated parameter (or a function
|
|
51
|
+
* passed by name) must accept every error the handlers fail with, in either
|
|
52
|
+
* order.
|
|
53
|
+
*
|
|
54
|
+
* Only failures reach it: a defect or interruption (in a handler or in
|
|
55
|
+
* `onError`) still rejects the promise SvelteKit awaits, as does a failure
|
|
56
|
+
* when `onError` is omitted (rejecting with the error itself, as if the
|
|
57
|
+
* handler ended in `Effect.orDie`). SvelteKit does not catch that rejection:
|
|
58
|
+
* it sends no request after a rejected `onSubmit`, applies no default result
|
|
59
|
+
* after a rejected `onResult`, and the browser reports an unhandled
|
|
60
|
+
* rejection.
|
|
61
|
+
*/
|
|
62
|
+
readonly onError?: ((error: E) => Effect.Effect<void, never, R>) | undefined;
|
|
27
63
|
}
|
|
28
64
|
/** Options for {@link makeSubmitFunction}. */
|
|
29
65
|
interface EnhanceOptions<R = never> {
|
|
30
66
|
/**
|
|
31
|
-
* The runtime to run the handler effects against
|
|
32
|
-
*
|
|
67
|
+
* The runtime to run the handler effects against, providing every service
|
|
68
|
+
* `R` they require. Required when the handlers (or `onError`) require
|
|
69
|
+
* services; omit it when they require none (`R = never`), and they run on
|
|
70
|
+
* the default runtime.
|
|
33
71
|
*/
|
|
34
|
-
readonly runtime?: EnhanceRuntime<R
|
|
72
|
+
readonly runtime?: EnhanceRuntime<R> | undefined;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The options argument of `Forms.enhance`, as a rest tuple: optional when the
|
|
76
|
+
* handlers require no services (`R = never`), and otherwise required, with a
|
|
77
|
+
* `runtime` that provides `R`. There is no ambient runtime to fall back on, so
|
|
78
|
+
* handlers that require services and run without one would die with a
|
|
79
|
+
* missing-service defect. A function that wraps `Forms.enhance` for a generic
|
|
80
|
+
* `R` takes its options as `...options: EnhanceOptionsArgs<R>` and forwards
|
|
81
|
+
* them unchanged.
|
|
82
|
+
*/
|
|
83
|
+
type EnhanceOptionsArgs<R> = [R] extends [never] ? [options?: EnhanceOptions<never> | undefined] : [options: EnhanceOptions<R> & {
|
|
84
|
+
readonly runtime: EnhanceRuntime<R>;
|
|
85
|
+
}];
|
|
86
|
+
/** The handler names {@link makeSubmitFunction} accepts. */
|
|
87
|
+
type EnhanceHandlerKey = keyof EnhanceHandlers;
|
|
88
|
+
/**
|
|
89
|
+
* Records which handlers a handlers object names: `Keys` is inferred from the
|
|
90
|
+
* object's keys, which TypeScript knows before it types any handler.
|
|
91
|
+
*/
|
|
92
|
+
type HandlerKeys<Keys extends EnhanceHandlerKey> = { readonly [Key in Keys]?: unknown; };
|
|
93
|
+
/** Whether `Errors` includes a handler error not inferred yet ({@link ErrorNotInferred}). */
|
|
94
|
+
type IsErrorNotInferred<Errors> = 0 extends 1 & Errors ? true : false;
|
|
95
|
+
/**
|
|
96
|
+
* The services a handler requires: `R`, or none while it is not inferred
|
|
97
|
+
* ({@link ServicesNotInferred}), as for an absent handler.
|
|
98
|
+
*
|
|
99
|
+
* Since `unknown` must count as none, so does every requirements type that
|
|
100
|
+
* `unknown` is assignable to: an effect typed as requiring `any` or `unknown`
|
|
101
|
+
* (to which a union with `unknown` collapses), such as one annotated
|
|
102
|
+
* `Effect.Effect<void, never, any>`, is treated as requiring no services, so
|
|
103
|
+
* no runtime is demanded for it. Such a type names no service a runtime could
|
|
104
|
+
* be checked against, and only a top type fits every handler in TypeScript's
|
|
105
|
+
* first inference pass.
|
|
106
|
+
*/
|
|
107
|
+
type RequiredServices<R> = unknown extends R ? never : R;
|
|
108
|
+
/** The errors of the handlers named in `Keys`. */
|
|
109
|
+
type HandlerErrors<Keys extends EnhanceHandlerKey, ESubmit, EResult> = ("onSubmit" extends Keys ? ESubmit : never) | ("onResult" extends Keys ? EResult : never);
|
|
110
|
+
/**
|
|
111
|
+
* The error an unannotated `onError` receives: the handlers' errors, or
|
|
112
|
+
* `unknown` while one of them is not inferred yet (`onError` written before a
|
|
113
|
+
* handler whose parameters are not annotated).
|
|
114
|
+
*/
|
|
115
|
+
type OnErrorInput<Errors> = IsErrorNotInferred<Errors> extends true ? unknown : Errors;
|
|
116
|
+
/**
|
|
117
|
+
* Requires `onError` to accept every error in `Errors` when its parameter is
|
|
118
|
+
* annotated (`E` is then inferred from the annotation). The check waits while
|
|
119
|
+
* a handler's error is not inferred yet, and applies once it is.
|
|
120
|
+
*/
|
|
121
|
+
type OnErrorAccepts<R, Errors, E> = IsErrorNotInferred<Errors> extends true ? unknown : [Errors] extends [E] ? unknown : OnErrorMustAccept<R, Errors>;
|
|
122
|
+
/** The `onError` that {@link OnErrorAccepts} requires. */
|
|
123
|
+
interface OnErrorMustAccept<R, Errors> {
|
|
124
|
+
readonly onError?: ((error: Errors) => Effect.Effect<void, never, R>) | undefined;
|
|
35
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* The handlers {@link makeSubmitFunction} accepts: {@link EnhanceHandlers},
|
|
128
|
+
* with each handler's requirements in a parameter of its own (`RSubmit`,
|
|
129
|
+
* `RResult`, `RError`). TypeScript infers one candidate per handler and does
|
|
130
|
+
* not union them, so a single requirements parameter would reject handlers
|
|
131
|
+
* that require different services even when the runtime provides them all.
|
|
132
|
+
*/
|
|
133
|
+
type EnhanceHandlersBy<RSubmit, RResult, RError, ESubmit, EResult, E> = Pick<EnhanceHandlers<RSubmit, ESubmit, EResult, E>, "onSubmit"> & Pick<EnhanceHandlers<RResult, ESubmit, EResult, E>, "onResult"> & Pick<EnhanceHandlers<RError, ESubmit, EResult, E>, "onError">;
|
|
36
134
|
//#endregion
|
|
37
|
-
export { EnhanceHandlers, EnhanceOptions, EnhanceRuntime, ResultOptions, SubmitInput };
|
|
135
|
+
export { EnhanceHandlerKey, EnhanceHandlers, EnhanceHandlersBy, EnhanceOptions, EnhanceOptionsArgs, EnhanceRuntime, HandlerErrors, HandlerKeys, IsErrorNotInferred, OnErrorAccepts, OnErrorInput, OnErrorMustAccept, RequiredServices, ResultOptions, SubmitInput };
|
|
38
136
|
//# sourceMappingURL=enhance.d.ts.map
|
package/dist/internal/enhance.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Context, Effect } from "effect";
|
|
2
2
|
//#region src/internal/enhance.ts
|
|
3
|
-
/** Run an `Effect<A,
|
|
3
|
+
/** Run an `Effect<A, E, R>` on the given runtime (or the default when none). */
|
|
4
4
|
const runPromiseWith = (runtime) => (effect) => {
|
|
5
5
|
if (runtime === void 0) return Effect.runPromise(effect);
|
|
6
6
|
return Context.isContext(runtime) ? Effect.runPromiseWith(runtime)(effect) : runtime.runPromise(effect);
|
|
@@ -8,14 +8,38 @@ const runPromiseWith = (runtime) => (effect) => {
|
|
|
8
8
|
/**
|
|
9
9
|
* Build a SvelteKit `SubmitFunction` from Effect-based handlers. See
|
|
10
10
|
* `Forms.enhance` for the public entry point and documentation.
|
|
11
|
+
*
|
|
12
|
+
* The type parameters are inferred, never written. `RSubmit`, `RResult` and
|
|
13
|
+
* `RError` are the services each handler requires (see
|
|
14
|
+
* {@link EnhanceHandlersBy}). `Keys` names the handlers present, and `E` (the
|
|
15
|
+
* error `onError` receives) is computed from their errors, or inferred from
|
|
16
|
+
* `onError`'s parameter annotation and then checked against them, so a
|
|
17
|
+
* handlers object type-checks whatever its property order (see
|
|
18
|
+
* {@link EnhanceHandlers.onError}). The options argument, and its `runtime`,
|
|
19
|
+
* are required when the handlers require any service, and the runtime must
|
|
20
|
+
* provide all of them (see {@link EnhanceOptionsArgs}).
|
|
21
|
+
*
|
|
22
|
+
* When a call does not type-check, TypeScript may report it against its first
|
|
23
|
+
* inference pass, which skips handlers whose parameters are not annotated. The
|
|
24
|
+
* defaults of the handler parameters ({@link ErrorNotInferred},
|
|
25
|
+
* {@link ServicesNotInferred}) accept any handler, so a missing or wrong
|
|
26
|
+
* runtime is reported on the call or on the runtime, never on a handler.
|
|
11
27
|
*/
|
|
12
|
-
const makeSubmitFunction = (handlers,
|
|
28
|
+
const makeSubmitFunction = (handlers, ...rest) => {
|
|
29
|
+
const options = rest[0];
|
|
13
30
|
const run = runPromiseWith(options?.runtime);
|
|
31
|
+
const phases = handlers;
|
|
32
|
+
const onError = handlers.onError;
|
|
33
|
+
const handleError = onError === void 0 ? void 0 : (error) => onError.call(handlers, error);
|
|
14
34
|
return async (input) => {
|
|
15
|
-
|
|
16
|
-
if (
|
|
17
|
-
const onResult =
|
|
18
|
-
|
|
35
|
+
const submit = phases.onSubmit?.(input);
|
|
36
|
+
if (submit !== void 0) await run(handleError === void 0 ? submit : submit.pipe(Effect.catch((error) => Effect.sync(() => input.cancel()).pipe(Effect.andThen(handleError(error))))));
|
|
37
|
+
const { onResult } = phases;
|
|
38
|
+
if (!onResult) return void 0;
|
|
39
|
+
return (resultOptions) => {
|
|
40
|
+
const result = onResult.call(handlers, resultOptions);
|
|
41
|
+
return run(handleError === void 0 ? result : result.pipe(Effect.catch(handleError)));
|
|
42
|
+
};
|
|
19
43
|
};
|
|
20
44
|
};
|
|
21
45
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enhance.js","names":[],"sources":["../../src/internal/enhance.ts"],"sourcesContent":["/**\n * The runtime-agnostic core of the `use:enhance` bridge, kept free of any\n * `$app/*` import so it can be unit-tested outside a SvelteKit app build.\n */\n\nimport type { SubmitFunction } from \"@sveltejs/kit\";\nimport { Context, Effect, ManagedRuntime } from \"effect\";\n\n/** The input SvelteKit passes to a `SubmitFunction` before the request is sent. */\nexport type SubmitInput = Parameters<SubmitFunction>[0];\n\n/** The result callback a `SubmitFunction` may return, run once the action responds. */\ntype ResultCallback = Extract<Awaited<ReturnType<SubmitFunction>>, (...args: never) => unknown>;\n\n/** The options passed to the result callback (`result`, `update`, ...). */\nexport type ResultOptions = Parameters<ResultCallback>[0];\n\n/** A runtime the handler effects can run against (a `Context` or `ManagedRuntime`). */\nexport type EnhanceRuntime<R> = Context.Context<R> | ManagedRuntime.ManagedRuntime<R, never>;\n\n/** Effect-based handlers for the two phases of an enhanced form submission. */\nexport interface EnhanceHandlers<R = never> {\n /**\n * Runs before the request is sent. Call `input.cancel()` to abort the\n * submission (the result phase then never runs). Use for optimistic UI or\n * validation.\n */\n readonly onSubmit?: (input: SubmitInput) => Effect.Effect<void, never, R>;\n /**\n * Runs once the action responds, with the `ActionResult` and SvelteKit's\n * `update()` (which applies the default behaviour — updating `page.form`,\n * resetting the form, invalidating). If omitted, SvelteKit's default\n * behaviour applies automatically.\n */\n readonly onResult?: (options: ResultOptions) => Effect.Effect<void, never, R>;\n}\n\n/** Options for {@link makeSubmitFunction}. */\nexport interface EnhanceOptions<R = never> {\n /**\n * The runtime to run the handler effects against. Omit when the handlers\n * require no services (`R = never`); they then run on the default runtime.\n */\n readonly runtime?: EnhanceRuntime<R>;\n}\n\n/** Run an `Effect<A, never, R>` on the given runtime (or the default when none). */\nconst runPromiseWith =\n <R>(runtime: EnhanceRuntime<R> | undefined) =>\n <A>(effect: Effect.Effect<A, never, R>): Promise<A> => {\n if (runtime === undefined) return Effect.runPromise(effect as Effect.Effect<A, never, never>);\n return Context.isContext(runtime)\n ? Effect.runPromiseWith(runtime)(effect)\n : runtime.runPromise(effect);\n };\n\n/**\n * Build a SvelteKit `SubmitFunction` from Effect-based handlers. See\n * `Forms.enhance` for the public entry point and documentation.\n */\nexport const makeSubmitFunction = <R = never>(\n handlers: EnhanceHandlers<R>,\n options?: EnhanceOptions<R>,\n): SubmitFunction => {\n const run = runPromiseWith(options?.runtime);\n return async (input) => {\n if (handlers.onSubmit) await run(handlers.onSubmit(input));\n // Returning `undefined` lets SvelteKit apply its default result behaviour.\n if (!handlers.onResult) return undefined;\n const onResult = handlers.onResult;\n return (resultOptions) => run(onResult(resultOptions));\n };\n};\n"],"mappings":";;;AA+CA,MAAM,kBACA,aACA,WAAmD;CACrD,IAAI,YAAY,KAAA,GAAW,OAAO,OAAO,WAAW,MAAwC;CAC5F,OAAO,QAAQ,UAAU,OAAO,IAC5B,OAAO,eAAe,OAAO,CAAC,CAAC,MAAM,IACrC,QAAQ,WAAW,MAAM;AAC/B;;;;;AAMF,MAAa,sBACX,UACA,YACmB;CACnB,MAAM,MAAM,eAAe,SAAS,OAAO;CAC3C,OAAO,OAAO,UAAU;EACtB,IAAI,SAAS,UAAU,MAAM,IAAI,SAAS,SAAS,KAAK,CAAC;EAEzD,IAAI,CAAC,SAAS,UAAU,OAAO,KAAA;EAC/B,MAAM,WAAW,SAAS;EAC1B,QAAQ,kBAAkB,IAAI,SAAS,aAAa,CAAC;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"enhance.js","names":[],"sources":["../../src/internal/enhance.ts"],"sourcesContent":["/**\n * The runtime-agnostic core of the `use:enhance` bridge, kept free of any\n * `$app/*` import so it can be unit-tested outside a SvelteKit app build.\n */\n\nimport type { SubmitFunction } from \"$app/forms\";\nimport { Context, Effect, ManagedRuntime } from \"effect\";\n\n/** The input SvelteKit passes to a `SubmitFunction` before the request is sent. */\nexport type SubmitInput = Parameters<SubmitFunction>[0];\n\n/** The result callback a `SubmitFunction` may return, run once the action responds. */\ntype ResultCallback = Extract<Awaited<ReturnType<SubmitFunction>>, (...args: never) => unknown>;\n\n/** The options passed to the result callback (`result`, `update`, ...). */\nexport type ResultOptions = Parameters<ResultCallback>[0];\n\n/** A runtime the handler effects can run against (a `Context` or `ManagedRuntime`). */\nexport type EnhanceRuntime<R> = Context.Context<R> | ManagedRuntime.ManagedRuntime<R, never>;\n\n/**\n * Effect-based handlers for the two phases of an enhanced form submission,\n * plus `onError` for the errors they fail with. `ESubmit` / `EResult` are the\n * errors `onSubmit` / `onResult` may fail with, and `E` (their union by\n * default) the error `onError` receives. Each handler is called as a method of\n * the handlers object, so `this` in a handler written as a method is that\n * object.\n */\nexport interface EnhanceHandlers<\n R = never,\n ESubmit = never,\n EResult = never,\n E = ESubmit | EResult,\n> {\n /**\n * Runs before the request is sent. Call `input.cancel()` to abort the\n * submission (the result phase then never runs). Use for optimistic UI or\n * validation.\n *\n * If it fails with `ESubmit`, the submission is cancelled and the error goes\n * to {@link EnhanceHandlers.onError | onError}.\n */\n readonly onSubmit?: ((input: SubmitInput) => Effect.Effect<void, ESubmit, R>) | undefined;\n /**\n * Runs once the action responds, with the `ActionResult` and SvelteKit's\n * `update()` (which applies the default behaviour — updating `page.form`,\n * resetting the form, invalidating). If omitted, SvelteKit's default\n * behaviour applies automatically.\n *\n * If it fails with `EResult`, the error goes to\n * {@link EnhanceHandlers.onError | onError}; SvelteKit's default behaviour\n * is not applied in its place.\n */\n readonly onResult?: ((options: ResultOptions) => Effect.Effect<void, EResult, R>) | undefined;\n /**\n * Handles an error `onSubmit` or `onResult` failed with (`E`, the union of\n * their error types), as `Effect.catch` would. It runs on the same runtime\n * and must not fail itself.\n *\n * Write it after `onSubmit` / `onResult` for `error` to be inferred\n * precisely. Written before a handler whose parameters are not annotated\n * (such as `onResult: ({ result }) => ...`), it still type-checks, but\n * `error` is `unknown`: TypeScript types `onError`'s parameter before it has\n * seen that handler's error type. An annotated parameter (or a function\n * passed by name) must accept every error the handlers fail with, in either\n * order.\n *\n * Only failures reach it: a defect or interruption (in a handler or in\n * `onError`) still rejects the promise SvelteKit awaits, as does a failure\n * when `onError` is omitted (rejecting with the error itself, as if the\n * handler ended in `Effect.orDie`). SvelteKit does not catch that rejection:\n * it sends no request after a rejected `onSubmit`, applies no default result\n * after a rejected `onResult`, and the browser reports an unhandled\n * rejection.\n */\n readonly onError?: ((error: E) => Effect.Effect<void, never, R>) | undefined;\n}\n\n/** Options for {@link makeSubmitFunction}. */\nexport interface EnhanceOptions<R = never> {\n /**\n * The runtime to run the handler effects against, providing every service\n * `R` they require. Required when the handlers (or `onError`) require\n * services; omit it when they require none (`R = never`), and they run on\n * the default runtime.\n */\n readonly runtime?: EnhanceRuntime<R> | undefined;\n}\n\n/**\n * The options argument of `Forms.enhance`, as a rest tuple: optional when the\n * handlers require no services (`R = never`), and otherwise required, with a\n * `runtime` that provides `R`. There is no ambient runtime to fall back on, so\n * handlers that require services and run without one would die with a\n * missing-service defect. A function that wraps `Forms.enhance` for a generic\n * `R` takes its options as `...options: EnhanceOptionsArgs<R>` and forwards\n * them unchanged.\n */\nexport type EnhanceOptionsArgs<R> = [R] extends [never]\n ? [options?: EnhanceOptions<never> | undefined]\n : [options: EnhanceOptions<R> & { readonly runtime: EnhanceRuntime<R> }];\n\n/** The handler names {@link makeSubmitFunction} accepts. */\nexport type EnhanceHandlerKey = keyof EnhanceHandlers;\n\n/**\n * Records which handlers a handlers object names: `Keys` is inferred from the\n * object's keys, which TypeScript knows before it types any handler.\n */\nexport type HandlerKeys<Keys extends EnhanceHandlerKey> = { readonly [Key in Keys]?: unknown };\n\n/**\n * The default of a handler's error (`ESubmit` / `EResult`) while TypeScript\n * has not inferred it: for a handler it types after `onError`, for one it\n * skips in its first inference pass (a handler whose parameters are not\n * annotated), or for one that is absent (and left out by `Keys`).\n *\n * It is `any` so that every handler type-checks against it, whatever it fails\n * with: when a call does not type-check, TypeScript may report the errors\n * against its first-pass inference, and a handler that did not fit this\n * default would then be blamed for a missing or wrong runtime. Detected with\n * {@link IsErrorNotInferred}, never left in `onError`'s parameter type.\n */\nexport type ErrorNotInferred = any;\n\n/** Whether `Errors` includes a handler error not inferred yet ({@link ErrorNotInferred}). */\nexport type IsErrorNotInferred<Errors> = 0 extends 1 & Errors ? true : false;\n\n/**\n * The default of a handler's requirements (`RSubmit` / `RResult` / `RError`)\n * while TypeScript has not inferred them: `unknown`, which every handler's\n * requirements are assignable to (see {@link ErrorNotInferred} for why), and\n * which {@link RequiredServices} counts as none.\n */\nexport type ServicesNotInferred = unknown;\n\n/**\n * The services a handler requires: `R`, or none while it is not inferred\n * ({@link ServicesNotInferred}), as for an absent handler.\n *\n * Since `unknown` must count as none, so does every requirements type that\n * `unknown` is assignable to: an effect typed as requiring `any` or `unknown`\n * (to which a union with `unknown` collapses), such as one annotated\n * `Effect.Effect<void, never, any>`, is treated as requiring no services, so\n * no runtime is demanded for it. Such a type names no service a runtime could\n * be checked against, and only a top type fits every handler in TypeScript's\n * first inference pass.\n */\nexport type RequiredServices<R> = unknown extends R ? never : R;\n\n/** The errors of the handlers named in `Keys`. */\nexport type HandlerErrors<Keys extends EnhanceHandlerKey, ESubmit, EResult> =\n | (\"onSubmit\" extends Keys ? ESubmit : never)\n | (\"onResult\" extends Keys ? EResult : never);\n\n/**\n * The error an unannotated `onError` receives: the handlers' errors, or\n * `unknown` while one of them is not inferred yet (`onError` written before a\n * handler whose parameters are not annotated).\n */\nexport type OnErrorInput<Errors> = IsErrorNotInferred<Errors> extends true ? unknown : Errors;\n\n/**\n * Requires `onError` to accept every error in `Errors` when its parameter is\n * annotated (`E` is then inferred from the annotation). The check waits while\n * a handler's error is not inferred yet, and applies once it is.\n */\nexport type OnErrorAccepts<R, Errors, E> =\n IsErrorNotInferred<Errors> extends true\n ? unknown\n : [Errors] extends [E]\n ? unknown\n : OnErrorMustAccept<R, Errors>;\n\n/** The `onError` that {@link OnErrorAccepts} requires. */\nexport interface OnErrorMustAccept<R, Errors> {\n readonly onError?: ((error: Errors) => Effect.Effect<void, never, R>) | undefined;\n}\n\n/** Run an `Effect<A, E, R>` on the given runtime (or the default when none). */\nconst runPromiseWith =\n <R>(runtime: EnhanceRuntime<R> | undefined) =>\n <A, E>(effect: Effect.Effect<A, E, R>): Promise<A> => {\n if (runtime === undefined) return Effect.runPromise(effect as Effect.Effect<A, E, never>);\n return Context.isContext(runtime)\n ? Effect.runPromiseWith(runtime)(effect)\n : runtime.runPromise(effect);\n };\n\n/**\n * The handlers {@link makeSubmitFunction} accepts: {@link EnhanceHandlers},\n * with each handler's requirements in a parameter of its own (`RSubmit`,\n * `RResult`, `RError`). TypeScript infers one candidate per handler and does\n * not union them, so a single requirements parameter would reject handlers\n * that require different services even when the runtime provides them all.\n */\nexport type EnhanceHandlersBy<RSubmit, RResult, RError, ESubmit, EResult, E> = Pick<\n EnhanceHandlers<RSubmit, ESubmit, EResult, E>,\n \"onSubmit\"\n> &\n Pick<EnhanceHandlers<RResult, ESubmit, EResult, E>, \"onResult\"> &\n Pick<EnhanceHandlers<RError, ESubmit, EResult, E>, \"onError\">;\n\n/**\n * Build a SvelteKit `SubmitFunction` from Effect-based handlers. See\n * `Forms.enhance` for the public entry point and documentation.\n *\n * The type parameters are inferred, never written. `RSubmit`, `RResult` and\n * `RError` are the services each handler requires (see\n * {@link EnhanceHandlersBy}). `Keys` names the handlers present, and `E` (the\n * error `onError` receives) is computed from their errors, or inferred from\n * `onError`'s parameter annotation and then checked against them, so a\n * handlers object type-checks whatever its property order (see\n * {@link EnhanceHandlers.onError}). The options argument, and its `runtime`,\n * are required when the handlers require any service, and the runtime must\n * provide all of them (see {@link EnhanceOptionsArgs}).\n *\n * When a call does not type-check, TypeScript may report it against its first\n * inference pass, which skips handlers whose parameters are not annotated. The\n * defaults of the handler parameters ({@link ErrorNotInferred},\n * {@link ServicesNotInferred}) accept any handler, so a missing or wrong\n * runtime is reported on the call or on the runtime, never on a handler.\n */\nexport const makeSubmitFunction = <\n RSubmit = ServicesNotInferred,\n RResult = ServicesNotInferred,\n RError = ServicesNotInferred,\n ESubmit = ErrorNotInferred,\n EResult = ErrorNotInferred,\n Keys extends EnhanceHandlerKey = never,\n E = OnErrorInput<HandlerErrors<Keys, ESubmit, EResult>>,\n>(\n handlers: EnhanceHandlersBy<RSubmit, RResult, RError, ESubmit, EResult, E> &\n HandlerKeys<Keys> &\n NoInfer<OnErrorAccepts<RError, HandlerErrors<Keys, ESubmit, EResult>, E>>,\n // The requirements are inferred from the handlers alone; the runtime is\n // then checked against their union.\n ...rest: NoInfer<\n EnhanceOptionsArgs<\n RequiredServices<RSubmit> | RequiredServices<RResult> | RequiredServices<RError>\n >\n >\n): SubmitFunction => {\n type R = RequiredServices<RSubmit> | RequiredServices<RResult> | RequiredServices<RError>;\n // Either branch of `EnhanceOptionsArgs<R>`: the `never` one only when `R`\n // is `never`, where the two coincide.\n const options = rest[0] as EnhanceOptions<R> | undefined;\n const run = runPromiseWith(options?.runtime);\n // Each handler requires a part of `R`, which the runtime provides in full.\n const phases = handlers as EnhanceHandlers<R, ESubmit, EResult, E>;\n // `E` is the union of the errors of the handlers present, so `onError`\n // accepts whatever either handler fails with.\n const onError = handlers.onError as\n | ((error: ESubmit | EResult) => Effect.Effect<void, never, R>)\n | undefined;\n // Each handler is called as a method of the handlers object (`this` is\n // `handlers`), as 0.5.0 called `onSubmit`.\n const handleError =\n onError === undefined ? undefined : (error: ESubmit | EResult) => onError.call(handlers, error);\n return async (input) => {\n // `onSubmit` and `onResult` are read on each submission, so a handler\n // replaced on the handlers object after `enhance()` is the one that runs.\n // `onResult` is read once `onSubmit` has run, so `onSubmit` may set it.\n const submit = phases.onSubmit?.(input);\n if (submit !== undefined) {\n await run(\n handleError === undefined\n ? submit\n : submit.pipe(\n Effect.catch((error) =>\n Effect.sync(() => input.cancel()).pipe(Effect.andThen(handleError(error))),\n ),\n ),\n );\n }\n const { onResult } = phases;\n // Returning `undefined` lets SvelteKit apply its default result behaviour.\n if (!onResult) return undefined;\n return (resultOptions) => {\n const result = onResult.call(handlers, resultOptions);\n return run(handleError === undefined ? result : result.pipe(Effect.catch(handleError)));\n };\n };\n};\n"],"mappings":";;;AAoLA,MAAM,kBACA,aACG,WAA+C;CACpD,IAAI,YAAY,KAAA,GAAW,OAAO,OAAO,WAAW,MAAoC;CACxF,OAAO,QAAQ,UAAU,OAAO,IAC5B,OAAO,eAAe,OAAO,CAAC,CAAC,MAAM,IACrC,QAAQ,WAAW,MAAM;AAC/B;;;;;;;;;;;;;;;;;;;;;AAoCF,MAAa,sBASX,UAKA,GAAG,SAKgB;CAInB,MAAM,UAAU,KAAK;CACrB,MAAM,MAAM,eAAe,SAAS,OAAO;CAE3C,MAAM,SAAS;CAGf,MAAM,UAAU,SAAS;CAKzB,MAAM,cACJ,YAAY,KAAA,IAAY,KAAA,KAAa,UAA6B,QAAQ,KAAK,UAAU,KAAK;CAChG,OAAO,OAAO,UAAU;EAItB,MAAM,SAAS,OAAO,WAAW,KAAK;EACtC,IAAI,WAAW,KAAA,GACb,MAAM,IACJ,gBAAgB,KAAA,IACZ,SACA,OAAO,KACL,OAAO,OAAO,UACZ,OAAO,WAAW,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,YAAY,KAAK,CAAC,CAAC,CAC3E,CACF,CACN;EAEF,MAAM,EAAE,aAAa;EAErB,IAAI,CAAC,UAAU,OAAO,KAAA;EACtB,QAAQ,kBAAkB;GACxB,MAAM,SAAS,SAAS,KAAK,UAAU,aAAa;GACpD,OAAO,IAAI,gBAAgB,KAAA,IAAY,SAAS,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC,CAAC;EACxF;CACF;AACF"}
|
package/dist/internal/error.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Cause } from "effect";
|
|
2
|
-
import { isHttpError, isRedirect } from "@sveltejs/kit";
|
|
2
|
+
import { error, isHttpError, isRedirect } from "@sveltejs/kit";
|
|
3
3
|
//#region src/internal/error.ts
|
|
4
4
|
/**
|
|
5
5
|
* Custom error type that preserves the original Effect Cause.
|
|
@@ -25,7 +25,28 @@ const causeToThrowable = (cause) => {
|
|
|
25
25
|
if (isRedirect(squashed) || isHttpError(squashed)) return squashed;
|
|
26
26
|
return new EffectCauseError(Cause.pretty(cause), cause);
|
|
27
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* `error()` with the message and the extra `App.Error` properties as separate
|
|
30
|
+
* arguments. Kit's typed overloads only admit a third argument once the app
|
|
31
|
+
* augments `App.Error`, which this library cannot see.
|
|
32
|
+
*/
|
|
33
|
+
const kitErrorWith = error;
|
|
34
|
+
/**
|
|
35
|
+
* Throw SvelteKit's `error()` for a string or `App.Error`-shaped body, without
|
|
36
|
+
* the `error(status, body)` overload Kit 3 deprecates (kit#16540): an object
|
|
37
|
+
* body is split into `error(status, message, properties)`.
|
|
38
|
+
*
|
|
39
|
+
* The resulting `HttpError` is the one the deprecated overload built: `status`
|
|
40
|
+
* always wins over a `status` field in the body, and a missing message becomes
|
|
41
|
+
* Kit's default `Error: <status>`. A non-string `message` field (outside the
|
|
42
|
+
* `App.Error` type) is dropped in favour of that default.
|
|
43
|
+
*/
|
|
44
|
+
const throwKitError = (status, body) => {
|
|
45
|
+
if (body === void 0 || typeof body === "string") return kitErrorWith(status, body);
|
|
46
|
+
const { message, ...properties } = body;
|
|
47
|
+
return kitErrorWith(status, typeof message === "string" ? message : void 0, properties);
|
|
48
|
+
};
|
|
28
49
|
//#endregion
|
|
29
|
-
export { EffectCauseError, causeToThrowable };
|
|
50
|
+
export { EffectCauseError, causeToThrowable, throwKitError };
|
|
30
51
|
|
|
31
52
|
//# sourceMappingURL=error.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","names":[],"sources":["../../src/internal/error.ts"],"sourcesContent":["import { isHttpError, isRedirect } from \"@sveltejs/kit\";\nimport { Cause } from \"effect\";\n\n/**\n * Custom error type that preserves the original Effect Cause.\n */\nexport class EffectCauseError extends Error {\n declare cause: Cause.Cause<unknown>;\n\n constructor(message: string, cause: Cause.Cause<unknown>) {\n super(message);\n this.name = \"EffectCauseError\";\n this.cause = cause;\n }\n}\n\n/**\n * Converts a failed Effect Cause into the value to `throw`.\n *\n * SvelteKit uses thrown `redirect()` and `error()` objects for control flow.\n * When one of those is raised inside an Effect (either thrown, surfacing as a\n * defect, or used as a typed failure) the original object is rethrown so\n * SvelteKit can handle it as intended. Anything else is wrapped in an\n * `EffectCauseError` that preserves the full Cause for debugging.\n */\nexport const causeToThrowable = (cause: Cause.Cause<unknown>): unknown => {\n const squashed = Cause.squash(cause);\n if (isRedirect(squashed) || isHttpError(squashed)) {\n return squashed;\n }\n return new EffectCauseError(Cause.pretty(cause), cause);\n};\n"],"mappings":";;;;;;AAMA,IAAa,mBAAb,cAAsC,MAAM;CAG1C,YAAY,SAAiB,OAA6B;EACxD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;;;;;;AAWA,MAAa,oBAAoB,UAAyC;CACxE,MAAM,WAAW,MAAM,OAAO,KAAK;CACnC,IAAI,WAAW,QAAQ,KAAK,YAAY,QAAQ,GAC9C,OAAO;CAET,OAAO,IAAI,iBAAiB,MAAM,OAAO,KAAK,GAAG,KAAK;AACxD"}
|
|
1
|
+
{"version":3,"file":"error.js","names":["kitError"],"sources":["../../src/internal/error.ts"],"sourcesContent":["import { error as kitError, isHttpError, isRedirect } from \"@sveltejs/kit\";\nimport { Cause } from \"effect\";\n\n/**\n * Custom error type that preserves the original Effect Cause.\n */\nexport class EffectCauseError extends Error {\n declare cause: Cause.Cause<unknown>;\n\n constructor(message: string, cause: Cause.Cause<unknown>) {\n super(message);\n this.name = \"EffectCauseError\";\n this.cause = cause;\n }\n}\n\n/**\n * Converts a failed Effect Cause into the value to `throw`.\n *\n * SvelteKit uses thrown `redirect()` and `error()` objects for control flow.\n * When one of those is raised inside an Effect (either thrown, surfacing as a\n * defect, or used as a typed failure) the original object is rethrown so\n * SvelteKit can handle it as intended. Anything else is wrapped in an\n * `EffectCauseError` that preserves the full Cause for debugging.\n */\nexport const causeToThrowable = (cause: Cause.Cause<unknown>): unknown => {\n const squashed = Cause.squash(cause);\n if (isRedirect(squashed) || isHttpError(squashed)) {\n return squashed;\n }\n return new EffectCauseError(Cause.pretty(cause), cause);\n};\n\n/**\n * `error()` with the message and the extra `App.Error` properties as separate\n * arguments. Kit's typed overloads only admit a third argument once the app\n * augments `App.Error`, which this library cannot see.\n */\nconst kitErrorWith = kitError as (\n status: number,\n message?: string,\n properties?: Readonly<Record<string, unknown>>,\n) => never;\n\n/**\n * Throw SvelteKit's `error()` for a string or `App.Error`-shaped body, without\n * the `error(status, body)` overload Kit 3 deprecates (kit#16540): an object\n * body is split into `error(status, message, properties)`.\n *\n * The resulting `HttpError` is the one the deprecated overload built: `status`\n * always wins over a `status` field in the body, and a missing message becomes\n * Kit's default `Error: <status>`. A non-string `message` field (outside the\n * `App.Error` type) is dropped in favour of that default.\n */\nexport const throwKitError = (\n status: number,\n body?: string | Readonly<Record<string, unknown>>,\n): never => {\n if (body === undefined || typeof body === \"string\") return kitErrorWith(status, body);\n const { message, ...properties } = body;\n return kitErrorWith(status, typeof message === \"string\" ? message : undefined, properties);\n};\n"],"mappings":";;;;;;AAMA,IAAa,mBAAb,cAAsC,MAAM;CAG1C,YAAY,SAAiB,OAA6B;EACxD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;;;;;;AAWA,MAAa,oBAAoB,UAAyC;CACxE,MAAM,WAAW,MAAM,OAAO,KAAK;CACnC,IAAI,WAAW,QAAQ,KAAK,YAAY,QAAQ,GAC9C,OAAO;CAET,OAAO,IAAI,iBAAiB,MAAM,OAAO,KAAK,GAAG,KAAK;AACxD;;;;;;AAOA,MAAM,eAAeA;;;;;;;;;;;AAgBrB,MAAa,iBACX,QACA,SACU;CACV,IAAI,SAAS,KAAA,KAAa,OAAO,SAAS,UAAU,OAAO,aAAa,QAAQ,IAAI;CACpF,MAAM,EAAE,SAAS,GAAG,eAAe;CACnC,OAAO,aAAa,QAAQ,OAAO,YAAY,WAAW,UAAU,KAAA,GAAW,UAAU;AAC3F"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../request-runtime.js";
|
|
2
2
|
import { Effect, Exit } from "effect";
|
|
3
|
-
import {
|
|
3
|
+
import { RemoteFormInvalidField } from "$app/server";
|
|
4
4
|
//#region src/internal/remote-run.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Maps a remote *form* handler's failure into SvelteKit's field issues, given
|
|
@@ -9,14 +9,14 @@ import { InvalidField } from "@sveltejs/kit";
|
|
|
9
9
|
* a generic failure. Receives the squashed handler failure.
|
|
10
10
|
*/
|
|
11
11
|
type FormErrorMapper = (error: unknown, ctx: {
|
|
12
|
-
readonly issue:
|
|
12
|
+
readonly issue: RemoteFormInvalidField<any>;
|
|
13
13
|
readonly data: unknown;
|
|
14
14
|
}) => never;
|
|
15
15
|
/** Runs a remote handler's effect and settles it (value or thrown via translator). */
|
|
16
16
|
type Runner = <A>(effect: Effect.Effect<A, unknown, any>) => Promise<A>;
|
|
17
17
|
/** Like {@link Runner}, but with the form's `issue` / `data` for error interop. */
|
|
18
18
|
type FormRunner = <A>(effect: Effect.Effect<A, unknown, any>, ctx: {
|
|
19
|
-
readonly issue:
|
|
19
|
+
readonly issue: RemoteFormInvalidField<any>;
|
|
20
20
|
readonly data: unknown;
|
|
21
21
|
}) => Promise<A>;
|
|
22
22
|
/** Runners that execute a remote-function handler's Effect on a request runtime, as `runRemote` returns them. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-run.js","names":[],"sources":["../../src/internal/remote-run.ts"],"sourcesContent":["/**\n * Run/settle helpers for the remote-function wrappers, factored out so they can\n * be unit-tested without importing `$app/server` (a SvelteKit virtual module\n * unavailable outside an app build). The `$app/server`-dependent resolvers live\n * in `remote-functions.ts`; this module only deals in `Exit`s.\n */\n\nimport type { InvalidField } from \"
|
|
1
|
+
{"version":3,"file":"remote-run.js","names":[],"sources":["../../src/internal/remote-run.ts"],"sourcesContent":["/**\n * Run/settle helpers for the remote-function wrappers, factored out so they can\n * be unit-tested without importing `$app/server` (a SvelteKit virtual module\n * unavailable outside an app build). The `$app/server`-dependent resolvers live\n * in `remote-functions.ts`; this module only deals in `Exit`s.\n */\n\nimport type { RemoteFormInvalidField as InvalidField } from \"$app/server\";\nimport { Cause, type Effect, Exit } from \"effect\";\nimport type { ErrorTranslator } from \"../request-runtime.js\";\nimport { SvelteKit } from \"../kit.js\";\n\n/** The default translator: Kit control-flow errors through, anything else a 500. */\nexport const defaultTranslate: ErrorTranslator = SvelteKit.translate;\n\n/**\n * Maps a remote *form* handler's failure into SvelteKit's field issues, given\n * the form's parsed `data` and the `issue` helper. It may call `invalid()` so a\n * structured/nested validation error drives field-level invalidation instead of\n * a generic failure. Receives the squashed handler failure.\n */\nexport type FormErrorMapper = (\n error: unknown,\n ctx: { readonly issue: InvalidField<any>; readonly data: unknown },\n) => never;\n\n/** Runs a remote handler's effect and settles it (value or thrown via translator). */\nexport type Runner = <A>(effect: Effect.Effect<A, unknown, any>) => Promise<A>;\n\n/** Like {@link Runner}, but with the form's `issue` / `data` for error interop. */\nexport type FormRunner = <A>(\n effect: Effect.Effect<A, unknown, any>,\n ctx: { readonly issue: InvalidField<any>; readonly data: unknown },\n) => Promise<A>;\n\n/** Runners that execute a remote-function handler's Effect on a request runtime, as `runRemote` returns them. */\nexport interface RunHelpers {\n readonly run: Runner;\n readonly runForm: FormRunner;\n}\n\n/** How to obtain an `Exit` for the current request, plus optional teardown. */\nexport type ExitResolver = () => {\n readonly runExit: <A>(effect: Effect.Effect<A, unknown, any>) => Promise<Exit.Exit<A, unknown>>;\n readonly dispose?: () => void;\n};\n\n/** Build the `run` / `runForm` helpers from an exit resolver and a translator. */\nexport const makeRunHelpers = (\n resolve: ExitResolver,\n translate: ErrorTranslator,\n formError?: FormErrorMapper,\n): RunHelpers => {\n const run: Runner = (effect) => {\n const { runExit, dispose } = resolve();\n return runExit(effect).then((exit) => {\n try {\n return Exit.isSuccess(exit) ? exit.value : translate(exit.cause);\n } finally {\n dispose?.();\n }\n });\n };\n const runForm: FormRunner = (effect, ctx) => {\n const { runExit, dispose } = resolve();\n return runExit(effect).then((exit) => {\n try {\n if (Exit.isSuccess(exit)) return exit.value;\n return formError ? formError(Cause.squash(exit.cause), ctx) : translate(exit.cause);\n } finally {\n dispose?.();\n }\n });\n };\n return { run, runForm };\n};\n"],"mappings":";;;;AAaA,MAAa,mBAAoC,UAAU;;AAmC3D,MAAa,kBACX,SACA,WACA,cACe;CACf,MAAM,OAAe,WAAW;EAC9B,MAAM,EAAE,SAAS,YAAY,QAAQ;EACrC,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,SAAS;GACpC,IAAI;IACF,OAAO,KAAK,UAAU,IAAI,IAAI,KAAK,QAAQ,UAAU,KAAK,KAAK;GACjE,UAAU;IACR,UAAU;GACZ;EACF,CAAC;CACH;CACA,MAAM,WAAuB,QAAQ,QAAQ;EAC3C,MAAM,EAAE,SAAS,YAAY,QAAQ;EACrC,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,SAAS;GACpC,IAAI;IACF,IAAI,KAAK,UAAU,IAAI,GAAG,OAAO,KAAK;IACtC,OAAO,YAAY,UAAU,MAAM,OAAO,KAAK,KAAK,GAAG,GAAG,IAAI,UAAU,KAAK,KAAK;GACpF,UAAU;IACR,UAAU;GACZ;EACF,CAAC;CACH;CACA,OAAO;EAAE;EAAK;CAAQ;AACxB"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { untrack } from "svelte";
|
|
2
|
+
//#region src/internal/watch.svelte.ts
|
|
3
|
+
/**
|
|
4
|
+
* The one runes-dependent piece of the `$app/state` bridge: watch a reactive
|
|
5
|
+
* read outside any component.
|
|
6
|
+
*
|
|
7
|
+
* `$app/state`'s `page` / `navigating` / `updated` are rune-backed, and Svelte
|
|
8
|
+
* offers no rune-free way to observe a signal, so this module is a `.svelte.ts`
|
|
9
|
+
* file (kept as `.svelte.js` in `dist/`, where the consumer's Svelte compiler
|
|
10
|
+
* processes it). Everything else lives in the rune-free `app-state.ts`,
|
|
11
|
+
* parameterised over {@link watch}, so it can be unit-tested in plain Node.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Calls `onValue` with `read()` on the next Svelte flush, then again each time
|
|
17
|
+
* a reactive value `read` touched changes. The effect lives in its own
|
|
18
|
+
* `$effect.root`, so it needs no component context; the returned function
|
|
19
|
+
* destroys it. On the server Svelte never runs effects, so `onValue` is never
|
|
20
|
+
* called there.
|
|
21
|
+
*/
|
|
22
|
+
function watch(read, onValue) {
|
|
23
|
+
return $effect.root(() => {
|
|
24
|
+
$effect(() => {
|
|
25
|
+
const value = read();
|
|
26
|
+
untrack(() => onValue(value));
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { watch };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=watch.svelte.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watch.svelte.js","names":[],"sources":["../../src/internal/watch.svelte.ts"],"sourcesContent":["/**\n * The one runes-dependent piece of the `$app/state` bridge: watch a reactive\n * read outside any component.\n *\n * `$app/state`'s `page` / `navigating` / `updated` are rune-backed, and Svelte\n * offers no rune-free way to observe a signal, so this module is a `.svelte.ts`\n * file (kept as `.svelte.js` in `dist/`, where the consumer's Svelte compiler\n * processes it). Everything else lives in the rune-free `app-state.ts`,\n * parameterised over {@link watch}, so it can be unit-tested in plain Node.\n *\n * @internal\n */\n\nimport { untrack } from \"svelte\";\n\n/**\n * Calls `onValue` with `read()` on the next Svelte flush, then again each time\n * a reactive value `read` touched changes. The effect lives in its own\n * `$effect.root`, so it needs no component context; the returned function\n * destroys it. On the server Svelte never runs effects, so `onValue` is never\n * called there.\n */\nexport function watch<A>(read: () => A, onValue: (value: A) => void): () => void {\n return $effect.root(() => {\n $effect(() => {\n const value = read();\n // Only `read` should be tracked; delivering the value must not subscribe\n // the effect to anything the consumer happens to touch.\n untrack(() => onValue(value));\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,MAAS,MAAe,SAAyC;CAC/E,OAAO,QAAQ,WAAW;EACxB,cAAc;GACZ,MAAM,QAAQ,KAAK;GAGnB,cAAc,QAAQ,KAAK,CAAC;EAC9B,CAAC;CACH,CAAC;AACH"}
|
package/dist/kit.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { causeToThrowable } from "./internal/error.js";
|
|
1
|
+
import { causeToThrowable, throwKitError } from "./internal/error.js";
|
|
2
2
|
import { Cause, Effect } from "effect";
|
|
3
|
-
import {
|
|
3
|
+
import { fail, redirect } from "@sveltejs/kit";
|
|
4
4
|
//#region src/kit.ts
|
|
5
5
|
/**
|
|
6
6
|
* Effect-native SvelteKit control-flow errors and a turnkey boundary translator.
|
|
@@ -93,7 +93,7 @@ var KitActionFailure = class extends Error {
|
|
|
93
93
|
const baseTranslate = (cause) => {
|
|
94
94
|
const squashed = Cause.squash(cause);
|
|
95
95
|
if (squashed instanceof KitRedirect) redirect(squashed.status, squashed.location);
|
|
96
|
-
if (squashed instanceof KitError)
|
|
96
|
+
if (squashed instanceof KitError) throwKitError(squashed.status, squashed.body);
|
|
97
97
|
if (squashed instanceof KitActionFailure) return fail(squashed.status, squashed.data);
|
|
98
98
|
throw causeToThrowable(cause);
|
|
99
99
|
};
|