@thomasfosterau/effect-sveltekit 0.5.0 → 0.7.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 +178 -83
- package/dist/Hooks.d.ts +3 -3
- package/dist/Hooks.js +1 -1
- package/dist/Hooks.js.map +1 -1
- package/dist/Navigation.d.ts +70 -17
- package/dist/Navigation.js +93 -19
- package/dist/Navigation.js.map +1 -1
- package/dist/Remote.d.ts +54 -35
- package/dist/Remote.js +22 -11
- package/dist/Remote.js.map +1 -1
- package/dist/State.d.ts +79 -6
- package/dist/State.js +117 -27
- package/dist/State.js.map +1 -1
- package/dist/adapter/assets.d.ts +24 -7
- package/dist/adapter/assets.js +58 -37
- package/dist/adapter/assets.js.map +1 -1
- package/dist/adapter/handler.d.ts +27 -12
- package/dist/adapter/handler.js +53 -26
- package/dist/adapter/handler.js.map +1 -1
- package/dist/adapter/index.d.ts +3 -3
- package/dist/adapter/index.js +1 -1
- package/dist/adapter/index.js.map +1 -1
- package/dist/adapter/serve.d.ts +6 -5
- package/dist/adapter/serve.js +3 -1
- package/dist/adapter/serve.js.map +1 -1
- package/dist/api-client.d.ts +3 -4
- package/dist/api-client.js +2 -1
- package/dist/api-client.js.map +1 -1
- package/dist/app-runtime.d.ts +12 -9
- package/dist/app-runtime.js +23 -14
- package/dist/app-runtime.js.map +1 -1
- package/dist/client/Hooks.d.ts +4 -4
- package/dist/client/Hooks.js +2 -1
- package/dist/client/Hooks.js.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/config.d.ts +7 -5
- package/dist/config.js +5 -34
- package/dist/config.js.map +1 -1
- package/dist/errors.d.ts +14 -16
- package/dist/errors.js +20 -12
- package/dist/errors.js.map +1 -1
- package/dist/forms.d.ts +70 -8
- package/dist/forms.js +69 -5
- package/dist/forms.js.map +1 -1
- package/dist/internal/app-state.d.ts +42 -5
- package/dist/internal/app-state.js +64 -15
- package/dist/internal/app-state.js.map +1 -1
- package/dist/internal/auto.d.ts +23 -14
- package/dist/internal/auto.js +50 -40
- package/dist/internal/auto.js.map +1 -1
- package/dist/internal/enhance.d.ts +114 -14
- package/dist/internal/enhance.js +33 -7
- package/dist/internal/enhance.js.map +1 -1
- package/dist/internal/error.d.ts +13 -0
- package/dist/internal/error.js +4 -3
- package/dist/internal/error.js.map +1 -1
- package/dist/internal/navigation-events.js +3 -1
- package/dist/internal/navigation-events.js.map +1 -1
- package/dist/internal/remote-run.d.ts +6 -6
- package/dist/internal/remote-run.js +13 -16
- package/dist/internal/remote-run.js.map +1 -1
- package/dist/internal/remote-validators.js +4 -3
- package/dist/internal/remote-validators.js.map +1 -1
- package/dist/internal/route-params.d.ts +1 -2
- package/dist/internal/sse.js +2 -1
- package/dist/internal/sse.js.map +1 -1
- package/dist/internal/watch.svelte.js +33 -0
- package/dist/internal/watch.svelte.js.map +1 -0
- package/dist/kit.d.ts +12 -11
- package/dist/kit.js +6 -2
- package/dist/kit.js.map +1 -1
- package/dist/realtime.d.ts +49 -30
- package/dist/realtime.js +90 -46
- package/dist/realtime.js.map +1 -1
- package/dist/remote-functions.d.ts +34 -18
- package/dist/remote-functions.js +78 -46
- package/dist/remote-functions.js.map +1 -1
- package/dist/remote-reactive.d.ts +8 -4
- package/dist/remote-reactive.js.map +1 -1
- package/dist/request-parse.d.ts +13 -13
- package/dist/request-parse.js +29 -15
- package/dist/request-parse.js.map +1 -1
- package/dist/request-runtime.d.ts +16 -11
- package/dist/request-runtime.js +28 -29
- package/dist/request-runtime.js.map +1 -1
- package/dist/request-services.d.ts +10 -8
- package/dist/request-services.js +3 -1
- package/dist/request-services.js.map +1 -1
- package/dist/response-headers.d.ts +2 -3
- package/dist/response-headers.js +2 -1
- package/dist/response-headers.js.map +1 -1
- package/dist/runtime.d.ts +8 -5
- package/dist/runtime.js +4 -1
- package/dist/runtime.js.map +1 -1
- package/dist/server/Endpoint.d.ts +17 -11
- package/dist/server/Endpoint.js +18 -4
- package/dist/server/Endpoint.js.map +1 -1
- package/dist/server/Hooks.d.ts +6 -6
- package/dist/server/Hooks.js +1 -1
- package/dist/server/Hooks.js.map +1 -1
- package/dist/server.d.ts +8 -7
- package/dist/server.js +8 -8
- package/dist/server.js.map +1 -1
- package/dist/streamed-load.d.ts +2 -3
- package/dist/streamed-load.js +1 -1
- package/dist/streamed-load.js.map +1 -1
- package/dist/testing.d.ts +15 -14
- package/dist/testing.js +27 -7
- package/dist/testing.js.map +1 -1
- package/dist/transport.d.ts +6 -7
- package/dist/transport.js +3 -6
- package/dist/transport.js.map +1 -1
- package/dist/universal.d.ts +3 -3
- package/dist/universal.js +1 -1
- package/dist/universal.js.map +1 -1
- package/dist/vite.d.ts +4 -4
- package/dist/vite.js +102 -103
- package/dist/vite.js.map +1 -1
- package/package.json +14 -11
- package/LICENSE +0 -21
package/dist/testing.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { ErrorTranslator } from "./request-runtime.js";
|
|
2
2
|
import { FormErrorMapper, RunHelpers } from "./internal/remote-run.js";
|
|
3
|
-
import
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Layer from "effect/Layer";
|
|
4
5
|
import { RequestEvent } from "@sveltejs/kit";
|
|
5
6
|
//#region src/testing.d.ts
|
|
6
7
|
/** Options for {@link TestRequestEvent}. */
|
|
7
|
-
interface TestRequestEventOptions {
|
|
8
|
+
export interface TestRequestEventOptions {
|
|
8
9
|
/**
|
|
9
10
|
* The request URL. Accepts a `string` or a `URL` instance.
|
|
10
11
|
* Defaults to `"http://localhost/"`.
|
|
@@ -22,10 +23,10 @@ interface TestRequestEventOptions {
|
|
|
22
23
|
*/
|
|
23
24
|
readonly params?: Record<string, string>;
|
|
24
25
|
/**
|
|
25
|
-
* Initial `event.locals` value
|
|
26
|
-
*
|
|
26
|
+
* Initial `event.locals` value, typed as your app's `App.Locals` (declare its
|
|
27
|
+
* fields in `src/app.d.ts`). Defaults to `{}`.
|
|
27
28
|
*/
|
|
28
|
-
readonly locals?:
|
|
29
|
+
readonly locals?: App.Locals;
|
|
29
30
|
/**
|
|
30
31
|
* Pre-seeded cookies as `{ name: value }` pairs.
|
|
31
32
|
* The backing store supports `get`, `getAll`, `set`, `delete`, and
|
|
@@ -36,7 +37,7 @@ interface TestRequestEventOptions {
|
|
|
36
37
|
* The `event.platform` value, if any.
|
|
37
38
|
* Pass a partial platform object matching the environment the handler targets.
|
|
38
39
|
*/
|
|
39
|
-
readonly platform?:
|
|
40
|
+
readonly platform?: App.Platform;
|
|
40
41
|
/**
|
|
41
42
|
* The `fetch` implementation used by `event.fetch`.
|
|
42
43
|
* Defaults to `globalThis.fetch`. Pass a custom function to intercept or
|
|
@@ -61,12 +62,12 @@ interface TestRequestEventOptions {
|
|
|
61
62
|
* });
|
|
62
63
|
* ```
|
|
63
64
|
*/
|
|
64
|
-
declare function TestRequestEvent(opts?: TestRequestEventOptions): RequestEvent;
|
|
65
|
+
export declare function TestRequestEvent(opts?: TestRequestEventOptions): RequestEvent;
|
|
65
66
|
/**
|
|
66
67
|
* Options shared by {@link runServerLoad}, {@link runAction}, and
|
|
67
68
|
* {@link runEndpoint}.
|
|
68
69
|
*/
|
|
69
|
-
interface TestRunOptions<R> {
|
|
70
|
+
export interface TestRunOptions<R> {
|
|
70
71
|
/**
|
|
71
72
|
* The `Layer` providing the handler effect's required services `R`.
|
|
72
73
|
* Omit when the handler has no service requirements (`R` is `never`).
|
|
@@ -82,7 +83,7 @@ interface TestRunOptions<R> {
|
|
|
82
83
|
/**
|
|
83
84
|
* Options for {@link runRemote}.
|
|
84
85
|
*/
|
|
85
|
-
interface RunRemoteOptions<R> {
|
|
86
|
+
export interface RunRemoteOptions<R> {
|
|
86
87
|
/** The `Layer` providing the remote handler's service requirements. */
|
|
87
88
|
readonly layer?: Layer.Layer<R>;
|
|
88
89
|
/**
|
|
@@ -118,7 +119,7 @@ interface RunRemoteOptions<R> {
|
|
|
118
119
|
* expect(data.items).toHaveLength(0);
|
|
119
120
|
* ```
|
|
120
121
|
*/
|
|
121
|
-
declare const runServerLoad: <R, A extends Record<string, any> | void = void>(fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<A>;
|
|
122
|
+
export declare const runServerLoad: <R, A extends Record<string, any> | void = void>(fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<A>;
|
|
122
123
|
/**
|
|
123
124
|
* Run an Effect-based form action handler under test.
|
|
124
125
|
*
|
|
@@ -131,7 +132,7 @@ declare const runServerLoad: <R, A extends Record<string, any> | void = void>(fn
|
|
|
131
132
|
* expect((result as any).success).toBe(true);
|
|
132
133
|
* ```
|
|
133
134
|
*/
|
|
134
|
-
declare const runAction: <R, A extends Record<string, any> | void = void>(fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<A>;
|
|
135
|
+
export declare const runAction: <R, A extends Record<string, any> | void = void>(fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<A>;
|
|
135
136
|
/**
|
|
136
137
|
* Run an Effect-based `+server.ts` endpoint handler under test.
|
|
137
138
|
*
|
|
@@ -144,7 +145,7 @@ declare const runAction: <R, A extends Record<string, any> | void = void>(fn: (e
|
|
|
144
145
|
* expect(response.status).toBe(200);
|
|
145
146
|
* ```
|
|
146
147
|
*/
|
|
147
|
-
declare const runEndpoint: <R>(fn: (event: RequestEvent) => Effect.Effect<Response, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<Response>;
|
|
148
|
+
export declare const runEndpoint: <R>(fn: (event: RequestEvent) => Effect.Effect<Response, unknown, R>, event: RequestEvent, opts?: TestRunOptions<R>) => Promise<Response>;
|
|
148
149
|
/**
|
|
149
150
|
* Build a `{ run, runForm }` helper pair for directly invoking remote-function
|
|
150
151
|
* Effect handlers under test.
|
|
@@ -168,7 +169,7 @@ declare const runEndpoint: <R>(fn: (event: RequestEvent) => Effect.Effect<Respon
|
|
|
168
169
|
* expect(items).toEqual([]);
|
|
169
170
|
* ```
|
|
170
171
|
*/
|
|
171
|
-
declare const runRemote: <R = never>(event: RequestEvent, opts?: RunRemoteOptions<R>) => RunHelpers;
|
|
172
|
+
export declare const runRemote: <R = never>(event: RequestEvent, opts?: RunRemoteOptions<R>) => RunHelpers;
|
|
172
173
|
//#endregion
|
|
173
|
-
export {
|
|
174
|
+
export type { FormErrorMapper, RunHelpers };
|
|
174
175
|
//# sourceMappingURL=testing.d.ts.map
|
package/dist/testing.js
CHANGED
|
@@ -1,28 +1,48 @@
|
|
|
1
1
|
import { SvelteKit } from "./kit.js";
|
|
2
2
|
import { makeRunHelpers } from "./internal/remote-run.js";
|
|
3
3
|
import { RequestRuntime, makeRuntimeAdapter } from "./request-runtime.js";
|
|
4
|
-
import
|
|
4
|
+
import "effect/Effect";
|
|
5
|
+
import * as Layer from "effect/Layer";
|
|
6
|
+
import * as Rec from "effect/Record";
|
|
7
|
+
import * as Arr from "effect/Array";
|
|
8
|
+
import * as Option from "effect/Option";
|
|
5
9
|
//#region src/testing.ts
|
|
6
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* In-memory Cookies implementation for use in {@link TestRequestEvent}: an
|
|
12
|
+
* ordered list, so `getAll()` returns cookies in the order they were first set
|
|
13
|
+
* (as SvelteKit's does), and `set` on an existing name replaces it in place.
|
|
14
|
+
*/
|
|
7
15
|
var TestCookies = class {
|
|
8
16
|
store;
|
|
9
17
|
constructor(initial = {}) {
|
|
10
|
-
this.store =
|
|
18
|
+
this.store = Arr.map(Rec.toEntries(initial), ([name, value]) => ({
|
|
19
|
+
name,
|
|
20
|
+
value
|
|
21
|
+
}));
|
|
11
22
|
}
|
|
12
23
|
get(name, _opts) {
|
|
13
|
-
return this.store.
|
|
24
|
+
return Option.getOrUndefined(Option.map(Arr.findFirst(this.store, (cookie) => cookie.name === name), (cookie) => cookie.value));
|
|
14
25
|
}
|
|
15
26
|
getAll(_opts) {
|
|
16
|
-
return
|
|
27
|
+
return Arr.map(this.store, ({ name, value }) => ({
|
|
17
28
|
name,
|
|
18
29
|
value
|
|
19
30
|
}));
|
|
20
31
|
}
|
|
21
32
|
set(name, value, _opts) {
|
|
22
|
-
this.store.
|
|
33
|
+
this.store = Option.match(Arr.findFirstIndex(this.store, (cookie) => cookie.name === name), {
|
|
34
|
+
onNone: () => Arr.append(this.store, {
|
|
35
|
+
name,
|
|
36
|
+
value
|
|
37
|
+
}),
|
|
38
|
+
onSome: (index) => Arr.map(this.store, (cookie, i) => i === index ? {
|
|
39
|
+
name,
|
|
40
|
+
value
|
|
41
|
+
} : cookie)
|
|
42
|
+
});
|
|
23
43
|
}
|
|
24
44
|
delete(name, _opts) {
|
|
25
|
-
this.store.
|
|
45
|
+
this.store = Arr.filter(this.store, (cookie) => cookie.name !== name);
|
|
26
46
|
}
|
|
27
47
|
serialize(name, value, _opts) {
|
|
28
48
|
return `${name}=${encodeURIComponent(value)}`;
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing.ts"],"sourcesContent":["/**\n * Framework-agnostic test utilities for `@thomasfosterau/effect-sveltekit`.\n *\n * Exports a minimal {@link TestRequestEvent} constructor and plain-async\n * runner helpers ({@link runServerLoad}, {@link runAction},\n * {@link runEndpoint}, {@link runRemote}) so Effect-based SvelteKit handlers\n * can be unit-tested without mocking the SvelteKit module graph or installing\n * `$app/server`.\n *\n * Ships under the `./testing` subpath of `@thomasfosterau/effect-sveltekit`.\n * It has no coupling to Vitest, Jest, or any other test framework — import\n * it from whichever test runner you use.\n *\n * @example\n * ```ts\n * import {\n * TestRequestEvent,\n * runServerLoad,\n * runAction,\n * runRemote,\n * } from \"@thomasfosterau/effect-sveltekit/testing\";\n * import { Effect } from \"effect\";\n *\n * const event = TestRequestEvent({ params: { id: \"1\" }, locals: { user } });\n *\n * // Test a server load:\n * const data = await runServerLoad(\n * (event) =>\n * Effect.gen(function* () {\n * const db = yield* Database;\n * return { item: yield* db.findById(event.params.id) };\n * }),\n * event,\n * { layer: TestDatabase.layer },\n * );\n *\n * // Test a remote function handler directly:\n * const { run } = runRemote(event, { layer: TestLayer });\n * const items = await run(listItems());\n * ```\n */\n\nimport type { RequestEvent } from \"@sveltejs/kit\";\nimport { Effect, Layer } from \"effect\";\nimport {\n makeRuntimeAdapter,\n RequestRuntime,\n type ErrorTranslator,\n type RequestRuntimeProvider,\n} from \"./request-runtime.js\";\nimport { SvelteKit } from \"./kit.js\";\nimport { makeRunHelpers, type FormErrorMapper, type RunHelpers } from \"./internal/remote-run.js\";\n\nexport type { RunHelpers, FormErrorMapper } from \"./internal/remote-run.js\";\n\n// ─── TestCookies ─────────────────────────────────────────────────────────────\n\n/** Map-backed Cookies implementation for use in {@link TestRequestEvent}. */\nclass TestCookies {\n private readonly store: Map<string, string>;\n\n constructor(initial: Record<string, string> = {}) {\n this.store = new Map(Object.entries(initial));\n }\n\n get(name: string, _opts?: unknown): string | undefined {\n return this.store.get(name);\n }\n\n getAll(_opts?: unknown): Array<{ name: string; value: string }> {\n return [...this.store.entries()].map(([name, value]) => ({ name, value }));\n }\n\n set(name: string, value: string, _opts?: unknown): void {\n this.store.set(name, value);\n }\n\n delete(name: string, _opts?: unknown): void {\n this.store.delete(name);\n }\n\n serialize(name: string, value: string, _opts?: unknown): string {\n return `${name}=${encodeURIComponent(value)}`;\n }\n}\n\n// ─── TestRequestEvent ─────────────────────────────────────────────────────────\n\n/** Options for {@link TestRequestEvent}. */\nexport interface TestRequestEventOptions {\n /**\n * The request URL. Accepts a `string` or a `URL` instance.\n * Defaults to `\"http://localhost/\"`.\n */\n readonly url?: string | URL;\n /** The HTTP method. Defaults to `\"GET\"`. */\n readonly method?: string;\n /** Additional HTTP headers added to the underlying `Request`. */\n readonly headers?: HeadersInit;\n /** The request body. Only usable with methods that accept a body. */\n readonly body?: BodyInit | null;\n /**\n * Route params (e.g. `{ id: \"123\" }` for a route like `/items/[id]`).\n * Defaults to `{}`.\n */\n readonly params?: Record<string, string>;\n /**\n * Initial `event.locals` value. Defaults to `{}`.\n * Cast to `App.Locals` — extend it with the properties your handlers need.\n */\n readonly locals?: Record<string, unknown>;\n /**\n * Pre-seeded cookies as `{ name: value }` pairs.\n * The backing store supports `get`, `getAll`, `set`, `delete`, and\n * `serialize`; the object is cast to SvelteKit's `Cookies` interface.\n */\n readonly cookies?: Record<string, string>;\n /**\n * The `event.platform` value, if any.\n * Pass a partial platform object matching the environment the handler targets.\n */\n readonly platform?: unknown;\n /**\n * The `fetch` implementation used by `event.fetch`.\n * Defaults to `globalThis.fetch`. Pass a custom function to intercept or\n * stub network calls made by the handler.\n */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Create a minimal {@link RequestEvent} for use in unit tests.\n *\n * All fields are optional — omit what the handler under test doesn't inspect.\n * Cookies are backed by an in-memory `Map`; mutations (`set`, `delete`) are\n * reflected in subsequent `get`/`getAll` calls on the same event.\n *\n * @example\n * ```ts\n * const event = TestRequestEvent({\n * url: \"http://localhost/items/42\",\n * params: { id: \"42\" },\n * locals: { user: { id: \"u1\", role: \"admin\" } },\n * cookies: { session: \"tok_test\" },\n * });\n * ```\n */\nexport function TestRequestEvent(opts: TestRequestEventOptions = {}): RequestEvent {\n const rawUrl = opts.url instanceof URL ? opts.url.toString() : (opts.url ?? \"http://localhost/\");\n const url = new URL(rawUrl);\n\n const init: RequestInit = { method: opts.method ?? \"GET\" };\n if (opts.headers !== undefined) init.headers = opts.headers;\n if (opts.body !== undefined) init.body = opts.body;\n\n const request = new Request(url.toString(), init);\n const cookies = new TestCookies(opts.cookies ?? {});\n const fetchFn = opts.fetch ?? globalThis.fetch;\n\n return {\n request,\n url,\n params: (opts.params ?? {}) as any,\n route: { id: null },\n fetch: fetchFn,\n cookies: cookies as any,\n locals: (opts.locals ?? {}) as any,\n platform: opts.platform as any,\n isDataRequest: false,\n isSubRequest: false,\n setHeaders: () => {},\n getClientAddress: () => \"127.0.0.1\",\n } as unknown as RequestEvent;\n}\n\n// ─── Options ──────────────────────────────────────────────────────────────────\n\n/**\n * Options shared by {@link runServerLoad}, {@link runAction}, and\n * {@link runEndpoint}.\n */\nexport interface TestRunOptions<R> {\n /**\n * The `Layer` providing the handler effect's required services `R`.\n * Omit when the handler has no service requirements (`R` is `never`).\n */\n readonly layer?: Layer.Layer<R>;\n /**\n * Translate a failed `Cause` at the boundary. Defaults to\n * {@link SvelteKit.translate} (Kit control-flow through; anything else\n * becomes an `EffectCauseError`).\n */\n readonly translateError?: ErrorTranslator;\n}\n\n/**\n * Options for {@link runRemote}.\n */\nexport interface RunRemoteOptions<R> {\n /** The `Layer` providing the remote handler's service requirements. */\n readonly layer?: Layer.Layer<R>;\n /**\n * Translate a failed `Cause` at the boundary. Defaults to\n * {@link SvelteKit.translate}.\n */\n readonly translateError?: ErrorTranslator;\n /**\n * Map a remote form handler's failure to SvelteKit field issues. Receives\n * the squashed handler failure and the `{ issue, data }` context. When\n * provided it is called instead of `translateError` on the form error path.\n */\n readonly formError?: FormErrorMapper;\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nconst makeAdapter = <R>(opts: TestRunOptions<R> | undefined) =>\n makeRuntimeAdapter(RequestRuntime.fromLayer((opts?.layer ?? Layer.empty) as Layer.Layer<R>), {\n translateError: opts?.translateError ?? SvelteKit.translate,\n });\n\n// ─── runServerLoad ────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based server `load` function under test.\n *\n * Wraps `fn` with `makeRuntimeAdapter` using the provided `opts.layer` (or\n * `Layer.empty` when omitted) and calls the resulting `ServerLoad` with\n * `event`. Errors are translated by `opts.translateError` (defaults to\n * {@link SvelteKit.translate}).\n *\n * @example\n * ```ts\n * const data = await runServerLoad(\n * (event) => Effect.gen(function* () {\n * const db = yield* Database;\n * return { items: yield* db.list() };\n * }),\n * TestRequestEvent(),\n * { layer: TestDatabase.layer },\n * );\n * expect(data.items).toHaveLength(0);\n * ```\n */\nexport const runServerLoad = <R, A extends Record<string, any> | void = void>(\n fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<A> => (makeAdapter(opts).serverLoad(fn) as (e: RequestEvent) => Promise<A>)(event);\n\n// ─── runAction ───────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based form action handler under test.\n *\n * @example\n * ```ts\n * const result = await runAction(\n * (_event) => Effect.succeed({ success: true }),\n * TestRequestEvent({ method: \"POST\" }),\n * );\n * expect((result as any).success).toBe(true);\n * ```\n */\nexport const runAction = <R, A extends Record<string, any> | void = void>(\n fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<A> => (makeAdapter(opts).action(fn) as (e: RequestEvent) => Promise<A>)(event);\n\n// ─── runEndpoint ──────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based `+server.ts` endpoint handler under test.\n *\n * @example\n * ```ts\n * const response = await runEndpoint(\n * (_event) => Effect.succeed(new Response(JSON.stringify({ ok: true }))),\n * TestRequestEvent({ url: \"http://localhost/api/ping\" }),\n * );\n * expect(response.status).toBe(200);\n * ```\n */\nexport const runEndpoint = <R>(\n fn: (event: RequestEvent) => Effect.Effect<Response, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<Response> => Promise.resolve(makeAdapter(opts).endpoint(fn)(event as any));\n\n// ─── runRemote ────────────────────────────────────────────────────────────────\n\n/**\n * Build a `{ run, runForm }` helper pair for directly invoking remote-function\n * Effect handlers under test.\n *\n * Unlike the production `query` / `command` / `form` helpers, which resolve the\n * request event via `$app/server.getRequestEvent()`, this resolves it from the\n * `event` argument you supply — no SvelteKit module-graph mocking required.\n *\n * Use `run` for `query` / `command` handlers and `runForm` for `form` handlers\n * that need the `issue` / `data` context.\n *\n * @example\n * ```ts\n * import { TestRequestEvent, runRemote } from \"@thomasfosterau/effect-sveltekit/testing\";\n *\n * const event = TestRequestEvent();\n * const { run } = runRemote(event, { layer: TestDatabase.layer });\n *\n * // Invoke the underlying Effect directly — no AppServer needed:\n * const items = await run(listItemsEffect());\n * expect(items).toEqual([]);\n * ```\n */\nexport const runRemote = <R = never>(\n event: RequestEvent,\n opts?: RunRemoteOptions<R>,\n): RunHelpers => {\n const translate = opts?.translateError ?? SvelteKit.translate;\n const layer = (opts?.layer ?? Layer.empty) as Layer.Layer<R>;\n const provider: RequestRuntimeProvider<R> = RequestRuntime.fromLayer(layer);\n return makeRunHelpers(\n () => ({ runExit: (effect) => provider.run(event).runPromiseExit(effect) }),\n translate,\n opts?.formError,\n );\n};\n"],"mappings":";;;;;;AA0DA,IAAM,cAAN,MAAkB;CAChB;CAEA,YAAY,UAAkC,CAAC,GAAG;EAChD,KAAK,QAAQ,IAAI,IAAI,OAAO,QAAQ,OAAO,CAAC;CAC9C;CAEA,IAAI,MAAc,OAAqC;EACrD,OAAO,KAAK,MAAM,IAAI,IAAI;CAC5B;CAEA,OAAO,OAAyD;EAC9D,OAAO,CAAC,GAAG,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY;GAAE;GAAM;EAAM,EAAE;CAC3E;CAEA,IAAI,MAAc,OAAe,OAAuB;EACtD,KAAK,MAAM,IAAI,MAAM,KAAK;CAC5B;CAEA,OAAO,MAAc,OAAuB;EAC1C,KAAK,MAAM,OAAO,IAAI;CACxB;CAEA,UAAU,MAAc,OAAe,OAAyB;EAC9D,OAAO,GAAG,KAAK,GAAG,mBAAmB,KAAK;CAC5C;AACF;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,iBAAiB,OAAgC,CAAC,GAAiB;CACjF,MAAM,SAAS,KAAK,eAAe,MAAM,KAAK,IAAI,SAAS,IAAK,KAAK,OAAO;CAC5E,MAAM,MAAM,IAAI,IAAI,MAAM;CAE1B,MAAM,OAAoB,EAAE,QAAQ,KAAK,UAAU,MAAM;CACzD,IAAI,KAAK,YAAY,KAAA,GAAW,KAAK,UAAU,KAAK;CACpD,IAAI,KAAK,SAAS,KAAA,GAAW,KAAK,OAAO,KAAK;CAE9C,MAAM,UAAU,IAAI,QAAQ,IAAI,SAAS,GAAG,IAAI;CAChD,MAAM,UAAU,IAAI,YAAY,KAAK,WAAW,CAAC,CAAC;CAClD,MAAM,UAAU,KAAK,SAAS,WAAW;CAEzC,OAAO;EACL;EACA;EACA,QAAS,KAAK,UAAU,CAAC;EACzB,OAAO,EAAE,IAAI,KAAK;EAClB,OAAO;EACE;EACT,QAAS,KAAK,UAAU,CAAC;EACzB,UAAU,KAAK;EACf,eAAe;EACf,cAAc;EACd,kBAAkB,CAAC;EACnB,wBAAwB;CAC1B;AACF;AA2CA,MAAM,eAAkB,SACtB,mBAAmB,eAAe,UAAW,MAAM,SAAS,MAAM,KAAwB,GAAG,EAC3F,gBAAgB,MAAM,kBAAkB,UAAU,UACpD,CAAC;;;;;;;;;;;;;;;;;;;;;;AAyBH,MAAa,iBACX,IACA,OACA,SACgB,YAAY,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,CAAqC,KAAK;;;;;;;;;;;;;AAgB5F,MAAa,aACX,IACA,OACA,SACgB,YAAY,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC,CAAqC,KAAK;;;;;;;;;;;;;AAgBxF,MAAa,eACX,IACA,OACA,SACsB,QAAQ,QAAQ,YAAY,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,KAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;AA2BpF,MAAa,aACX,OACA,SACe;CACf,MAAM,YAAY,MAAM,kBAAkB,UAAU;CACpD,MAAM,QAAS,MAAM,SAAS,MAAM;CACpC,MAAM,WAAsC,eAAe,UAAU,KAAK;CAC1E,OAAO,sBACE,EAAE,UAAU,WAAW,SAAS,IAAI,KAAK,CAAC,CAAC,eAAe,MAAM,EAAE,IACzE,WACA,MAAM,SACR;AACF"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing.ts"],"sourcesContent":["/**\n * Framework-agnostic test utilities for `@thomasfosterau/effect-sveltekit`.\n *\n * Exports a minimal {@link TestRequestEvent} constructor and plain-async\n * runner helpers ({@link runServerLoad}, {@link runAction},\n * {@link runEndpoint}, {@link runRemote}) so Effect-based SvelteKit handlers\n * can be unit-tested without mocking the SvelteKit module graph or installing\n * `$app/server`.\n *\n * Ships under the `./testing` subpath of `@thomasfosterau/effect-sveltekit`.\n * It has no coupling to Vitest, Jest, or any other test framework — import\n * it from whichever test runner you use.\n *\n * @example\n * ```ts\n * import {\n * TestRequestEvent,\n * runServerLoad,\n * runAction,\n * runRemote,\n * } from \"@thomasfosterau/effect-sveltekit/testing\";\n * import { Effect } from \"effect\";\n *\n * const event = TestRequestEvent({ params: { id: \"1\" }, locals: { user } });\n *\n * // Test a server load:\n * const data = await runServerLoad(\n * (event) =>\n * Effect.gen(function* () {\n * const db = yield* Database;\n * return { item: yield* db.findById(event.params.id) };\n * }),\n * event,\n * { layer: TestDatabase.layer },\n * );\n *\n * // Test a remote function handler directly:\n * const { run } = runRemote(event, { layer: TestLayer });\n * const items = await run(listItems());\n * ```\n */\n\nimport type { Cookies, RequestEvent } from \"@sveltejs/kit\";\nimport * as Effect from \"effect/Effect\";\nimport * as Arr from \"effect/Array\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Rec from \"effect/Record\";\nimport {\n makeRuntimeAdapter,\n RequestRuntime,\n type ErrorTranslator,\n type RequestRuntimeProvider,\n} from \"./request-runtime.js\";\nimport { SvelteKit } from \"./kit.js\";\nimport { makeRunHelpers, type FormErrorMapper, type RunHelpers } from \"./internal/remote-run.js\";\n\nexport type { RunHelpers, FormErrorMapper } from \"./internal/remote-run.js\";\n\n// ─── TestCookies ─────────────────────────────────────────────────────────────\n\ntype CookieParseOptions = Parameters<Cookies[\"get\"]>[1];\ntype CookieSerializeOptions = Parameters<Cookies[\"set\"]>[2];\n\n/** One stored cookie. */\ninterface TestCookie {\n readonly name: string;\n readonly value: string;\n}\n\n/**\n * In-memory Cookies implementation for use in {@link TestRequestEvent}: an\n * ordered list, so `getAll()` returns cookies in the order they were first set\n * (as SvelteKit's does), and `set` on an existing name replaces it in place.\n */\nclass TestCookies {\n private store: ReadonlyArray<TestCookie>;\n\n constructor(initial: Readonly<Record<string, string>> = {}) {\n this.store = Arr.map(Rec.toEntries(initial), ([name, value]) => ({ name, value }));\n }\n\n get(name: string, _opts?: CookieParseOptions): string | undefined {\n return Option.getOrUndefined(\n Option.map(\n Arr.findFirst(this.store, (cookie) => cookie.name === name),\n (cookie) => cookie.value,\n ),\n );\n }\n\n getAll(_opts?: CookieParseOptions): Array<{ name: string; value: string }> {\n return Arr.map(this.store, ({ name, value }) => ({ name, value }));\n }\n\n set(name: string, value: string, _opts?: CookieSerializeOptions): void {\n this.store = Option.match(\n Arr.findFirstIndex(this.store, (cookie) => cookie.name === name),\n {\n onNone: () => Arr.append(this.store, { name, value }),\n onSome: (index) =>\n Arr.map(this.store, (cookie, i) => (i === index ? { name, value } : cookie)),\n },\n );\n }\n\n delete(name: string, _opts?: CookieSerializeOptions): void {\n this.store = Arr.filter(this.store, (cookie) => cookie.name !== name);\n }\n\n serialize(name: string, value: string, _opts?: CookieSerializeOptions): string {\n return `${name}=${encodeURIComponent(value)}`;\n }\n}\n\n// ─── TestRequestEvent ─────────────────────────────────────────────────────────\n\n/** Options for {@link TestRequestEvent}. */\nexport interface TestRequestEventOptions {\n /**\n * The request URL. Accepts a `string` or a `URL` instance.\n * Defaults to `\"http://localhost/\"`.\n */\n readonly url?: string | URL;\n /** The HTTP method. Defaults to `\"GET\"`. */\n readonly method?: string;\n /** Additional HTTP headers added to the underlying `Request`. */\n readonly headers?: HeadersInit;\n /** The request body. Only usable with methods that accept a body. */\n readonly body?: BodyInit | null;\n /**\n * Route params (e.g. `{ id: \"123\" }` for a route like `/items/[id]`).\n * Defaults to `{}`.\n */\n readonly params?: Record<string, string>;\n /**\n * Initial `event.locals` value, typed as your app's `App.Locals` (declare its\n * fields in `src/app.d.ts`). Defaults to `{}`.\n */\n readonly locals?: App.Locals;\n /**\n * Pre-seeded cookies as `{ name: value }` pairs.\n * The backing store supports `get`, `getAll`, `set`, `delete`, and\n * `serialize`; the object is cast to SvelteKit's `Cookies` interface.\n */\n readonly cookies?: Record<string, string>;\n /**\n * The `event.platform` value, if any.\n * Pass a partial platform object matching the environment the handler targets.\n */\n readonly platform?: App.Platform;\n /**\n * The `fetch` implementation used by `event.fetch`.\n * Defaults to `globalThis.fetch`. Pass a custom function to intercept or\n * stub network calls made by the handler.\n */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/**\n * The fields {@link TestRequestEvent} actually provides: a {@link RequestEvent}\n * without `tracing` / `isRemoteRequest`, with Map-backed cookies (no `parse`)\n * and the test's own `locals` / `platform` values.\n */\ntype TestRequestEventFixture = Omit<\n RequestEvent,\n \"cookies\" | \"locals\" | \"platform\" | \"tracing\" | \"isRemoteRequest\"\n> & {\n readonly cookies: Omit<Cookies, \"parse\">;\n readonly locals: App.Locals;\n readonly platform: App.Platform | undefined;\n};\n\n/**\n * Create a minimal {@link RequestEvent} for use in unit tests.\n *\n * All fields are optional — omit what the handler under test doesn't inspect.\n * Cookies are backed by an in-memory `Map`; mutations (`set`, `delete`) are\n * reflected in subsequent `get`/`getAll` calls on the same event.\n *\n * @example\n * ```ts\n * const event = TestRequestEvent({\n * url: \"http://localhost/items/42\",\n * params: { id: \"42\" },\n * locals: { user: { id: \"u1\", role: \"admin\" } },\n * cookies: { session: \"tok_test\" },\n * });\n * ```\n */\nexport function TestRequestEvent(opts: TestRequestEventOptions = {}): RequestEvent {\n const rawUrl = opts.url instanceof URL ? opts.url.toString() : (opts.url ?? \"http://localhost/\");\n const url = new URL(rawUrl);\n\n const init: RequestInit = { method: opts.method ?? \"GET\" };\n if (opts.headers !== undefined) init.headers = opts.headers;\n if (opts.body !== undefined) init.body = opts.body;\n\n const request = new Request(url.toString(), init);\n const cookies = new TestCookies(opts.cookies ?? {});\n const fetchFn = opts.fetch ?? globalThis.fetch;\n\n const fixture: TestRequestEventFixture = {\n request,\n url,\n params: opts.params ?? {},\n route: { id: null },\n fetch: fetchFn,\n cookies,\n locals: opts.locals ?? {},\n platform: opts.platform,\n isDataRequest: false,\n isSubRequest: false,\n setHeaders: () => {},\n getClientAddress: () => \"127.0.0.1\",\n };\n // SAFETY: a deliberately partial fixture, as the TSDoc above says: it has\n // the fields load/action/endpoint/remote handlers read, while `tracing`,\n // `isRemoteRequest` and `cookies.parse` are absent, and `locals` / `platform`\n // are whatever the test passed in place of `App.Locals` / `App.Platform`.\n return fixture as RequestEvent;\n}\n\n// ─── Options ──────────────────────────────────────────────────────────────────\n\n/**\n * Options shared by {@link runServerLoad}, {@link runAction}, and\n * {@link runEndpoint}.\n */\nexport interface TestRunOptions<R> {\n /**\n * The `Layer` providing the handler effect's required services `R`.\n * Omit when the handler has no service requirements (`R` is `never`).\n */\n readonly layer?: Layer.Layer<R>;\n /**\n * Translate a failed `Cause` at the boundary. Defaults to\n * {@link SvelteKit.translate} (Kit control-flow through; anything else\n * becomes an `EffectCauseError`).\n */\n readonly translateError?: ErrorTranslator;\n}\n\n/**\n * Options for {@link runRemote}.\n */\nexport interface RunRemoteOptions<R> {\n /** The `Layer` providing the remote handler's service requirements. */\n readonly layer?: Layer.Layer<R>;\n /**\n * Translate a failed `Cause` at the boundary. Defaults to\n * {@link SvelteKit.translate}.\n */\n readonly translateError?: ErrorTranslator;\n /**\n * Map a remote form handler's failure to SvelteKit field issues. Receives\n * the squashed handler failure and the `{ issue, data }` context. When\n * provided it is called instead of `translateError` on the form error path.\n */\n readonly formError?: FormErrorMapper;\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\n// SAFETY: `layer` may be omitted only when the handler needs no services\n// (`R` is `never`, as `TestRunOptions.layer` documents), and then `Layer.empty`\n// provides all of `R`.\nconst makeAdapter = <R>(opts: TestRunOptions<R> | undefined) =>\n makeRuntimeAdapter(RequestRuntime.fromLayer((opts?.layer ?? Layer.empty) as Layer.Layer<R>), {\n translateError: opts?.translateError ?? SvelteKit.translate,\n });\n\n// ─── runServerLoad ────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based server `load` function under test.\n *\n * Wraps `fn` with `makeRuntimeAdapter` using the provided `opts.layer` (or\n * `Layer.empty` when omitted) and calls the resulting `ServerLoad` with\n * `event`. Errors are translated by `opts.translateError` (defaults to\n * {@link SvelteKit.translate}).\n *\n * @example\n * ```ts\n * const data = await runServerLoad(\n * (event) => Effect.gen(function* () {\n * const db = yield* Database;\n * return { items: yield* db.list() };\n * }),\n * TestRequestEvent(),\n * { layer: TestDatabase.layer },\n * );\n * expect(data.items).toHaveLength(0);\n * ```\n */\n// SAFETY: the adapter's `serverLoad` handler is an async function that reads\n// only `RequestEvent` fields (`route.id` plus whatever `fn` reads), so it\n// accepts a plain `RequestEvent` and always returns a `Promise`.\nexport const runServerLoad = <R, A extends Record<string, any> | void = void>(\n fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<A> => (makeAdapter(opts).serverLoad(fn) as (e: RequestEvent) => Promise<A>)(event);\n\n// ─── runAction ───────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based form action handler under test.\n *\n * @example\n * ```ts\n * const result = await runAction(\n * (_event) => Effect.succeed({ success: true }),\n * TestRequestEvent({ method: \"POST\" }),\n * );\n * expect((result as any).success).toBe(true);\n * ```\n */\n// SAFETY: the adapter's `action` handler is an async function over a\n// `RequestEvent`, so it always returns a `Promise` of the action's value.\nexport const runAction = <R, A extends Record<string, any> | void = void>(\n fn: (event: RequestEvent) => Effect.Effect<A, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<A> => (makeAdapter(opts).action(fn) as (e: RequestEvent) => Promise<A>)(event);\n\n// ─── runEndpoint ──────────────────────────────────────────────────────────────\n\n/**\n * Run an Effect-based `+server.ts` endpoint handler under test.\n *\n * @example\n * ```ts\n * const response = await runEndpoint(\n * (_event) => Effect.succeed(new Response(JSON.stringify({ ok: true }))),\n * TestRequestEvent({ url: \"http://localhost/api/ping\" }),\n * );\n * expect(response.status).toBe(200);\n * ```\n */\nexport const runEndpoint = <R>(\n fn: (event: RequestEvent) => Effect.Effect<Response, unknown, R>,\n event: RequestEvent,\n opts?: TestRunOptions<R>,\n): Promise<Response> => Promise.resolve(makeAdapter(opts).endpoint(fn)(event));\n\n// ─── runRemote ────────────────────────────────────────────────────────────────\n\n/**\n * Build a `{ run, runForm }` helper pair for directly invoking remote-function\n * Effect handlers under test.\n *\n * Unlike the production `query` / `command` / `form` helpers, which resolve the\n * request event via `$app/server.getRequestEvent()`, this resolves it from the\n * `event` argument you supply — no SvelteKit module-graph mocking required.\n *\n * Use `run` for `query` / `command` handlers and `runForm` for `form` handlers\n * that need the `issue` / `data` context.\n *\n * @example\n * ```ts\n * import { TestRequestEvent, runRemote } from \"@thomasfosterau/effect-sveltekit/testing\";\n *\n * const event = TestRequestEvent();\n * const { run } = runRemote(event, { layer: TestDatabase.layer });\n *\n * // Invoke the underlying Effect directly — no AppServer needed:\n * const items = await run(listItemsEffect());\n * expect(items).toEqual([]);\n * ```\n */\nexport const runRemote = <R = never>(\n event: RequestEvent,\n opts?: RunRemoteOptions<R>,\n): RunHelpers => {\n const translate = opts?.translateError ?? SvelteKit.translate;\n // SAFETY: `layer` may be omitted only when the handlers need no services\n // (`R = never`, the default), and then `Layer.empty` provides all of `R`.\n const layer = (opts?.layer ?? Layer.empty) as Layer.Layer<R>;\n const provider: RequestRuntimeProvider<R> = RequestRuntime.fromLayer(layer);\n return makeRunHelpers(\n () => ({ runExit: (effect) => provider.run(event).runPromiseExit(effect) }),\n translate,\n opts?.formError,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;AA2EA,IAAM,cAAN,MAAkB;CAChB;CAEA,YAAY,UAA4C,CAAC,GAAG;EAC1D,KAAK,QAAQ,IAAI,IAAI,IAAI,UAAU,OAAO,IAAI,CAAC,MAAM,YAAY;GAAE;GAAM;EAAM,EAAE;CACnF;CAEA,IAAI,MAAc,OAAgD;EAChE,OAAO,OAAO,eACZ,OAAO,IACL,IAAI,UAAU,KAAK,QAAQ,WAAW,OAAO,SAAS,IAAI,IACzD,WAAW,OAAO,KACrB,CACF;CACF;CAEA,OAAO,OAAoE;EACzE,OAAO,IAAI,IAAI,KAAK,QAAQ,EAAE,MAAM,aAAa;GAAE;GAAM;EAAM,EAAE;CACnE;CAEA,IAAI,MAAc,OAAe,OAAsC;EACrE,KAAK,QAAQ,OAAO,MAClB,IAAI,eAAe,KAAK,QAAQ,WAAW,OAAO,SAAS,IAAI,GAC/D;GACE,cAAc,IAAI,OAAO,KAAK,OAAO;IAAE;IAAM;GAAM,CAAC;GACpD,SAAS,UACP,IAAI,IAAI,KAAK,QAAQ,QAAQ,MAAO,MAAM,QAAQ;IAAE;IAAM;GAAM,IAAI,MAAO;EAC/E,CACF;CACF;CAEA,OAAO,MAAc,OAAsC;EACzD,KAAK,QAAQ,IAAI,OAAO,KAAK,QAAQ,WAAW,OAAO,SAAS,IAAI;CACtE;CAEA,UAAU,MAAc,OAAe,OAAwC;EAC7E,OAAO,GAAG,KAAK,GAAG,mBAAmB,KAAK;CAC5C;AACF;;;;;;;;;;;;;;;;;;AA6EA,SAAgB,iBAAiB,OAAgC,CAAC,GAAiB;CACjF,MAAM,SAAS,KAAK,eAAe,MAAM,KAAK,IAAI,SAAS,IAAK,KAAK,OAAO;CAC5E,MAAM,MAAM,IAAI,IAAI,MAAM;CAE1B,MAAM,OAAoB,EAAE,QAAQ,KAAK,UAAU,MAAM;CACzD,IAAI,KAAK,YAAY,KAAA,GAAW,KAAK,UAAU,KAAK;CACpD,IAAI,KAAK,SAAS,KAAA,GAAW,KAAK,OAAO,KAAK;CAE9C,MAAM,UAAU,IAAI,QAAQ,IAAI,SAAS,GAAG,IAAI;CAChD,MAAM,UAAU,IAAI,YAAY,KAAK,WAAW,CAAC,CAAC;CAClD,MAAM,UAAU,KAAK,SAAS,WAAW;CAoBzC,OAAO;EAjBL;EACA;EACA,QAAQ,KAAK,UAAU,CAAC;EACxB,OAAO,EAAE,IAAI,KAAK;EAClB,OAAO;EACP;EACA,QAAQ,KAAK,UAAU,CAAC;EACxB,UAAU,KAAK;EACf,eAAe;EACf,cAAc;EACd,kBAAkB,CAAC;EACnB,wBAAwB;CAMb;AACf;AA8CA,MAAM,eAAkB,SACtB,mBAAmB,eAAe,UAAW,MAAM,SAAS,MAAM,KAAwB,GAAG,EAC3F,gBAAgB,MAAM,kBAAkB,UAAU,UACpD,CAAC;;;;;;;;;;;;;;;;;;;;;;AA4BH,MAAa,iBACX,IACA,OACA,SACgB,YAAY,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,CAAqC,KAAK;;;;;;;;;;;;;AAkB5F,MAAa,aACX,IACA,OACA,SACgB,YAAY,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC,CAAqC,KAAK;;;;;;;;;;;;;AAgBxF,MAAa,eACX,IACA,OACA,SACsB,QAAQ,QAAQ,YAAY,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;AA2B7E,MAAa,aACX,OACA,SACe;CACf,MAAM,YAAY,MAAM,kBAAkB,UAAU;CAGpD,MAAM,QAAS,MAAM,SAAS,MAAM;CACpC,MAAM,WAAsC,eAAe,UAAU,KAAK;CAC1E,OAAO,sBACE,EAAE,UAAU,WAAW,SAAS,IAAI,KAAK,CAAC,CAAC,eAAe,MAAM,EAAE,IACzE,WACA,MAAM,SACR;AACF"}
|
package/dist/transport.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as Schema from "effect/Schema";
|
|
2
2
|
import { Transport, Transporter } from "@sveltejs/kit/hooks";
|
|
3
3
|
//#region src/transport.d.ts
|
|
4
4
|
/**
|
|
@@ -10,7 +10,7 @@ import { Transport, Transporter } from "@sveltejs/kit/hooks";
|
|
|
10
10
|
* (e.g. an encoded `0`, `""`, `false`, or `null`) as "not this type" — and is
|
|
11
11
|
* unwrapped again by `decode` on the client.
|
|
12
12
|
*/
|
|
13
|
-
declare const transporter: <T, E>(schema: Schema.Codec<T, E>) => Transporter<T, readonly [E]>;
|
|
13
|
+
export declare const transporter: <T, E>(schema: Schema.Codec<T, E>) => Transporter<T, readonly [E]>;
|
|
14
14
|
/**
|
|
15
15
|
* Builds a deliberately-lossy {@link Transporter} for a non-POJO wrapper whose
|
|
16
16
|
* contents should *not* round-trip — the value is detected on the server and
|
|
@@ -32,9 +32,9 @@ declare const transporter: <T, E>(schema: Schema.Codec<T, E>) => Transporter<T,
|
|
|
32
32
|
* });
|
|
33
33
|
* ```
|
|
34
34
|
*/
|
|
35
|
-
declare const markerTransporter: <T>(options: MarkerTransporterOptions<T>) => Transporter<T, unknown>;
|
|
35
|
+
export declare const markerTransporter: <T>(options: MarkerTransporterOptions<T>) => Transporter<T, unknown>;
|
|
36
36
|
/** Options for {@link markerTransporter}. */
|
|
37
|
-
interface MarkerTransporterOptions<T> {
|
|
37
|
+
export interface MarkerTransporterOptions<T> {
|
|
38
38
|
/** Detect, on the server, values this transporter handles. */
|
|
39
39
|
readonly guard: (value: unknown) => value is T;
|
|
40
40
|
/** Produce a fresh value on the client (the payload is discarded). */
|
|
@@ -46,7 +46,7 @@ interface MarkerTransporterOptions<T> {
|
|
|
46
46
|
readonly marker?: unknown;
|
|
47
47
|
}
|
|
48
48
|
/** An entry accepted by {@link transport}: an Effect schema or a ready Transporter. */
|
|
49
|
-
type TransportEntry = Schema.Codec<any, any> | Transporter<any, any>;
|
|
49
|
+
export type TransportEntry = Schema.Codec<any, any> | Transporter<any, any>;
|
|
50
50
|
/**
|
|
51
51
|
* Assembles a SvelteKit `transport` object from a record of entries. Each entry
|
|
52
52
|
* is either an Effect {@link Schema.Codec} (wrapped with {@link transporter}) or
|
|
@@ -54,7 +54,6 @@ type TransportEntry = Schema.Codec<any, any> | Transporter<any, any>;
|
|
|
54
54
|
* round-tripping and marker-style values can be mixed. The keys are arbitrary
|
|
55
55
|
* labels (they only need to be stable between server and client).
|
|
56
56
|
*/
|
|
57
|
-
declare const transport: (entries: Record<string, TransportEntry>) => Transport;
|
|
57
|
+
export declare const transport: (entries: Record<string, TransportEntry>) => Transport;
|
|
58
58
|
//#endregion
|
|
59
|
-
export { MarkerTransporterOptions, TransportEntry, markerTransporter, transport, transporter };
|
|
60
59
|
//# sourceMappingURL=transport.d.ts.map
|
package/dist/transport.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as Rec from "effect/Record";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
2
3
|
//#region src/transport.ts
|
|
3
4
|
/**
|
|
4
5
|
* Builds a SvelteKit {@link Transporter} from an Effect {@link Schema.Codec}.
|
|
@@ -53,11 +54,7 @@ const markerTransporter = (options) => {
|
|
|
53
54
|
* round-tripping and marker-style values can be mixed. The keys are arbitrary
|
|
54
55
|
* labels (they only need to be stable between server and client).
|
|
55
56
|
*/
|
|
56
|
-
const transport = (entries) =>
|
|
57
|
-
const result = {};
|
|
58
|
-
for (const [name, entry] of Object.entries(entries)) result[name] = Schema.isSchema(entry) ? transporter(entry) : entry;
|
|
59
|
-
return result;
|
|
60
|
-
};
|
|
57
|
+
const transport = (entries) => Rec.map(entries, (entry) => Schema.isSchema(entry) ? transporter(entry) : entry);
|
|
61
58
|
//#endregion
|
|
62
59
|
export { markerTransporter, transport, transporter };
|
|
63
60
|
|
package/dist/transport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["/**\n * Effect Schema ⇄ SvelteKit `transport` hook.\n *\n * SvelteKit's universal [`transport`](https://svelte.dev/docs/kit/hooks#Universal-hooks-transport)\n * hook moves custom (non-POJO) values across the server/client boundary — for\n * data returned from `load` functions and from remote functions. Each entry is\n * a {@link Transporter}: a sync `encode` (server) / `decode` (client) pair,\n * where `encode` returns `false` for values it does not handle.\n *\n * An Effect {@link Schema.Codec} is exactly such a pair. {@link transporter}\n * turns a schema into a `Transporter`, and {@link transport} assembles a whole\n * `transport` object from a record of schemas — so `Option`, `DateTime`,\n * branded types, `Schema.Class` instances, tagged errors, etc. round-trip with\n * no hand-written serialization.\n *\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from \"@thomasfosterau/effect-sveltekit\";\n * import { Schema } from \"effect\";\n *\n * export const transport = Hooks.transport({\n * Option: Schema.Option(Schema.Number),\n * Date: Schema.Date,\n * });\n * ```\n */\n\nimport type { Transport, Transporter } from \"@sveltejs/kit/hooks\";\nimport
|
|
1
|
+
{"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["/**\n * Effect Schema ⇄ SvelteKit `transport` hook.\n *\n * SvelteKit's universal [`transport`](https://svelte.dev/docs/kit/hooks#Universal-hooks-transport)\n * hook moves custom (non-POJO) values across the server/client boundary — for\n * data returned from `load` functions and from remote functions. Each entry is\n * a {@link Transporter}: a sync `encode` (server) / `decode` (client) pair,\n * where `encode` returns `false` for values it does not handle.\n *\n * An Effect {@link Schema.Codec} is exactly such a pair. {@link transporter}\n * turns a schema into a `Transporter`, and {@link transport} assembles a whole\n * `transport` object from a record of schemas — so `Option`, `DateTime`,\n * branded types, `Schema.Class` instances, tagged errors, etc. round-trip with\n * no hand-written serialization.\n *\n * ```ts\n * // src/hooks.ts\n * import { Hooks } from \"@thomasfosterau/effect-sveltekit\";\n * import { Schema } from \"effect\";\n *\n * export const transport = Hooks.transport({\n * Option: Schema.Option(Schema.Number),\n * Date: Schema.Date,\n * });\n * ```\n */\n\nimport type { Transport, Transporter } from \"@sveltejs/kit/hooks\";\nimport * as Rec from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\n\n/**\n * Builds a SvelteKit {@link Transporter} from an Effect {@link Schema.Codec}.\n *\n * The decoded `Type` is detected with `Schema.is`; matching values are encoded\n * with `Schema.encodeSync` and wrapped in a single-element tuple. The wrapper\n * guarantees the encoding is truthy — SvelteKit treats a falsy `encode` result\n * (e.g. an encoded `0`, `\"\"`, `false`, or `null`) as \"not this type\" — and is\n * unwrapped again by `decode` on the client.\n */\nexport const transporter = <T, E>(schema: Schema.Codec<T, E>): Transporter<T, readonly [E]> => {\n const guard = Schema.is(schema);\n const encode = Schema.encodeSync(schema);\n const decode = Schema.decodeSync(schema);\n return {\n encode: (value) => (guard(value) ? ([encode(value)] as const) : false),\n decode: ([data]) => decode(data),\n };\n};\n\n/**\n * Builds a deliberately-lossy {@link Transporter} for a non-POJO wrapper whose\n * contents should *not* round-trip — the value is detected on the server and\n * reconstructed fresh on the client.\n *\n * Unlike {@link transporter} (which needs a round-tripping {@link Schema.Codec}),\n * this is for values that have no meaningful serialization but still need a\n * `transport` entry so SvelteKit doesn't reject them: `encode` returns a truthy\n * marker for matching values, and `decode` ignores it and produces a fresh value\n * from {@link MarkerTransporterOptions.make}.\n *\n * ```ts\n * // A non-serializable handle reconstructed as a fresh, empty instance:\n * export const transport = Hooks.transport({\n * Live: Hooks.markerTransporter({\n * guard: (v): v is LiveHandle => v instanceof LiveHandle,\n * make: () => LiveHandle.empty(),\n * }),\n * });\n * ```\n */\nexport const markerTransporter = <T>(\n options: MarkerTransporterOptions<T>,\n): Transporter<T, unknown> => {\n const marker = options.marker ?? 1;\n return {\n encode: (value) => (options.guard(value) ? marker : false),\n decode: () => options.make(),\n };\n};\n\n/** Options for {@link markerTransporter}. */\nexport interface MarkerTransporterOptions<T> {\n /** Detect, on the server, values this transporter handles. */\n readonly guard: (value: unknown) => value is T;\n /** Produce a fresh value on the client (the payload is discarded). */\n readonly make: () => T;\n /**\n * The truthy marker `encode` emits (SvelteKit treats a falsy `encode` result\n * as \"not this type\"). Defaults to `1`.\n */\n readonly marker?: unknown;\n}\n\n/** An entry accepted by {@link transport}: an Effect schema or a ready Transporter. */\nexport type TransportEntry = Schema.Codec<any, any> | Transporter<any, any>;\n\n/**\n * Assembles a SvelteKit `transport` object from a record of entries. Each entry\n * is either an Effect {@link Schema.Codec} (wrapped with {@link transporter}) or\n * a ready {@link Transporter} (e.g. from {@link markerTransporter}), so\n * round-tripping and marker-style values can be mixed. The keys are arbitrary\n * labels (they only need to be stable between server and client).\n */\nexport const transport = (entries: Record<string, TransportEntry>): Transport =>\n Rec.map(entries, (entry): Transporter<any, any> =>\n Schema.isSchema(entry) ? transporter(entry) : entry,\n );\n"],"mappings":";;;;;;;;;;;;AAwCA,MAAa,eAAqB,WAA6D;CAC7F,MAAM,QAAQ,OAAO,GAAG,MAAM;CAC9B,MAAM,SAAS,OAAO,WAAW,MAAM;CACvC,MAAM,SAAS,OAAO,WAAW,MAAM;CACvC,OAAO;EACL,SAAS,UAAW,MAAM,KAAK,IAAK,CAAC,OAAO,KAAK,CAAC,IAAc;EAChE,SAAS,CAAC,UAAU,OAAO,IAAI;CACjC;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,qBACX,YAC4B;CAC5B,MAAM,SAAS,QAAQ,UAAU;CACjC,OAAO;EACL,SAAS,UAAW,QAAQ,MAAM,KAAK,IAAI,SAAS;EACpD,cAAc,QAAQ,KAAK;CAC7B;AACF;;;;;;;;AAyBA,MAAa,aAAa,YACxB,IAAI,IAAI,UAAU,UAChB,OAAO,SAAS,KAAK,IAAI,YAAY,KAAK,IAAI,KAChD"}
|
package/dist/universal.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SvelteRouteParams } from "./internal/route-params.js";
|
|
2
2
|
import { UniversalRuntime, makeUniversalRuntime } from "./app-runtime.js";
|
|
3
|
-
import
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
4
|
import * as HttpClient from "effect/http/HttpClient";
|
|
5
5
|
import { Load } from "@sveltejs/kit";
|
|
6
6
|
//#region src/universal.d.ts
|
|
@@ -29,7 +29,7 @@ import { Load } from "@sveltejs/kit";
|
|
|
29
29
|
* );
|
|
30
30
|
* ```
|
|
31
31
|
*/
|
|
32
|
-
declare function load<Params extends SvelteRouteParams = SvelteRouteParams, InputData extends Record<string, unknown> | null = any, ParentData extends Record<string, unknown> = any, OutputData extends Record<string, unknown> | void = any, RouteId extends string | null = any>(fn: (event: Parameters<Load<Params, InputData, ParentData, OutputData, RouteId>>[0]) => Effect.Effect<OutputData, unknown, HttpClient.HttpClient>): Load<Params, InputData, ParentData, OutputData, RouteId>;
|
|
32
|
+
export declare function load<Params extends SvelteRouteParams = SvelteRouteParams, InputData extends Record<string, unknown> | null = any, ParentData extends Record<string, unknown> = any, OutputData extends Record<string, unknown> | void = any, RouteId extends string | null = any>(fn: (event: Parameters<Load<Params, InputData, ParentData, OutputData, RouteId>>[0]) => Effect.Effect<OutputData, unknown, HttpClient.HttpClient>): Load<Params, InputData, ParentData, OutputData, RouteId>;
|
|
33
33
|
//#endregion
|
|
34
|
-
export { type UniversalRuntime,
|
|
34
|
+
export { type UniversalRuntime, makeUniversalRuntime };
|
|
35
35
|
//# sourceMappingURL=universal.d.ts.map
|
package/dist/universal.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { makeUniversalRuntime } from "./app-runtime.js";
|
|
2
2
|
import { defaultUniversalRuntime } from "./internal/default-runtime.js";
|
|
3
|
-
import "effect";
|
|
3
|
+
import "effect/Effect";
|
|
4
4
|
//#region src/universal.ts
|
|
5
5
|
/**
|
|
6
6
|
* Wraps an Effect-based function to work as a SvelteKit universal load function.
|
package/dist/universal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"universal.js","names":["runtime"],"sources":["../src/universal.ts"],"sourcesContent":["import type { Load } from \"@sveltejs/kit\";\nimport
|
|
1
|
+
{"version":3,"file":"universal.js","names":["runtime"],"sources":["../src/universal.ts"],"sourcesContent":["import type { Load } from \"@sveltejs/kit\";\nimport * as Effect from \"effect/Effect\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport type { SvelteRouteParams } from \"./internal/route-params.js\";\nimport { defaultUniversalRuntime as runtime } from \"./internal/default-runtime.js\";\n\n/**\n * Wraps an Effect-based function to work as a SvelteKit universal load function.\n *\n * The effect has access to `HttpClient` on both the server and the client:\n * it is backed by the load event's `fetch`, so relative URLs and SvelteKit's\n * fetch behaviours (deduplication, cookies forwarding) work as expected.\n *\n * To give effects access to your own application services, create an\n * app-wide runtime with `makeUniversalRuntime` and use its `load` instead.\n *\n * @example\n * ```ts\n * import { load as effectLoad } from '@thomasfosterau/effect-sveltekit';\n * import * as HttpClient from 'effect/http/HttpClient';\n * import { Effect } from 'effect';\n *\n * export const load = effectLoad((event) =>\n * Effect.gen(function* () {\n * const client = yield* HttpClient.HttpClient;\n * const response = yield* client.get(`/api/items/${event.params.id}`);\n * return { item: yield* response.json };\n * })\n * );\n * ```\n */\nexport function load<\n Params extends SvelteRouteParams = SvelteRouteParams,\n InputData extends Record<string, unknown> | null = any,\n ParentData extends Record<string, unknown> = any,\n OutputData extends Record<string, unknown> | void = any,\n RouteId extends string | null = any,\n>(\n fn: (\n event: Parameters<Load<Params, InputData, ParentData, OutputData, RouteId>>[0],\n ) => Effect.Effect<OutputData, unknown, HttpClient.HttpClient>,\n): Load<Params, InputData, ParentData, OutputData, RouteId> {\n return runtime().load(fn);\n}\n\n/**\n * App-wide runtime: define your application's (universal) Effect services\n * once and share them across every `load` invocation.\n */\nexport { makeUniversalRuntime, type UniversalRuntime } from \"./app-runtime.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,KAOd,IAG0D;CAC1D,OAAOA,wBAAQ,CAAC,CAAC,KAAK,EAAE;AAC1B"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Plugin } from "vite";
|
|
2
2
|
//#region src/vite.d.ts
|
|
3
3
|
/** The SvelteKit route and hook file kinds `effectKit()` can rewrite. */
|
|
4
|
-
type EffectKitFileKind = "pageServer" | "page" | "layoutServer" | "layout" | "server" | "hooks" | "hooksServer" | "hooksClient";
|
|
4
|
+
export type EffectKitFileKind = "pageServer" | "page" | "layoutServer" | "layout" | "server" | "hooks" | "hooksServer" | "hooksClient";
|
|
5
5
|
/** Options for {@link effectKit}. */
|
|
6
|
-
interface EffectKitPluginOptions {
|
|
6
|
+
export interface EffectKitPluginOptions {
|
|
7
7
|
/**
|
|
8
8
|
* Restrict transformation to a subset of SvelteKit file kinds.
|
|
9
9
|
* Defaults to all standard route files.
|
|
@@ -37,7 +37,7 @@ interface EffectKitPluginOptions {
|
|
|
37
37
|
* functions returning Effects, are accepted wherever SvelteKit expects a
|
|
38
38
|
* function-shaped export.
|
|
39
39
|
*/
|
|
40
|
-
declare function effectKit(options?: EffectKitPluginOptions): Plugin;
|
|
40
|
+
export declare function effectKit(options?: EffectKitPluginOptions): Plugin;
|
|
41
41
|
//#endregion
|
|
42
|
-
export {
|
|
42
|
+
export { effectKit as default };
|
|
43
43
|
//# sourceMappingURL=vite.d.ts.map
|