@thomasfosterau/effect-sveltekit 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -15
- package/dist/Hooks.d.ts +1 -1
- package/dist/Hooks.js.map +1 -1
- package/dist/Navigation.d.ts +17 -6
- package/dist/Navigation.js +17 -5
- package/dist/Navigation.js.map +1 -1
- package/dist/Remote.d.ts +1 -1
- package/dist/Remote.js.map +1 -1
- package/dist/State.d.ts +4 -4
- 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 +6 -6
- package/dist/forms.js.map +1 -1
- package/dist/internal/app-state.d.ts +1 -1
- 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 +1 -1
- 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/kit.js +3 -3
- package/dist/kit.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 +6 -4
package/dist/adapter/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { writeFileSync } from "node:fs";
|
|
1
|
+
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
2
|
//#region src/adapter/index.ts
|
|
3
3
|
/**
|
|
4
4
|
* Effect deployment adapter for SvelteKit.
|
|
@@ -10,14 +10,14 @@ import { writeFileSync } from "node:fs";
|
|
|
10
10
|
* shutdown that runs all finalizers).
|
|
11
11
|
*
|
|
12
12
|
* ```js
|
|
13
|
-
* //
|
|
13
|
+
* // vite.config.ts
|
|
14
|
+
* import { sveltekit } from "@sveltejs/kit/vite";
|
|
14
15
|
* import adapter from "@thomasfosterau/effect-sveltekit/adapter";
|
|
16
|
+
* import { defineConfig } from "vite";
|
|
15
17
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* };
|
|
19
|
-
*
|
|
20
|
-
* export default config;
|
|
18
|
+
* export default defineConfig({
|
|
19
|
+
* plugins: [sveltekit({ adapter: adapter() })],
|
|
20
|
+
* });
|
|
21
21
|
* ```
|
|
22
22
|
*
|
|
23
23
|
* The build output (`build/` by default) contains:
|
|
@@ -25,7 +25,9 @@ import { writeFileSync } from "node:fs";
|
|
|
25
25
|
* - `index.js` — runs the production server: `node build`
|
|
26
26
|
* - `handler.js` — exports the SvelteKit app as a composable Effect HTTP
|
|
27
27
|
* handler, for mounting inside an existing `effect/http` server
|
|
28
|
-
* - `client/`, `server/`, `prerendered/`, `
|
|
28
|
+
* - `client/`, `server/`, `prerendered/`, `server.js` (the SvelteKit
|
|
29
|
+
* `server` instance), `manifest.js` (prerendered paths, base and app path) —
|
|
30
|
+
* the built app
|
|
29
31
|
*
|
|
30
32
|
* Unlike `adapter-node`, the server output is not bundled: the deployment
|
|
31
33
|
* needs `node_modules` with the app's production dependencies installed
|
|
@@ -39,8 +41,8 @@ import { dirname } from "node:path";
|
|
|
39
41
|
import { fileURLToPath } from "node:url";
|
|
40
42
|
import process from "node:process";
|
|
41
43
|
import { makeHandler } from "${PACKAGE}/adapter/handler";
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
44
|
+
import { server } from "./server.js";
|
|
45
|
+
import { prerendered, base, appPath } from "./manifest.js";
|
|
44
46
|
|
|
45
47
|
const dir = dirname(fileURLToPath(import.meta.url));
|
|
46
48
|
|
|
@@ -51,8 +53,8 @@ const dir = dirname(fileURLToPath(import.meta.url));
|
|
|
51
53
|
* \`effect/http\` HTTP server.
|
|
52
54
|
*/
|
|
53
55
|
export const handler = makeHandler({
|
|
54
|
-
|
|
55
|
-
|
|
56
|
+
server,
|
|
57
|
+
appPath,
|
|
56
58
|
prerendered,
|
|
57
59
|
base,
|
|
58
60
|
dir,
|
|
@@ -77,8 +79,7 @@ serve(handler, { envPrefix: ${JSON.stringify(envPrefix)} });
|
|
|
77
79
|
const fetchEntryTemplate = (envPrefix) => `\
|
|
78
80
|
import { Layer } from "effect";
|
|
79
81
|
import { makeHandlerWith, AssetSource, toWebHandler } from "${PACKAGE}/adapter/handler";
|
|
80
|
-
import {
|
|
81
|
-
import { manifest } from "./manifest.js";
|
|
82
|
+
import { server } from "./server.js";
|
|
82
83
|
|
|
83
84
|
let fetchHandler;
|
|
84
85
|
|
|
@@ -87,8 +88,7 @@ export default {
|
|
|
87
88
|
fetch(request, env, ctx) {
|
|
88
89
|
fetchHandler ??= toWebHandler(
|
|
89
90
|
makeHandlerWith({
|
|
90
|
-
|
|
91
|
-
manifest,
|
|
91
|
+
server,
|
|
92
92
|
env,
|
|
93
93
|
envPrefix: ${JSON.stringify(envPrefix)},
|
|
94
94
|
// Static assets come from the Workers ASSETS binding (configure it to
|
|
@@ -113,9 +113,12 @@ function effectAdapter(options = {}) {
|
|
|
113
113
|
return {
|
|
114
114
|
name: `${PACKAGE}/adapter`,
|
|
115
115
|
async adapt(builder) {
|
|
116
|
-
const base = builder.config.
|
|
117
|
-
|
|
118
|
-
|
|
116
|
+
const base = builder.config.paths.base;
|
|
117
|
+
rmSync(out, {
|
|
118
|
+
recursive: true,
|
|
119
|
+
force: true
|
|
120
|
+
});
|
|
121
|
+
mkdirSync(out, { recursive: true });
|
|
119
122
|
builder.log.minor("Copying assets");
|
|
120
123
|
builder.writeClient(`${out}/client${base}`);
|
|
121
124
|
builder.writePrerendered(`${out}/prerendered${base}`);
|
|
@@ -125,10 +128,11 @@ function effectAdapter(options = {}) {
|
|
|
125
128
|
}
|
|
126
129
|
builder.log.minor("Building server");
|
|
127
130
|
builder.writeServer(`${out}/server`);
|
|
131
|
+
builder.generateServerInstance(`${out}/server.js`, { serverDirectory: `${out}/server` });
|
|
128
132
|
writeFileSync(`${out}/manifest.js`, [
|
|
129
|
-
`export const manifest = ${builder.generateManifest({ relativePath: "./server" })};`,
|
|
130
133
|
`export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});`,
|
|
131
|
-
`export const base = ${JSON.stringify(base)}
|
|
134
|
+
`export const base = ${JSON.stringify(base)};`,
|
|
135
|
+
`export const appPath = ${JSON.stringify(builder.getAppPath())};`
|
|
132
136
|
].join("\n\n"));
|
|
133
137
|
builder.log.minor("Writing server entry");
|
|
134
138
|
writeFileSync(`${out}/handler.js`, handlerTemplate(envPrefix));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/adapter/index.ts"],"sourcesContent":["/**\n * Effect deployment adapter for SvelteKit.\n *\n * Like `@sveltejs/adapter-node`, but the production server is an\n * `effect/http` HTTP server: requests are handled by an Effect HTTP\n * handler, configuration is read through `Config`, and startup/shutdown is\n * managed by Effect layers and scopes (SIGINT/SIGTERM trigger a graceful\n * shutdown that runs all finalizers).\n *\n * ```js\n * //
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/adapter/index.ts"],"sourcesContent":["/**\n * Effect deployment adapter for SvelteKit.\n *\n * Like `@sveltejs/adapter-node`, but the production server is an\n * `effect/http` HTTP server: requests are handled by an Effect HTTP\n * handler, configuration is read through `Config`, and startup/shutdown is\n * managed by Effect layers and scopes (SIGINT/SIGTERM trigger a graceful\n * shutdown that runs all finalizers).\n *\n * ```js\n * // vite.config.ts\n * import { sveltekit } from \"@sveltejs/kit/vite\";\n * import adapter from \"@thomasfosterau/effect-sveltekit/adapter\";\n * import { defineConfig } from \"vite\";\n *\n * export default defineConfig({\n * plugins: [sveltekit({ adapter: adapter() })],\n * });\n * ```\n *\n * The build output (`build/` by default) contains:\n *\n * - `index.js` — runs the production server: `node build`\n * - `handler.js` — exports the SvelteKit app as a composable Effect HTTP\n * handler, for mounting inside an existing `effect/http` server\n * - `client/`, `server/`, `prerendered/`, `server.js` (the SvelteKit\n * `server` instance), `manifest.js` (prerendered paths, base and app path) —\n * the built app\n *\n * Unlike `adapter-node`, the server output is not bundled: the deployment\n * needs `node_modules` with the app's production dependencies installed\n * (including `@thomasfosterau/effect-sveltekit`, `effect`, and\n * `@effect/platform-node`).\n */\n\nimport { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport type { Adapter } from \"@sveltejs/kit\";\n\n/** Options for {@link effectAdapter}. */\nexport interface EffectAdapterOptions {\n /**\n * The directory to write the production build to.\n * @default \"build\"\n */\n readonly out?: string;\n /**\n * Precompress static assets and prerendered pages with gzip and brotli.\n * @default true\n */\n readonly precompress?: boolean;\n /**\n * Prefix for the environment variables the production server reads\n * (`PORT`, `HOST`, `ORIGIN`, `PROTOCOL_HEADER`, `HOST_HEADER`,\n * `PORT_HEADER`, `ADDRESS_HEADER`, `XFF_DEPTH`).\n * @default \"\"\n */\n readonly envPrefix?: string;\n /**\n * The deployment target for the generated entry:\n *\n * - `\"node\"` (default) — a production Node HTTP server (`node build`) on\n * `@effect/platform-node`, serving assets from disk.\n * - `\"fetch\"` — a Web `fetch` handler suitable for Cloudflare Workers\n * (`build/index.js` exports `default { fetch }`), serving assets from the\n * `env.ASSETS` binding via `AssetSource.cloudflareAssets`.\n *\n * Both targets also write `build/handler.js` (the SvelteKit `HttpApp`), so you\n * can compose your own entry for any `effect/http` runtime.\n *\n * @default \"node\"\n */\n readonly target?: \"node\" | \"fetch\";\n}\n\nconst PACKAGE = \"@thomasfosterau/effect-sveltekit\";\n\n/** Template for the generated `<out>/handler.js`. */\nconst handlerTemplate = (envPrefix: string): string => `\\\nimport { dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport process from \"node:process\";\nimport { makeHandler } from \"${PACKAGE}/adapter/handler\";\nimport { server } from \"./server.js\";\nimport { prerendered, base, appPath } from \"./manifest.js\";\n\nconst dir = dirname(fileURLToPath(import.meta.url));\n\n/**\n * The SvelteKit application as a composable Effect HTTP handler.\n *\n * Serve it with the generated index.js, or mount it inside any\n * \\`effect/http\\` HTTP server.\n */\nexport const handler = makeHandler({\n server,\n appPath,\n prerendered,\n base,\n dir,\n env: process.env,\n envPrefix: ${JSON.stringify(envPrefix)},\n});\n`;\n\n/** Template for the generated Node `<out>/index.js`. */\nconst nodeEntryTemplate = (envPrefix: string): string => `\\\nimport { serve } from \"${PACKAGE}/adapter/serve\";\nimport { handler } from \"./handler.js\";\n\nserve(handler, { envPrefix: ${JSON.stringify(envPrefix)} });\n`;\n\n/**\n * Template for the generated Cloudflare Workers `<out>/index.js`.\n *\n * Exports a module worker (`default { fetch }`). Static client assets and\n * prerendered pages are served from the `ASSETS` binding; everything else is\n * server-side rendered by the SvelteKit `HttpApp`.\n */\nconst fetchEntryTemplate = (envPrefix: string): string => `\\\nimport { Layer } from \"effect\";\nimport { makeHandlerWith, AssetSource, toWebHandler } from \"${PACKAGE}/adapter/handler\";\nimport { server } from \"./server.js\";\n\nlet fetchHandler;\n\nexport default {\n /** @param {Request} request @param {Record<string, any>} env @param {any} ctx */\n fetch(request, env, ctx) {\n fetchHandler ??= toWebHandler(\n makeHandlerWith({\n server,\n env,\n envPrefix: ${JSON.stringify(envPrefix)},\n // Static assets come from the Workers ASSETS binding (configure it to\n // serve the uploaded \\`client/\\` + \\`prerendered/\\` output).\n assets: AssetSource.cloudflareAssets(env.ASSETS),\n // \\`read()\\` from \\`$app/server\\` is not backed by a file system on workerd.\n read: (file) => {\n throw new Error(\\`read() is not supported on this deployment (\\${file})\\`);\n },\n }),\n Layer.empty,\n );\n return fetchHandler(request);\n },\n};\n`;\n\n/**\n * Creates the Effect SvelteKit adapter.\n */\nexport function effectAdapter(options: EffectAdapterOptions = {}): Adapter {\n const { out = \"build\", precompress = true, envPrefix = \"\", target = \"node\" } = options;\n\n return {\n name: `${PACKAGE}/adapter`,\n\n async adapt(builder) {\n const base = builder.config.paths.base;\n\n rmSync(out, { recursive: true, force: true });\n mkdirSync(out, { recursive: true });\n\n builder.log.minor(\"Copying assets\");\n builder.writeClient(`${out}/client${base}`);\n builder.writePrerendered(`${out}/prerendered${base}`);\n\n if (precompress) {\n builder.log.minor(\"Compressing assets\");\n await Promise.all([\n builder.compress(`${out}/client`),\n builder.compress(`${out}/prerendered`),\n ]);\n }\n\n builder.log.minor(\"Building server\");\n builder.writeServer(`${out}/server`);\n // `<out>/server.js` exports the SvelteKit `server` instance, with the\n // manifest of the (non-prerendered) routes baked in.\n builder.generateServerInstance(`${out}/server.js`, { serverDirectory: `${out}/server` });\n\n writeFileSync(\n `${out}/manifest.js`,\n [\n `export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});`,\n `export const base = ${JSON.stringify(base)};`,\n `export const appPath = ${JSON.stringify(builder.getAppPath())};`,\n ].join(\"\\n\\n\"),\n );\n\n builder.log.minor(\"Writing server entry\");\n writeFileSync(`${out}/handler.js`, handlerTemplate(envPrefix));\n writeFileSync(\n `${out}/index.js`,\n target === \"fetch\" ? fetchEntryTemplate(envPrefix) : nodeEntryTemplate(envPrefix),\n );\n },\n\n supports: {\n // On Node, `read()` from `$app/server` is backed by the platform\n // FileSystem. On the `fetch` (Workers) target it has no file system, so\n // routes using `read()` are unsupported there.\n read: () => target !== \"fetch\",\n },\n };\n}\n\nexport default effectAdapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,UAAU;;AAGhB,MAAM,mBAAmB,cAA8B;;;;+BAIxB,QAAQ;;;;;;;;;;;;;;;;;;;eAmBxB,KAAK,UAAU,SAAS,EAAE;;;;AAKzC,MAAM,qBAAqB,cAA8B;yBAChC,QAAQ;;;8BAGH,KAAK,UAAU,SAAS,EAAE;;;;;;;;;AAUxD,MAAM,sBAAsB,cAA8B;;8DAEI,QAAQ;;;;;;;;;;;;qBAYjD,KAAK,UAAU,SAAS,EAAE;;;;;;;;;;;;;;;;;;AAmB/C,SAAgB,cAAc,UAAgC,CAAC,GAAY;CACzE,MAAM,EAAE,MAAM,SAAS,cAAc,MAAM,YAAY,IAAI,SAAS,WAAW;CAE/E,OAAO;EACL,MAAM,GAAG,QAAQ;EAEjB,MAAM,MAAM,SAAS;GACnB,MAAM,OAAO,QAAQ,OAAO,MAAM;GAElC,OAAO,KAAK;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GAC5C,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;GAElC,QAAQ,IAAI,MAAM,gBAAgB;GAClC,QAAQ,YAAY,GAAG,IAAI,SAAS,MAAM;GAC1C,QAAQ,iBAAiB,GAAG,IAAI,cAAc,MAAM;GAEpD,IAAI,aAAa;IACf,QAAQ,IAAI,MAAM,oBAAoB;IACtC,MAAM,QAAQ,IAAI,CAChB,QAAQ,SAAS,GAAG,IAAI,QAAQ,GAChC,QAAQ,SAAS,GAAG,IAAI,aAAa,CACvC,CAAC;GACH;GAEA,QAAQ,IAAI,MAAM,iBAAiB;GACnC,QAAQ,YAAY,GAAG,IAAI,QAAQ;GAGnC,QAAQ,uBAAuB,GAAG,IAAI,aAAa,EAAE,iBAAiB,GAAG,IAAI,SAAS,CAAC;GAEvF,cACE,GAAG,IAAI,eACP;IACE,sCAAsC,KAAK,UAAU,QAAQ,YAAY,KAAK,EAAE;IAChF,uBAAuB,KAAK,UAAU,IAAI,EAAE;IAC5C,0BAA0B,KAAK,UAAU,QAAQ,WAAW,CAAC,EAAE;GACjE,CAAC,CAAC,KAAK,MAAM,CACf;GAEA,QAAQ,IAAI,MAAM,sBAAsB;GACxC,cAAc,GAAG,IAAI,cAAc,gBAAgB,SAAS,CAAC;GAC7D,cACE,GAAG,IAAI,YACP,WAAW,UAAU,mBAAmB,SAAS,IAAI,kBAAkB,SAAS,CAClF;EACF;EAEA,UAAU,EAIR,YAAY,WAAW,QACzB;CACF;AACF"}
|
package/dist/api-client.js
CHANGED
|
@@ -17,7 +17,7 @@ import * as HttpApiClient from "effect/http-api/HttpApiClient";
|
|
|
17
17
|
* // src/routes/+page.ts — a universal load
|
|
18
18
|
* import { apiClient } from "@thomasfosterau/effect-sveltekit";
|
|
19
19
|
* import { Effect } from "effect";
|
|
20
|
-
* import { api } from "
|
|
20
|
+
* import { api } from "#lib/api.ts"; // the shared HttpApi definition
|
|
21
21
|
*
|
|
22
22
|
* export const load = (event) =>
|
|
23
23
|
* Effect.gen(function* () {
|
package/dist/api-client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.js","names":[],"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * A typed client for an Effect [`HttpApi`](https://effect.website) served by\n * {@link Endpoint.fromApi}, closing the serve↔consume loop.\n *\n * {@link apiClient} wraps Effect's own `HttpApiClient.make` and provides the\n * `HttpClient` for you (via `FetchHttpClient`), so a browser or a universal\n * `load` can call the same-origin API with full end-to-end types derived from\n * the shared `HttpApi` definition. In a `load`, pass `event.fetch` so the call\n * participates in SvelteKit's SSR fetch (relative URLs, credentials, dedupe).\n *\n * @example\n * ```ts\n * // src/routes/+page.ts — a universal load\n * import { apiClient } from \"@thomasfosterau/effect-sveltekit\";\n * import { Effect } from \"effect\";\n * import { api } from \"
|
|
1
|
+
{"version":3,"file":"api-client.js","names":[],"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * A typed client for an Effect [`HttpApi`](https://effect.website) served by\n * {@link Endpoint.fromApi}, closing the serve↔consume loop.\n *\n * {@link apiClient} wraps Effect's own `HttpApiClient.make` and provides the\n * `HttpClient` for you (via `FetchHttpClient`), so a browser or a universal\n * `load` can call the same-origin API with full end-to-end types derived from\n * the shared `HttpApi` definition. In a `load`, pass `event.fetch` so the call\n * participates in SvelteKit's SSR fetch (relative URLs, credentials, dedupe).\n *\n * @example\n * ```ts\n * // src/routes/+page.ts — a universal load\n * import { apiClient } from \"@thomasfosterau/effect-sveltekit\";\n * import { Effect } from \"effect\";\n * import { api } from \"#lib/api.ts\"; // the shared HttpApi definition\n *\n * export const load = (event) =>\n * Effect.gen(function* () {\n * const client = yield* apiClient(api, { baseUrl: \"/api\", fetch: event.fetch });\n * return { user: yield* client.users.get({ path: { id: event.params.id } }) };\n * });\n * ```\n */\n\nimport { Effect, Layer } from \"effect\";\nimport * as FetchHttpClient from \"effect/http/FetchHttpClient\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport type * as HttpApi from \"effect/http-api/HttpApi\";\nimport * as HttpApiClient from \"effect/http-api/HttpApiClient\";\nimport type * as HttpApiGroup from \"effect/http-api/HttpApiGroup\";\n\n/** Options for {@link apiClient}. */\nexport interface ApiClientOptions {\n /**\n * The base URL the API is mounted at. For an `Endpoint.fromApi` mounted at\n * `src/routes/api/[...path]` with `prefix: \"/api\"`, pass `\"/api\"`. Defaults to\n * the endpoint paths relative to the current origin.\n */\n readonly baseUrl?: URL | string;\n /**\n * The `fetch` implementation to use. In a `load`, pass `event.fetch` so the\n * request joins SvelteKit's SSR fetch. Defaults to the platform `fetch`.\n */\n readonly fetch?: typeof globalThis.fetch;\n /** Transform the underlying `HttpClient` (e.g. add headers, retries). */\n readonly transformClient?: (client: HttpClient.HttpClient) => HttpClient.HttpClient;\n}\n\n/**\n * Build a typed {@link HttpApiClient} for `api`, with the `HttpClient` provided\n * via `FetchHttpClient`. Yields the client from an `Effect`; the only remaining\n * requirement is any client middleware the API declares.\n */\nexport const apiClient = <ApiId extends string, Groups extends HttpApiGroup.Constraint>(\n api: HttpApi.HttpApi<ApiId, Groups>,\n options?: ApiClientOptions,\n): Effect.Effect<HttpApiClient.Client<Groups>, never, HttpApiGroup.MiddlewareClient<Groups>> => {\n const fetchLayer =\n options?.fetch === undefined\n ? FetchHttpClient.layer\n : FetchHttpClient.layer.pipe(\n Layer.provide(Layer.succeed(FetchHttpClient.Fetch, options.fetch)),\n );\n\n return HttpApiClient.make(api, {\n baseUrl: options?.baseUrl,\n transformClient: options?.transformClient,\n }).pipe(Effect.provide(fetchLayer));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aACX,KACA,YAC8F;CAC9F,MAAM,aACJ,SAAS,UAAU,KAAA,IACf,gBAAgB,QAChB,gBAAgB,MAAM,KACpB,MAAM,QAAQ,MAAM,QAAQ,gBAAgB,OAAO,QAAQ,KAAK,CAAC,CACnE;CAEN,OAAO,cAAc,KAAK,KAAK;EAC7B,SAAS,SAAS;EAClB,iBAAiB,SAAS;CAC5B,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC;AACpC"}
|
package/dist/app-runtime.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { ErrorTranslator } from "./request-runtime.js";
|
|
|
4
4
|
import { SvelteKitCookies, SvelteKitLocals, SvelteKitResponseHeaders } from "./request-services.js";
|
|
5
5
|
import { Effect, Exit, Fiber, Layer, ManagedRuntime } from "effect";
|
|
6
6
|
import * as HttpClient from "effect/http/HttpClient";
|
|
7
|
-
import { Action, Actions,
|
|
7
|
+
import { Action, Actions, Load, RequestEvent, ServerLoad } from "@sveltejs/kit";
|
|
8
|
+
import { Handle, HandleFetch, HandleServerError, ServerInit } from "@sveltejs/kit/hooks";
|
|
8
9
|
//#region src/app-runtime.d.ts
|
|
9
10
|
/**
|
|
10
11
|
* The services provided to every wrapped effect on the server, in addition to
|
|
@@ -152,9 +153,9 @@ interface ServerRuntime<R = never, E = never> {
|
|
|
152
153
|
*
|
|
153
154
|
* ```ts
|
|
154
155
|
* // src/routes/items/+page.server.ts
|
|
155
|
-
* import { runtime } from '
|
|
156
|
+
* import { runtime } from '#lib/server/runtime.ts';
|
|
156
157
|
* import { Effect } from 'effect';
|
|
157
|
-
* import { Database } from '
|
|
158
|
+
* import { Database } from '#lib/server/database.ts';
|
|
158
159
|
*
|
|
159
160
|
* export const load = runtime.serverLoad((event) =>
|
|
160
161
|
* Effect.gen(function* () {
|
|
@@ -204,16 +205,16 @@ interface UniversalRuntime<R = never, E = never> {
|
|
|
204
205
|
* ```ts
|
|
205
206
|
* // src/lib/runtime.ts
|
|
206
207
|
* import { makeUniversalRuntime } from '@thomasfosterau/effect-sveltekit';
|
|
207
|
-
* import { ApiClient } from '
|
|
208
|
+
* import { ApiClient } from '#lib/api.ts';
|
|
208
209
|
*
|
|
209
210
|
* export const runtime = makeUniversalRuntime(ApiClient.layer);
|
|
210
211
|
* ```
|
|
211
212
|
*
|
|
212
213
|
* ```ts
|
|
213
214
|
* // src/routes/+page.ts
|
|
214
|
-
* import { runtime } from '
|
|
215
|
+
* import { runtime } from '#lib/runtime.ts';
|
|
215
216
|
* import { Effect } from 'effect';
|
|
216
|
-
* import { ApiClient } from '
|
|
217
|
+
* import { ApiClient } from '#lib/api.ts';
|
|
217
218
|
*
|
|
218
219
|
* export const load = runtime.load((event) =>
|
|
219
220
|
* Effect.gen(function* () {
|
package/dist/app-runtime.js
CHANGED
|
@@ -45,9 +45,9 @@ const settle = makeSettle(SvelteKit.translate);
|
|
|
45
45
|
*
|
|
46
46
|
* ```ts
|
|
47
47
|
* // src/routes/items/+page.server.ts
|
|
48
|
-
* import { runtime } from '
|
|
48
|
+
* import { runtime } from '#lib/server/runtime.ts';
|
|
49
49
|
* import { Effect } from 'effect';
|
|
50
|
-
* import { Database } from '
|
|
50
|
+
* import { Database } from '#lib/server/database.ts';
|
|
51
51
|
*
|
|
52
52
|
* export const load = runtime.serverLoad((event) =>
|
|
53
53
|
* Effect.gen(function* () {
|
|
@@ -137,16 +137,16 @@ const makeServerRuntime = (layer, options) => {
|
|
|
137
137
|
* ```ts
|
|
138
138
|
* // src/lib/runtime.ts
|
|
139
139
|
* import { makeUniversalRuntime } from '@thomasfosterau/effect-sveltekit';
|
|
140
|
-
* import { ApiClient } from '
|
|
140
|
+
* import { ApiClient } from '#lib/api.ts';
|
|
141
141
|
*
|
|
142
142
|
* export const runtime = makeUniversalRuntime(ApiClient.layer);
|
|
143
143
|
* ```
|
|
144
144
|
*
|
|
145
145
|
* ```ts
|
|
146
146
|
* // src/routes/+page.ts
|
|
147
|
-
* import { runtime } from '
|
|
147
|
+
* import { runtime } from '#lib/runtime.ts';
|
|
148
148
|
* import { Effect } from 'effect';
|
|
149
|
-
* import { ApiClient } from '
|
|
149
|
+
* import { ApiClient } from '#lib/api.ts';
|
|
150
150
|
*
|
|
151
151
|
* export const load = runtime.load((event) =>
|
|
152
152
|
* Effect.gen(function* () {
|
package/dist/app-runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-runtime.js","names":[],"sources":["../src/app-runtime.ts"],"sourcesContent":["/**\n * App-wide Effect runtimes for SvelteKit.\n *\n * `makeServerRuntime` / `makeUniversalRuntime` let an application define its\n * Effect services (database clients, API wrappers, config, ...) as a single\n * `Layer`, built once per server process and shared by every request, instead\n * of being rebuilt for each `load` / `action` / endpoint invocation.\n *\n * Per-request services — the {@link SvelteKitRequestEvent} and an `HttpClient`\n * backed by the event's `fetch` — are provided on top of the shared runtime\n * for each call, so SvelteKit's fetch behaviours (cookie forwarding, request\n * deduplication, relative URLs) keep working as expected.\n */\n\nimport type {\n Action,\n Actions,\n Handle,\n HandleFetch,\n HandleServerError,\n Load,\n RequestEvent,\n ServerInit,\n ServerLoad,\n} from \"@sveltejs/kit\";\nimport { Context, Effect, type Fiber, Exit, Layer, ManagedRuntime, Scope } from \"effect\";\nimport * as FetchHttpClient from \"effect/http/FetchHttpClient\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport { SvelteKitRequestEvent } from \"./runtime.js\";\nimport type { SvelteRouteParams } from \"./internal/route-params.js\";\nimport type { ErrorTranslator } from \"./request-runtime.js\";\nimport { SvelteKit } from \"./kit.js\";\nimport {\n SvelteKitCookies,\n SvelteKitLocals,\n SvelteKitResponseHeaders,\n requestServicesFrom,\n} from \"./request-services.js\";\n\n/**\n * The services provided to every wrapped effect on the server, in addition to\n * the application's own layer.\n */\nexport type SvelteKitServices =\n | HttpClient.HttpClient\n | SvelteKitRequestEvent\n | SvelteKitCookies\n | SvelteKitResponseHeaders\n | SvelteKitLocals;\n\n/**\n * A per-request Effect runtime: the application layer's services plus the\n * per-request {@link SvelteKitServices} (an `HttpClient` backed by the request's\n * `fetch`, and the {@link SvelteKitRequestEvent}), with the request services\n * built once for the request and shared.\n *\n * A {@link ServerRuntime}'s `handle` hook creates one per request and stores it\n * on `event.locals` (`App.Locals`). Every other wrapper for the same runtime\n * (`serverLoad`, `action`, `endpoint`, ...) then runs on it, so a request's\n * effects share one `HttpClient` and one request scope. Retrieve it from an\n * event with `ServerRuntime.requestRuntime` to run your own effects.\n */\nexport interface RequestRuntime<R = never> {\n /** Run an effect for this request, returning its `Exit`. */\n readonly runPromiseExit: <A>(\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<Exit.Exit<A, unknown>>;\n /** Run an effect for this request, throwing on failure (passing SvelteKit control flow through). */\n readonly runPromise: <A>(effect: Effect.Effect<A, unknown, R | SvelteKitServices>) => Promise<A>;\n /** Fork an effect for this request, returning the running fiber. */\n readonly runFork: <A>(\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Fiber.Fiber<A, unknown>;\n}\n\n/**\n * Symbol under which a {@link ServerRuntime}'s `handle` stores the per-request\n * {@link RequestRuntime} on `event.locals`. `Symbol.for` so the key is stable\n * across module instances.\n */\nconst RequestRuntimeKey: unique symbol = Symbol.for(\n \"@thomasfosterau/effect-sveltekit/requestRuntime\",\n);\n\n/**\n * The locals entry: the per-request runtime tagged with the `ServerRuntime`\n * that created it, so a different runtime's wrappers ignore it (and fall back\n * to building request services themselves) rather than running on the wrong\n * application layer.\n */\ninterface RequestRuntimeEntry {\n readonly owner: object;\n readonly runtime: RequestRuntime<any>;\n}\n\n/** Read the per-request runtime entry an event carries, if any. */\nconst requestRuntimeEntry = (event: RequestEvent): RequestRuntimeEntry | undefined =>\n (event.locals as Record<PropertyKey, unknown> | undefined)?.[RequestRuntimeKey] as\n | RequestRuntimeEntry\n | undefined;\n\n/** Layer with the per-request services for a server-side request. */\nconst requestLayer = (event: RequestEvent): Layer.Layer<SvelteKitServices> => {\n const services = requestServicesFrom(event);\n return Layer.mergeAll(\n FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, event.fetch))),\n Layer.succeed(SvelteKitRequestEvent, event),\n Layer.succeed(SvelteKitCookies, services.cookies),\n Layer.succeed(SvelteKitResponseHeaders, services.responseHeaders),\n Layer.succeed(SvelteKitLocals, services.locals),\n );\n};\n\n/** Layer providing `HttpClient` backed by an arbitrary fetch implementation. */\nconst fetchLayer = (fetchFn: typeof globalThis.fetch): Layer.Layer<HttpClient.HttpClient> =>\n FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));\n\n/** Build a settle that returns a success value or throws via the translator. */\nconst makeSettle =\n (translate: ErrorTranslator) =>\n <A>(exit: Exit.Exit<A, unknown>): A =>\n Exit.match(exit, {\n onFailure: (cause) => translate(cause),\n onSuccess: (value) => value,\n });\n\n/** The default settle: Kit control-flow errors through, anything else a 500. */\nconst settle = makeSettle(SvelteKit.translate);\n\n/**\n * Options for {@link makeServerRuntime}.\n */\nexport interface ServerRuntimeOptions {\n /**\n * Translate a failed `Cause` into SvelteKit control flow at the boundary of\n * every wrapper (`serverLoad`, `action`, `actions`, `endpoint`, `handle`,\n * `handleFetch`, `handleError`, `init`). It may throw `redirect()` /\n * `error()` so a domain error catalogue surfaces as SvelteKit control flow\n * instead of a generic 500. Defaults to the package passthrough: SvelteKit's\n * own `redirect()` / `error()` are rethrown, anything else becomes an\n * `EffectCauseError` (a 500).\n */\n readonly translateError?: ErrorTranslator;\n}\n\n/**\n * A server-side Effect runtime bound to an application layer.\n *\n * Produced by {@link makeServerRuntime}. The wrapper methods mirror the\n * standalone helpers in `@thomasfosterau/effect-sveltekit/server`, but\n * effects additionally have access to the services `R` of the application\n * layer.\n */\nexport interface ServerRuntime<R = never, E = never> {\n /** The underlying managed runtime for the application layer. */\n readonly runtime: ManagedRuntime.ManagedRuntime<R, E>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `load`.\n */\n readonly serverLoad: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n ParentData extends Record<string, any> = any,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>,\n ) => ServerLoad<Params, ParentData, OutputData, RouteId>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit form action.\n */\n readonly action: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>,\n ) => Action<Params, OutputData, RouteId>;\n\n /**\n * Wraps an object of Effect-based form actions.\n */\n readonly actions: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n actionsMap: Record<\n string,\n (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>\n >,\n ) => Actions<Params, OutputData, RouteId>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit `handle` hook.\n */\n readonly handle: (\n fn: (args: Parameters<Handle>[0]) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => Handle;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `handleFetch` hook,\n * which intercepts `event.fetch` calls made on the server. The effect runs\n * with the per-request services on top of the application layer and produces\n * the `Response` to use.\n */\n readonly handleFetch: (\n fn: (\n args: Parameters<HandleFetch>[0],\n ) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => HandleFetch;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `handleError` hook.\n *\n * The effect receives the error and the request event, and produces the\n * shape that SvelteKit exposes to the client (your `App.Error`, or nothing).\n * It runs with the per-request services on top of the application layer.\n */\n readonly handleError: (\n fn: (\n args: Parameters<HandleServerError>[0],\n ) => Effect.Effect<Awaited<ReturnType<HandleServerError>>, unknown, R | SvelteKitServices>,\n ) => HandleServerError;\n\n /**\n * Wraps an Effect as a SvelteKit server `init` hook, run once before the\n * server responds to its first request. There is no request event, so the\n * effect only has access to the application layer's services.\n */\n readonly init: (effect: Effect.Effect<void, unknown, R>) => ServerInit;\n\n /**\n * The per-request {@link RequestRuntime} this runtime's `handle` stored on the\n * event, or `undefined` when `handle` was not used for the request. Use it to\n * run your own effects on the same per-request runtime (shared `HttpClient`\n * and request scope) that `serverLoad` / `action` / `endpoint` use.\n *\n * @example\n * ```ts\n * // anywhere with the request event, e.g. another `handle` in the sequence\n * const rt = runtime.requestRuntime(event);\n * await rt?.runPromise(Effect.gen(function* () {\n * const user = yield* Auth.currentUser;\n * event.locals.user = user;\n * }));\n * ```\n */\n readonly requestRuntime: (event: RequestEvent) => RequestRuntime<R> | undefined;\n\n /**\n * Wraps an Effect-based function as a SvelteKit `+server.ts` endpoint\n * handler (`GET`, `POST`, ...).\n */\n readonly endpoint: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => (event: RequestEvent<Params, RouteId>) => Promise<Response>;\n\n /**\n * Runs an effect for a specific request, providing both the application\n * layer and the per-request services. Failures (other than SvelteKit\n * control flow) are thrown as `EffectCauseError`.\n */\n readonly runPromise: <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<A>;\n\n /**\n * Runs an effect for a specific request and returns the Exit, without\n * translating failures into thrown errors.\n */\n readonly runPromiseExit: <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<Exit.Exit<A, unknown>>;\n\n /**\n * Disposes the underlying managed runtime, running the layer's finalizers.\n * Call this on server shutdown or in tests.\n */\n readonly dispose: () => Promise<void>;\n}\n\n/**\n * Creates a {@link ServerRuntime} from an application layer.\n *\n * The layer is built lazily on first use and shared by all requests for the\n * lifetime of the server process. Define it once in a server-only module and\n * import its wrappers from your routes:\n *\n * @example\n * ```ts\n * // src/lib/server/runtime.ts\n * import { makeServerRuntime } from '@thomasfosterau/effect-sveltekit/server';\n * import { Layer } from 'effect';\n * import { Database } from './database';\n *\n * export const runtime = makeServerRuntime(Database.layer);\n * ```\n *\n * ```ts\n * // src/routes/items/+page.server.ts\n * import { runtime } from '$lib/server/runtime';\n * import { Effect } from 'effect';\n * import { Database } from '$lib/server/database';\n *\n * export const load = runtime.serverLoad((event) =>\n * Effect.gen(function* () {\n * const db = yield* Database;\n * return { items: yield* db.listItems() };\n * })\n * );\n * ```\n *\n * Note that the application layer is built outside of any request, so its\n * services cannot depend on the per-request `SvelteKitRequestEvent` or\n * `HttpClient`. Request-specific data should be passed to service methods as\n * arguments instead.\n */\nexport const makeServerRuntime = <R = never, E = never>(\n layer?: Layer.Layer<R, E>,\n options?: ServerRuntimeOptions,\n): ServerRuntime<R, E> => {\n const runtime = ManagedRuntime.make((layer ?? Layer.empty) as Layer.Layer<R, E>);\n\n // The boundary translator for this runtime's wrappers (defaults to the\n // package passthrough: SvelteKit control flow through, anything else a 500).\n const settleRequest = options?.translateError ? makeSettle(options.translateError) : settle;\n\n // Identity token tagging the per-request runtimes this runtime creates, so a\n // different runtime's wrappers don't run on the wrong application layer.\n const owner = {};\n\n /** A {@link ScopedRequestRuntime} that provides the prebuilt request services. */\n const makeRequestRuntime = (\n requestServices: Context.Context<SvelteKitServices>,\n ): RequestRuntime<R> => {\n const provide = <A>(effect: Effect.Effect<A, unknown, R | SvelteKitServices>) =>\n Effect.provideContext(effect, requestServices) as Effect.Effect<A, unknown, R>;\n return {\n runPromiseExit: (effect) =>\n runtime.runPromiseExit(provide(effect)) as Promise<Exit.Exit<any, unknown>>,\n runPromise: (effect) => runtime.runPromiseExit(provide(effect)).then(settleRequest),\n runFork: (effect) => runtime.runFork(provide(effect)) as Fiber.Fiber<any, unknown>,\n };\n };\n\n /** The per-request runtime for this runtime carried by the event, if any. */\n const requestRuntimeOf = (event: RequestEvent): RequestRuntime<R> | undefined => {\n const entry = requestRuntimeEntry(event);\n return entry?.owner === owner ? (entry.runtime as RequestRuntime<R>) : undefined;\n };\n\n const runExit = <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ): Promise<Exit.Exit<A, unknown>> => {\n // Reuse the per-request runtime `handle` installed, if any; otherwise build\n // the per-request services for this single call.\n const requestRuntime = requestRuntimeOf(event);\n if (requestRuntime !== undefined) return requestRuntime.runPromiseExit(effect);\n const provided = Effect.provide(effect, requestLayer(event)) as Effect.Effect<A, unknown, R>;\n return runtime.runPromiseExit(provided) as Promise<Exit.Exit<A, unknown>>;\n };\n\n const run = <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ): Promise<A> => runExit(event, effect).then(settleRequest);\n\n const action: ServerRuntime<R, E>[\"action\"] = (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`action ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n );\n\n /**\n * The `handle` hook: build a per-request runtime, store it on `event.locals`\n * so every other wrapper (and the user's own code) runs on it, run the user's\n * effect, then close the request scope.\n */\n const handle: ServerRuntime<R, E>[\"handle\"] = (fn) => async (input) => {\n const { event } = input;\n const scope = Scope.makeUnsafe();\n const requestServices = (await runtime.runPromise(\n Layer.buildWithScope(requestLayer(event), scope),\n )) as Context.Context<SvelteKitServices>;\n\n const entry: RequestRuntimeEntry = { owner, runtime: makeRequestRuntime(requestServices) };\n (event.locals as Record<PropertyKey, unknown>)[RequestRuntimeKey] = entry;\n\n try {\n return await (entry.runtime as RequestRuntime<R>).runPromise(\n fn(input).pipe(\n Effect.withSpan(`handle ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n );\n } finally {\n await runtime.runPromise(Scope.close(scope, Exit.void));\n }\n };\n\n return {\n runtime,\n serverLoad: (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`serverLoad ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n ),\n action,\n actions: (actionsMap) => {\n const wrapped: Record<string, Action<any, any, any>> = {};\n for (const [key, fn] of Object.entries(actionsMap)) {\n wrapped[key] = action(fn);\n }\n return wrapped as never;\n },\n handle,\n handleFetch: (fn) => (args) =>\n run(\n args.event,\n fn(args).pipe(\n Effect.withSpan(`handleFetch ${args.event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n ),\n handleError: (fn) => (args) => run(args.event, fn(args)),\n init: (effect) => async () => {\n // `init` runs outside of any request, so it executes directly on the\n // application runtime without the per-request layer.\n settleRequest(await runtime.runPromiseExit(effect));\n },\n requestRuntime: requestRuntimeOf,\n endpoint: (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`${event.request.method} ${event.route.id ?? \"(unknown)\"}`, {\n kind: \"server\",\n }),\n ),\n ),\n runPromise: run,\n runPromiseExit: runExit,\n dispose: () => runtime.dispose(),\n };\n};\n\n/**\n * A universal (client + server) Effect runtime bound to an application layer.\n *\n * Produced by {@link makeUniversalRuntime}. Because universal `load`\n * functions also run in the browser, the layer must only use services that\n * work in both environments.\n */\nexport interface UniversalRuntime<R = never, E = never> {\n /** The underlying managed runtime for the application layer. */\n readonly runtime: ManagedRuntime.ManagedRuntime<R, E>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit universal `load`.\n *\n * The effect gets `HttpClient` (backed by the load event's `fetch`) on both\n * client and server, plus the services of the application layer.\n */\n readonly 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, R | HttpClient.HttpClient>,\n ) => Load<Params, InputData, ParentData, OutputData, RouteId>;\n\n /**\n * Runs an effect with `HttpClient` backed by the given fetch implementation\n * plus the application layer.\n */\n readonly runPromise: <A>(\n fetchFn: typeof globalThis.fetch,\n effect: Effect.Effect<A, unknown, R | HttpClient.HttpClient>,\n ) => Promise<A>;\n\n /**\n * Disposes the underlying managed runtime, running the layer's finalizers.\n */\n readonly dispose: () => Promise<void>;\n}\n\n/**\n * Creates a {@link UniversalRuntime} from an application layer.\n *\n * @example\n * ```ts\n * // src/lib/runtime.ts\n * import { makeUniversalRuntime } from '@thomasfosterau/effect-sveltekit';\n * import { ApiClient } from '$lib/api';\n *\n * export const runtime = makeUniversalRuntime(ApiClient.layer);\n * ```\n *\n * ```ts\n * // src/routes/+page.ts\n * import { runtime } from '$lib/runtime';\n * import { Effect } from 'effect';\n * import { ApiClient } from '$lib/api';\n *\n * export const load = runtime.load((event) =>\n * Effect.gen(function* () {\n * const api = yield* ApiClient;\n * return { stories: yield* api.topStories() };\n * })\n * );\n * ```\n */\nexport const makeUniversalRuntime = <R = never, E = never>(\n layer?: Layer.Layer<R, E>,\n): UniversalRuntime<R, E> => {\n const runtime = ManagedRuntime.make((layer ?? Layer.empty) as Layer.Layer<R, E>);\n\n const run = <A>(\n fetchFn: typeof globalThis.fetch,\n effect: Effect.Effect<A, unknown, R | HttpClient.HttpClient>,\n event?: RequestEvent,\n ): Promise<A> => {\n // On the server the full request layer (HttpClient + SvelteKitRequestEvent)\n // is available; on the client only HttpClient backed by the event's fetch.\n const services = event ? requestLayer(event) : fetchLayer(fetchFn);\n const provided = Effect.provide(effect, services) as Effect.Effect<A, unknown, R>;\n return runtime.runPromiseExit(provided).then(settle);\n };\n\n return {\n runtime,\n load: (fn) => (event) => {\n const serverEvent = (event as { request?: unknown }).request\n ? (event as unknown as RequestEvent)\n : undefined;\n return run(event.fetch, fn(event), serverEvent);\n },\n runPromise: (fetchFn, effect) => run(fetchFn, effect),\n dispose: () => runtime.dispose(),\n };\n};\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"app-runtime.js","names":[],"sources":["../src/app-runtime.ts"],"sourcesContent":["/**\n * App-wide Effect runtimes for SvelteKit.\n *\n * `makeServerRuntime` / `makeUniversalRuntime` let an application define its\n * Effect services (database clients, API wrappers, config, ...) as a single\n * `Layer`, built once per server process and shared by every request, instead\n * of being rebuilt for each `load` / `action` / endpoint invocation.\n *\n * Per-request services — the {@link SvelteKitRequestEvent} and an `HttpClient`\n * backed by the event's `fetch` — are provided on top of the shared runtime\n * for each call, so SvelteKit's fetch behaviours (cookie forwarding, request\n * deduplication, relative URLs) keep working as expected.\n */\n\nimport type { Action, Actions, Load, RequestEvent, ServerLoad } from \"@sveltejs/kit\";\nimport type { Handle, HandleFetch, HandleServerError, ServerInit } from \"@sveltejs/kit/hooks\";\nimport { Context, Effect, type Fiber, Exit, Layer, ManagedRuntime, Scope } from \"effect\";\nimport * as FetchHttpClient from \"effect/http/FetchHttpClient\";\nimport type * as HttpClient from \"effect/http/HttpClient\";\nimport { SvelteKitRequestEvent } from \"./runtime.js\";\nimport type { SvelteRouteParams } from \"./internal/route-params.js\";\nimport type { ErrorTranslator } from \"./request-runtime.js\";\nimport { SvelteKit } from \"./kit.js\";\nimport {\n SvelteKitCookies,\n SvelteKitLocals,\n SvelteKitResponseHeaders,\n requestServicesFrom,\n} from \"./request-services.js\";\n\n/**\n * The services provided to every wrapped effect on the server, in addition to\n * the application's own layer.\n */\nexport type SvelteKitServices =\n | HttpClient.HttpClient\n | SvelteKitRequestEvent\n | SvelteKitCookies\n | SvelteKitResponseHeaders\n | SvelteKitLocals;\n\n/**\n * A per-request Effect runtime: the application layer's services plus the\n * per-request {@link SvelteKitServices} (an `HttpClient` backed by the request's\n * `fetch`, and the {@link SvelteKitRequestEvent}), with the request services\n * built once for the request and shared.\n *\n * A {@link ServerRuntime}'s `handle` hook creates one per request and stores it\n * on `event.locals` (`App.Locals`). Every other wrapper for the same runtime\n * (`serverLoad`, `action`, `endpoint`, ...) then runs on it, so a request's\n * effects share one `HttpClient` and one request scope. Retrieve it from an\n * event with `ServerRuntime.requestRuntime` to run your own effects.\n */\nexport interface RequestRuntime<R = never> {\n /** Run an effect for this request, returning its `Exit`. */\n readonly runPromiseExit: <A>(\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<Exit.Exit<A, unknown>>;\n /** Run an effect for this request, throwing on failure (passing SvelteKit control flow through). */\n readonly runPromise: <A>(effect: Effect.Effect<A, unknown, R | SvelteKitServices>) => Promise<A>;\n /** Fork an effect for this request, returning the running fiber. */\n readonly runFork: <A>(\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Fiber.Fiber<A, unknown>;\n}\n\n/**\n * Symbol under which a {@link ServerRuntime}'s `handle` stores the per-request\n * {@link RequestRuntime} on `event.locals`. `Symbol.for` so the key is stable\n * across module instances.\n */\nconst RequestRuntimeKey: unique symbol = Symbol.for(\n \"@thomasfosterau/effect-sveltekit/requestRuntime\",\n);\n\n/**\n * The locals entry: the per-request runtime tagged with the `ServerRuntime`\n * that created it, so a different runtime's wrappers ignore it (and fall back\n * to building request services themselves) rather than running on the wrong\n * application layer.\n */\ninterface RequestRuntimeEntry {\n readonly owner: object;\n readonly runtime: RequestRuntime<any>;\n}\n\n/** Read the per-request runtime entry an event carries, if any. */\nconst requestRuntimeEntry = (event: RequestEvent): RequestRuntimeEntry | undefined =>\n (event.locals as Record<PropertyKey, unknown> | undefined)?.[RequestRuntimeKey] as\n | RequestRuntimeEntry\n | undefined;\n\n/** Layer with the per-request services for a server-side request. */\nconst requestLayer = (event: RequestEvent): Layer.Layer<SvelteKitServices> => {\n const services = requestServicesFrom(event);\n return Layer.mergeAll(\n FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, event.fetch))),\n Layer.succeed(SvelteKitRequestEvent, event),\n Layer.succeed(SvelteKitCookies, services.cookies),\n Layer.succeed(SvelteKitResponseHeaders, services.responseHeaders),\n Layer.succeed(SvelteKitLocals, services.locals),\n );\n};\n\n/** Layer providing `HttpClient` backed by an arbitrary fetch implementation. */\nconst fetchLayer = (fetchFn: typeof globalThis.fetch): Layer.Layer<HttpClient.HttpClient> =>\n FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));\n\n/** Build a settle that returns a success value or throws via the translator. */\nconst makeSettle =\n (translate: ErrorTranslator) =>\n <A>(exit: Exit.Exit<A, unknown>): A =>\n Exit.match(exit, {\n onFailure: (cause) => translate(cause),\n onSuccess: (value) => value,\n });\n\n/** The default settle: Kit control-flow errors through, anything else a 500. */\nconst settle = makeSettle(SvelteKit.translate);\n\n/**\n * Options for {@link makeServerRuntime}.\n */\nexport interface ServerRuntimeOptions {\n /**\n * Translate a failed `Cause` into SvelteKit control flow at the boundary of\n * every wrapper (`serverLoad`, `action`, `actions`, `endpoint`, `handle`,\n * `handleFetch`, `handleError`, `init`). It may throw `redirect()` /\n * `error()` so a domain error catalogue surfaces as SvelteKit control flow\n * instead of a generic 500. Defaults to the package passthrough: SvelteKit's\n * own `redirect()` / `error()` are rethrown, anything else becomes an\n * `EffectCauseError` (a 500).\n */\n readonly translateError?: ErrorTranslator;\n}\n\n/**\n * A server-side Effect runtime bound to an application layer.\n *\n * Produced by {@link makeServerRuntime}. The wrapper methods mirror the\n * standalone helpers in `@thomasfosterau/effect-sveltekit/server`, but\n * effects additionally have access to the services `R` of the application\n * layer.\n */\nexport interface ServerRuntime<R = never, E = never> {\n /** The underlying managed runtime for the application layer. */\n readonly runtime: ManagedRuntime.ManagedRuntime<R, E>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `load`.\n */\n readonly serverLoad: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n ParentData extends Record<string, any> = any,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>,\n ) => ServerLoad<Params, ParentData, OutputData, RouteId>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit form action.\n */\n readonly action: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>,\n ) => Action<Params, OutputData, RouteId>;\n\n /**\n * Wraps an object of Effect-based form actions.\n */\n readonly actions: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n OutputData extends Record<string, any> | void = any,\n RouteId extends string | null = any,\n >(\n actionsMap: Record<\n string,\n (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<OutputData, unknown, R | SvelteKitServices>\n >,\n ) => Actions<Params, OutputData, RouteId>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit `handle` hook.\n */\n readonly handle: (\n fn: (args: Parameters<Handle>[0]) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => Handle;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `handleFetch` hook,\n * which intercepts `event.fetch` calls made on the server. The effect runs\n * with the per-request services on top of the application layer and produces\n * the `Response` to use.\n */\n readonly handleFetch: (\n fn: (\n args: Parameters<HandleFetch>[0],\n ) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => HandleFetch;\n\n /**\n * Wraps an Effect-based function as a SvelteKit server `handleError` hook.\n *\n * The effect receives the error and the request event, and produces the\n * shape that SvelteKit exposes to the client (your `App.Error`, or nothing).\n * It runs with the per-request services on top of the application layer.\n */\n readonly handleError: (\n fn: (\n args: Parameters<HandleServerError>[0],\n ) => Effect.Effect<Awaited<ReturnType<HandleServerError>>, unknown, R | SvelteKitServices>,\n ) => HandleServerError;\n\n /**\n * Wraps an Effect as a SvelteKit server `init` hook, run once before the\n * server responds to its first request. There is no request event, so the\n * effect only has access to the application layer's services.\n */\n readonly init: (effect: Effect.Effect<void, unknown, R>) => ServerInit;\n\n /**\n * The per-request {@link RequestRuntime} this runtime's `handle` stored on the\n * event, or `undefined` when `handle` was not used for the request. Use it to\n * run your own effects on the same per-request runtime (shared `HttpClient`\n * and request scope) that `serverLoad` / `action` / `endpoint` use.\n *\n * @example\n * ```ts\n * // anywhere with the request event, e.g. another `handle` in the sequence\n * const rt = runtime.requestRuntime(event);\n * await rt?.runPromise(Effect.gen(function* () {\n * const user = yield* Auth.currentUser;\n * event.locals.user = user;\n * }));\n * ```\n */\n readonly requestRuntime: (event: RequestEvent) => RequestRuntime<R> | undefined;\n\n /**\n * Wraps an Effect-based function as a SvelteKit `+server.ts` endpoint\n * handler (`GET`, `POST`, ...).\n */\n readonly endpoint: <\n Params extends SvelteRouteParams = SvelteRouteParams,\n RouteId extends string | null = any,\n >(\n fn: (\n event: RequestEvent<Params, RouteId>,\n ) => Effect.Effect<Response, unknown, R | SvelteKitServices>,\n ) => (event: RequestEvent<Params, RouteId>) => Promise<Response>;\n\n /**\n * Runs an effect for a specific request, providing both the application\n * layer and the per-request services. Failures (other than SvelteKit\n * control flow) are thrown as `EffectCauseError`.\n */\n readonly runPromise: <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<A>;\n\n /**\n * Runs an effect for a specific request and returns the Exit, without\n * translating failures into thrown errors.\n */\n readonly runPromiseExit: <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ) => Promise<Exit.Exit<A, unknown>>;\n\n /**\n * Disposes the underlying managed runtime, running the layer's finalizers.\n * Call this on server shutdown or in tests.\n */\n readonly dispose: () => Promise<void>;\n}\n\n/**\n * Creates a {@link ServerRuntime} from an application layer.\n *\n * The layer is built lazily on first use and shared by all requests for the\n * lifetime of the server process. Define it once in a server-only module and\n * import its wrappers from your routes:\n *\n * @example\n * ```ts\n * // src/lib/server/runtime.ts\n * import { makeServerRuntime } from '@thomasfosterau/effect-sveltekit/server';\n * import { Layer } from 'effect';\n * import { Database } from './database';\n *\n * export const runtime = makeServerRuntime(Database.layer);\n * ```\n *\n * ```ts\n * // src/routes/items/+page.server.ts\n * import { runtime } from '#lib/server/runtime.ts';\n * import { Effect } from 'effect';\n * import { Database } from '#lib/server/database.ts';\n *\n * export const load = runtime.serverLoad((event) =>\n * Effect.gen(function* () {\n * const db = yield* Database;\n * return { items: yield* db.listItems() };\n * })\n * );\n * ```\n *\n * Note that the application layer is built outside of any request, so its\n * services cannot depend on the per-request `SvelteKitRequestEvent` or\n * `HttpClient`. Request-specific data should be passed to service methods as\n * arguments instead.\n */\nexport const makeServerRuntime = <R = never, E = never>(\n layer?: Layer.Layer<R, E>,\n options?: ServerRuntimeOptions,\n): ServerRuntime<R, E> => {\n const runtime = ManagedRuntime.make((layer ?? Layer.empty) as Layer.Layer<R, E>);\n\n // The boundary translator for this runtime's wrappers (defaults to the\n // package passthrough: SvelteKit control flow through, anything else a 500).\n const settleRequest = options?.translateError ? makeSettle(options.translateError) : settle;\n\n // Identity token tagging the per-request runtimes this runtime creates, so a\n // different runtime's wrappers don't run on the wrong application layer.\n const owner = {};\n\n /** A {@link ScopedRequestRuntime} that provides the prebuilt request services. */\n const makeRequestRuntime = (\n requestServices: Context.Context<SvelteKitServices>,\n ): RequestRuntime<R> => {\n const provide = <A>(effect: Effect.Effect<A, unknown, R | SvelteKitServices>) =>\n Effect.provideContext(effect, requestServices) as Effect.Effect<A, unknown, R>;\n return {\n runPromiseExit: (effect) =>\n runtime.runPromiseExit(provide(effect)) as Promise<Exit.Exit<any, unknown>>,\n runPromise: (effect) => runtime.runPromiseExit(provide(effect)).then(settleRequest),\n runFork: (effect) => runtime.runFork(provide(effect)) as Fiber.Fiber<any, unknown>,\n };\n };\n\n /** The per-request runtime for this runtime carried by the event, if any. */\n const requestRuntimeOf = (event: RequestEvent): RequestRuntime<R> | undefined => {\n const entry = requestRuntimeEntry(event);\n return entry?.owner === owner ? (entry.runtime as RequestRuntime<R>) : undefined;\n };\n\n const runExit = <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ): Promise<Exit.Exit<A, unknown>> => {\n // Reuse the per-request runtime `handle` installed, if any; otherwise build\n // the per-request services for this single call.\n const requestRuntime = requestRuntimeOf(event);\n if (requestRuntime !== undefined) return requestRuntime.runPromiseExit(effect);\n const provided = Effect.provide(effect, requestLayer(event)) as Effect.Effect<A, unknown, R>;\n return runtime.runPromiseExit(provided) as Promise<Exit.Exit<A, unknown>>;\n };\n\n const run = <A>(\n event: RequestEvent,\n effect: Effect.Effect<A, unknown, R | SvelteKitServices>,\n ): Promise<A> => runExit(event, effect).then(settleRequest);\n\n const action: ServerRuntime<R, E>[\"action\"] = (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`action ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n );\n\n /**\n * The `handle` hook: build a per-request runtime, store it on `event.locals`\n * so every other wrapper (and the user's own code) runs on it, run the user's\n * effect, then close the request scope.\n */\n const handle: ServerRuntime<R, E>[\"handle\"] = (fn) => async (input) => {\n const { event } = input;\n const scope = Scope.makeUnsafe();\n const requestServices = (await runtime.runPromise(\n Layer.buildWithScope(requestLayer(event), scope),\n )) as Context.Context<SvelteKitServices>;\n\n const entry: RequestRuntimeEntry = { owner, runtime: makeRequestRuntime(requestServices) };\n (event.locals as Record<PropertyKey, unknown>)[RequestRuntimeKey] = entry;\n\n try {\n return await (entry.runtime as RequestRuntime<R>).runPromise(\n fn(input).pipe(\n Effect.withSpan(`handle ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n );\n } finally {\n await runtime.runPromise(Scope.close(scope, Exit.void));\n }\n };\n\n return {\n runtime,\n serverLoad: (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`serverLoad ${event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n ),\n action,\n actions: (actionsMap) => {\n const wrapped: Record<string, Action<any, any, any>> = {};\n for (const [key, fn] of Object.entries(actionsMap)) {\n wrapped[key] = action(fn);\n }\n return wrapped as never;\n },\n handle,\n handleFetch: (fn) => (args) =>\n run(\n args.event,\n fn(args).pipe(\n Effect.withSpan(`handleFetch ${args.event.route.id ?? \"(unknown)\"}`, { kind: \"server\" }),\n ),\n ),\n handleError: (fn) => (args) => run(args.event, fn(args)),\n init: (effect) => async () => {\n // `init` runs outside of any request, so it executes directly on the\n // application runtime without the per-request layer.\n settleRequest(await runtime.runPromiseExit(effect));\n },\n requestRuntime: requestRuntimeOf,\n endpoint: (fn) => (event) =>\n run(\n event,\n fn(event).pipe(\n Effect.withSpan(`${event.request.method} ${event.route.id ?? \"(unknown)\"}`, {\n kind: \"server\",\n }),\n ),\n ),\n runPromise: run,\n runPromiseExit: runExit,\n dispose: () => runtime.dispose(),\n };\n};\n\n/**\n * A universal (client + server) Effect runtime bound to an application layer.\n *\n * Produced by {@link makeUniversalRuntime}. Because universal `load`\n * functions also run in the browser, the layer must only use services that\n * work in both environments.\n */\nexport interface UniversalRuntime<R = never, E = never> {\n /** The underlying managed runtime for the application layer. */\n readonly runtime: ManagedRuntime.ManagedRuntime<R, E>;\n\n /**\n * Wraps an Effect-based function as a SvelteKit universal `load`.\n *\n * The effect gets `HttpClient` (backed by the load event's `fetch`) on both\n * client and server, plus the services of the application layer.\n */\n readonly 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, R | HttpClient.HttpClient>,\n ) => Load<Params, InputData, ParentData, OutputData, RouteId>;\n\n /**\n * Runs an effect with `HttpClient` backed by the given fetch implementation\n * plus the application layer.\n */\n readonly runPromise: <A>(\n fetchFn: typeof globalThis.fetch,\n effect: Effect.Effect<A, unknown, R | HttpClient.HttpClient>,\n ) => Promise<A>;\n\n /**\n * Disposes the underlying managed runtime, running the layer's finalizers.\n */\n readonly dispose: () => Promise<void>;\n}\n\n/**\n * Creates a {@link UniversalRuntime} from an application layer.\n *\n * @example\n * ```ts\n * // src/lib/runtime.ts\n * import { makeUniversalRuntime } from '@thomasfosterau/effect-sveltekit';\n * import { ApiClient } from '#lib/api.ts';\n *\n * export const runtime = makeUniversalRuntime(ApiClient.layer);\n * ```\n *\n * ```ts\n * // src/routes/+page.ts\n * import { runtime } from '#lib/runtime.ts';\n * import { Effect } from 'effect';\n * import { ApiClient } from '#lib/api.ts';\n *\n * export const load = runtime.load((event) =>\n * Effect.gen(function* () {\n * const api = yield* ApiClient;\n * return { stories: yield* api.topStories() };\n * })\n * );\n * ```\n */\nexport const makeUniversalRuntime = <R = never, E = never>(\n layer?: Layer.Layer<R, E>,\n): UniversalRuntime<R, E> => {\n const runtime = ManagedRuntime.make((layer ?? Layer.empty) as Layer.Layer<R, E>);\n\n const run = <A>(\n fetchFn: typeof globalThis.fetch,\n effect: Effect.Effect<A, unknown, R | HttpClient.HttpClient>,\n event?: RequestEvent,\n ): Promise<A> => {\n // On the server the full request layer (HttpClient + SvelteKitRequestEvent)\n // is available; on the client only HttpClient backed by the event's fetch.\n const services = event ? requestLayer(event) : fetchLayer(fetchFn);\n const provided = Effect.provide(effect, services) as Effect.Effect<A, unknown, R>;\n return runtime.runPromiseExit(provided).then(settle);\n };\n\n return {\n runtime,\n load: (fn) => (event) => {\n const serverEvent = (event as { request?: unknown }).request\n ? (event as unknown as RequestEvent)\n : undefined;\n return run(event.fetch, fn(event), serverEvent);\n },\n runPromise: (fetchFn, effect) => run(fetchFn, effect),\n dispose: () => runtime.dispose(),\n };\n};\n"],"mappings":"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"}
|
package/dist/client/Hooks.d.ts
CHANGED
package/dist/client/Hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Hooks.js","names":[],"sources":["../../src/client/Hooks.ts"],"sourcesContent":["/**\n * Effect wrappers for SvelteKit's client-side hooks (`src/hooks.client.ts`),\n * exposed as the `Hooks` namespace of `@thomasfosterau/effect-sveltekit/client`.\n *\n * These mirror the server hook helpers in `../server/Hooks.ts`, but run on the\n * client: there is no request context, so each effect runs on a bare Effect\n * runtime. For application services, run the effect through your own runtime\n * instead. Kept free of `$app/*` imports so it stays importable (and testable)\n * outside of a SvelteKit app.\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const handleError = Hooks.handleError(({ error, event }) =>\n * Effect.as(Effect.logError(`navigation to ${event.url.pathname} failed`, error), {\n * message: 'Something went wrong',\n * })\n * );\n * ```\n */\n\nimport type { ClientInit, HandleClientError } from \"@sveltejs/kit\";\nimport { Effect, Exit } from \"effect\";\nimport { causeToThrowable } from \"../internal/error.js\";\n\n/** Run a bare Effect (no request context) and settle it the way a hook expects. */\nconst runBareHook = async <A>(effect: Effect.Effect<A, unknown>): Promise<A> =>\n Exit.match(await Effect.runPromiseExit(effect), {\n onFailure: (cause) => {\n throw causeToThrowable(cause);\n },\n onSuccess: (value) => value,\n });\n\n/**\n * Wraps an Effect-based function as the SvelteKit client\n * [`handleError`](https://svelte.dev/docs/kit/hooks#Shared-hooks-handleError)\n * hook, which runs when an unexpected error is thrown while navigating in the\n * browser. The effect receives the error and navigation event and produces the\n * shape exposed to the page (your `App.Error`, or nothing).\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const handleError = Hooks.handleError(({ error, event }) =>\n * Effect.gen(function* () {\n * yield* Effect.logError(`navigation to ${event.url.pathname} failed`, error);\n * return { message: 'Something went wrong' };\n * })\n * );\n * ```\n */\nexport function handleError(\n fn: (\n args: Parameters<HandleClientError>[0],\n ) => Effect.Effect<Awaited<ReturnType<HandleClientError>>, unknown>,\n): HandleClientError {\n return (args) => runBareHook(fn(args));\n}\n\n/**\n * Wraps an Effect as the SvelteKit client\n * [`init`](https://svelte.dev/docs/kit/hooks#Shared-hooks-init) hook, which\n * runs once when the app starts in the browser. The effect runs on a bare\n * Effect runtime.\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const init = Hooks.init(Effect.logInfo('client app started'));\n * ```\n */\nexport function init(effect: Effect.Effect<void, unknown>): ClientInit {\n return () => runBareHook(effect);\n}\n"],"mappings":";;;;;;;;;AA6BA,MAAM,cAAc,OAAU,WAC5B,KAAK,MAAM,MAAM,OAAO,eAAe,MAAM,GAAG;CAC9C,YAAY,UAAU;EACpB,MAAM,iBAAiB,KAAK;CAC9B;CACA,YAAY,UAAU;AACxB,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBH,SAAgB,YACd,IAGmB;CACnB,QAAQ,SAAS,YAAY,GAAG,IAAI,CAAC;AACvC;;;;;;;;;;;;;;;;AAiBA,SAAgB,KAAK,QAAkD;CACrE,aAAa,YAAY,MAAM;AACjC"}
|
|
1
|
+
{"version":3,"file":"Hooks.js","names":[],"sources":["../../src/client/Hooks.ts"],"sourcesContent":["/**\n * Effect wrappers for SvelteKit's client-side hooks (`src/hooks.client.ts`),\n * exposed as the `Hooks` namespace of `@thomasfosterau/effect-sveltekit/client`.\n *\n * These mirror the server hook helpers in `../server/Hooks.ts`, but run on the\n * client: there is no request context, so each effect runs on a bare Effect\n * runtime. For application services, run the effect through your own runtime\n * instead. Kept free of `$app/*` imports so it stays importable (and testable)\n * outside of a SvelteKit app.\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const handleError = Hooks.handleError(({ error, event }) =>\n * Effect.as(Effect.logError(`navigation to ${event.url.pathname} failed`, error), {\n * message: 'Something went wrong',\n * })\n * );\n * ```\n */\n\nimport type { ClientInit, HandleClientError } from \"@sveltejs/kit/hooks\";\nimport { Effect, Exit } from \"effect\";\nimport { causeToThrowable } from \"../internal/error.js\";\n\n/** Run a bare Effect (no request context) and settle it the way a hook expects. */\nconst runBareHook = async <A>(effect: Effect.Effect<A, unknown>): Promise<A> =>\n Exit.match(await Effect.runPromiseExit(effect), {\n onFailure: (cause) => {\n throw causeToThrowable(cause);\n },\n onSuccess: (value) => value,\n });\n\n/**\n * Wraps an Effect-based function as the SvelteKit client\n * [`handleError`](https://svelte.dev/docs/kit/hooks#Shared-hooks-handleError)\n * hook, which runs when an unexpected error is thrown while navigating in the\n * browser. The effect receives the error and navigation event and produces the\n * shape exposed to the page (your `App.Error`, or nothing).\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const handleError = Hooks.handleError(({ error, event }) =>\n * Effect.gen(function* () {\n * yield* Effect.logError(`navigation to ${event.url.pathname} failed`, error);\n * return { message: 'Something went wrong' };\n * })\n * );\n * ```\n */\nexport function handleError(\n fn: (\n args: Parameters<HandleClientError>[0],\n ) => Effect.Effect<Awaited<ReturnType<HandleClientError>>, unknown>,\n): HandleClientError {\n return (args) => runBareHook(fn(args));\n}\n\n/**\n * Wraps an Effect as the SvelteKit client\n * [`init`](https://svelte.dev/docs/kit/hooks#Shared-hooks-init) hook, which\n * runs once when the app starts in the browser. The effect runs on a bare\n * Effect runtime.\n *\n * @example\n * ```ts\n * // src/hooks.client.ts\n * import { Hooks } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * export const init = Hooks.init(Effect.logInfo('client app started'));\n * ```\n */\nexport function init(effect: Effect.Effect<void, unknown>): ClientInit {\n return () => runBareHook(effect);\n}\n"],"mappings":";;;;;;;;;AA6BA,MAAM,cAAc,OAAU,WAC5B,KAAK,MAAM,MAAM,OAAO,eAAe,MAAM,GAAG;CAC9C,YAAY,UAAU;EACpB,MAAM,iBAAiB,KAAK;CAC9B;CACA,YAAY,UAAU;AACxB,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBH,SAAgB,YACd,IAGmB;CACnB,QAAQ,SAAS,YAAY,GAAG,IAAI,CAAC;AACvC;;;;;;;;;;;;;;;;AAiBA,SAAgB,KAAK,QAAkD;CACrE,aAAa,YAAY,MAAM;AACjC"}
|
package/dist/errors.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { throwKitError } from "./internal/error.js";
|
|
2
3
|
import { SvelteKit } from "./kit.js";
|
|
3
4
|
import { Cause, Predicate } from "effect";
|
|
4
|
-
import {
|
|
5
|
+
import { redirect } from "@sveltejs/kit";
|
|
5
6
|
//#region src/errors.ts
|
|
6
7
|
/**
|
|
7
8
|
* A `translateError` built from a **tagged-error catalogue** instead of a
|
|
@@ -68,7 +69,7 @@ const isErrorStatus = (status) => Predicate.isNumber(status) && Number.isInteger
|
|
|
68
69
|
const isRedirectStatus = (status) => Predicate.isNumber(status) && Number.isInteger(status) && status >= 300 && status <= 308;
|
|
69
70
|
/** The error's own non-empty `message` field, else its `_tag`. */
|
|
70
71
|
const defaultBody = (error) => Object.hasOwn(error, "message") && Predicate.isString(error.message) && error.message !== "" ? error.message : error._tag;
|
|
71
|
-
const throwError = (status, body) =>
|
|
72
|
+
const throwError = (status, body) => throwKitError(status, body);
|
|
72
73
|
const apply = (entry, error) => {
|
|
73
74
|
if (Predicate.isNumber(entry)) return throwError(entry, defaultBody(error));
|
|
74
75
|
if (Predicate.isFunction(entry)) return entry(error);
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["
|
|
1
|
+
{"version":3,"file":"errors.js","names":["kitRedirect"],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * A `translateError` built from a **tagged-error catalogue** instead of a\n * hand-written switch.\n *\n * Every application maps the same handful of domain errors to SvelteKit control\n * flow at the request boundary — `NotFound → error(404)`, `Forbidden → 403`,\n * `Unauthorized → 401`, `Redirect → redirect()`, the catch-all HTTP error →\n * `error(status)` — and re-throws everything else so `handleError` sees the\n * defect. {@link toSvelteKit} takes that mapping as data, keyed by `_tag`, and\n * returns the {@link KitErrorTranslator} that `makeRuntimeAdapter` /\n * `RemoteFunction.withRuntime` accept.\n *\n * @example\n * ```ts\n * // src/lib/server/effect/kit.ts\n * import { Errors, makeRuntimeAdapter, RequestRuntime } from \"@thomasfosterau/effect-sveltekit/server\";\n * import { Layer, Schema } from \"effect\";\n *\n * // The application's tagged-error catalogue (usually imported from a shared models package).\n * class NotFound extends Schema.TaggedError<NotFound>()(\"NotFound\", {\n * resource: Schema.String,\n * id: Schema.String,\n * }) {}\n * class Forbidden extends Schema.TaggedError<Forbidden>()(\"Forbidden\", {\n * message: Schema.optional(Schema.String),\n * }) {}\n * class Redirect extends Schema.TaggedError<Redirect>()(\"Redirect\", {\n * to: Schema.String,\n * status: Schema.Number,\n * }) {}\n * class HttpError extends Schema.TaggedError<HttpError>()(\"HttpError\", {\n * status: Schema.Number,\n * message: Schema.String,\n * }) {}\n *\n * type AppError = NotFound | Forbidden | Redirect | HttpError;\n *\n * // Apps typically use `RequestRuntime.fromLocals((event) => event.locals.runtime)`.\n * const AppLayer = Layer.empty;\n *\n * export const { serverLoad, endpoint } = makeRuntimeAdapter(RequestRuntime.fromLayer(AppLayer), {\n * translateError: Errors.toSvelteKit<AppError>({\n * NotFound: { status: 404, message: (e) => `${e.resource} ${e.id} not found` },\n * Forbidden: 403, // body: the error's own `message`, else \"Forbidden\"\n * Redirect: \"redirect\", // redirect(e.status, e.to)\n * HttpError: \"status\", // error(e.status, e.message)\n * }),\n * });\n * ```\n *\n * @module\n */\n\nimport { redirect as kitRedirect } from \"@sveltejs/kit\";\nimport { Cause, Predicate } from \"effect\";\nimport { throwKitError } from \"./internal/error.js\";\nimport { SvelteKit, type KitErrorTranslator } from \"./kit.js\";\n\n/** Any value carrying a string `_tag` — `Schema.TaggedError`, `Data.TaggedError`, … */\nexport interface Tagged {\n readonly _tag: string;\n}\n\n/** An error `_tag` with arbitrary fields: the element type of an untyped catalogue. */\nexport type AnyTagged = Tagged & { readonly [field: string]: any };\n\n/** A 4xx / 5xx status for SvelteKit's `error()`. */\nexport type ErrorStatus = number;\n\n/**\n * How one tag is translated.\n *\n * - `404` (a status) — `error(status, body)`. The body is the error's own\n * non-empty `message` field, else its `_tag`.\n * - `{ status, message }` — `error(status, message(e))`; `message` may return a\n * string or an `App.Error` object.\n * - `\"status\"` — `error(e.status, body)`, for a catch-all error that carries its\n * own status (a non-4xx/5xx status becomes `500`).\n * - `\"redirect\"` — `redirect(e.status, e.to ?? e.location)`; a missing or\n * non-3xx status becomes `303`.\n * - a function — full control: throw any SvelteKit primitive (`error`,\n * `redirect`, `invalid`, …) or anything else.\n */\nexport type CatalogueEntry<E> =\n | ErrorStatus\n | {\n readonly status: ErrorStatus;\n readonly message?: ((error: E) => string | App.Error) | undefined;\n }\n | \"status\"\n | \"redirect\"\n | ((error: E) => never);\n\n/**\n * A tag-keyed catalogue. With an explicit error union `E`, keys are limited to\n * `E`'s tags and each entry's functions receive the matching member.\n */\nexport type Catalogue<E extends Tagged> = {\n readonly [K in E[\"_tag\"]]?: CatalogueEntry<Extract<E, { readonly _tag: K }>>;\n};\n\n/** Options for {@link toSvelteKit}. */\nexport interface ToSvelteKitOptions {\n /**\n * What to do with a cause whose error is not in the catalogue. Defaults to\n * {@link SvelteKit.translate}: the Kit control-flow errors\n * (`SvelteKit.redirect` / `.error` / `.fail`) and SvelteKit's own thrown\n * `redirect()` / `error()` pass through, anything else becomes an\n * `EffectCauseError` (a 500 whose `cause` is the full Effect `Cause`).\n *\n * Pass {@link rethrowSquashed} to rethrow the squashed error unchanged\n * instead, so `handleError` sees the original value.\n */\n readonly fallback?: KitErrorTranslator | undefined;\n}\n\n/** A {@link ToSvelteKitOptions.fallback} that rethrows `Cause.squash(cause)` unchanged. */\nexport const rethrowSquashed: KitErrorTranslator = (cause) => {\n throw Cause.squash(cause);\n};\n\nconst isTagged = (value: unknown): value is AnyTagged =>\n Predicate.hasProperty(value, \"_tag\") && Predicate.isString(value._tag);\n\nconst isErrorStatus = (status: unknown): status is number =>\n Predicate.isNumber(status) && Number.isInteger(status) && status >= 400 && status <= 599;\n\nconst isRedirectStatus = (\n status: unknown,\n): status is 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 =>\n Predicate.isNumber(status) && Number.isInteger(status) && status >= 300 && status <= 308;\n\n/** The error's own non-empty `message` field, else its `_tag`. */\nconst defaultBody = (error: AnyTagged): string =>\n Object.hasOwn(error, \"message\") && Predicate.isString(error.message) && error.message !== \"\"\n ? error.message\n : error._tag;\n\nconst throwError = (status: number, body: string | App.Error): never =>\n throwKitError(status, body as string | Readonly<Record<string, unknown>>);\n\nconst apply = (entry: CatalogueEntry<AnyTagged>, error: AnyTagged): never => {\n if (Predicate.isNumber(entry)) return throwError(entry, defaultBody(error));\n if (Predicate.isFunction(entry)) return entry(error);\n if (entry === \"status\") {\n return throwError(isErrorStatus(error.status) ? error.status : 500, defaultBody(error));\n }\n if (entry === \"redirect\") {\n const location: unknown = error.to ?? error.location;\n return kitRedirect(\n isRedirectStatus(error.status) ? error.status : 303,\n Predicate.isString(location) || location instanceof URL ? location : \"/\",\n );\n }\n return throwError(\n entry.status,\n entry.message === undefined ? defaultBody(error) : entry.message(error),\n );\n};\n\n/**\n * Build a `translateError` from a tag-keyed catalogue.\n *\n * The translator squashes the failed `Cause` (the first typed failure, else the\n * first defect — so a tagged error that was thrown also matches), looks its\n * `_tag` up in `catalogue`, and throws the matching SvelteKit primitive. Errors\n * outside the catalogue go to `options.fallback` (by default\n * {@link SvelteKit.translate}).\n *\n * Pass the application's error union as the type argument to have the keys and\n * each entry's callbacks checked against it; without it the catalogue is\n * untyped (`Record<string, CatalogueEntry<AnyTagged>>`).\n *\n * @example\n * ```ts\n * import { Errors } from \"@thomasfosterau/effect-sveltekit/server\";\n * import { error } from \"@sveltejs/kit\";\n *\n * const translateError = Errors.toSvelteKit({\n * NotFound: 404,\n * Unauthorized: 401,\n * Forbidden: 403,\n * Redirect: \"redirect\",\n * HttpError: \"status\",\n * // Full control for anything bespoke, e.g. a JSON:API error document:\n * JsonapiError: (e) => error(e.status, JSON.stringify(e.toDocument())),\n * });\n * ```\n */\nexport const toSvelteKit = <E extends Tagged = AnyTagged>(\n catalogue: Catalogue<E>,\n options: ToSvelteKitOptions = {},\n): KitErrorTranslator => {\n const entries = catalogue as Readonly<Record<string, CatalogueEntry<AnyTagged> | undefined>>;\n const fallback = options.fallback ?? SvelteKit.translate;\n return (cause) => {\n const squashed = Cause.squash(cause);\n if (isTagged(squashed) && Object.hasOwn(entries, squashed._tag)) {\n const entry = entries[squashed._tag];\n if (entry !== undefined) return apply(entry, squashed);\n }\n return fallback(cause);\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHA,MAAa,mBAAuC,UAAU;CAC5D,MAAM,MAAM,OAAO,KAAK;AAC1B;AAEA,MAAM,YAAY,UAChB,UAAU,YAAY,OAAO,MAAM,KAAK,UAAU,SAAS,MAAM,IAAI;AAEvE,MAAM,iBAAiB,WACrB,UAAU,SAAS,MAAM,KAAK,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU;AAEvF,MAAM,oBACJ,WAEA,UAAU,SAAS,MAAM,KAAK,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU;;AAGvF,MAAM,eAAe,UACnB,OAAO,OAAO,OAAO,SAAS,KAAK,UAAU,SAAS,MAAM,OAAO,KAAK,MAAM,YAAY,KACtF,MAAM,UACN,MAAM;AAEZ,MAAM,cAAc,QAAgB,SAClC,cAAc,QAAQ,IAAkD;AAE1E,MAAM,SAAS,OAAkC,UAA4B;CAC3E,IAAI,UAAU,SAAS,KAAK,GAAG,OAAO,WAAW,OAAO,YAAY,KAAK,CAAC;CAC1E,IAAI,UAAU,WAAW,KAAK,GAAG,OAAO,MAAM,KAAK;CACnD,IAAI,UAAU,UACZ,OAAO,WAAW,cAAc,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK,YAAY,KAAK,CAAC;CAExF,IAAI,UAAU,YAAY;EACxB,MAAM,WAAoB,MAAM,MAAM,MAAM;EAC5C,OAAOA,SACL,iBAAiB,MAAM,MAAM,IAAI,MAAM,SAAS,KAChD,UAAU,SAAS,QAAQ,KAAK,oBAAoB,MAAM,WAAW,GACvE;CACF;CACA,OAAO,WACL,MAAM,QACN,MAAM,YAAY,KAAA,IAAY,YAAY,KAAK,IAAI,MAAM,QAAQ,KAAK,CACxE;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eACX,WACA,UAA8B,CAAC,MACR;CACvB,MAAM,UAAU;CAChB,MAAM,WAAW,QAAQ,YAAY,UAAU;CAC/C,QAAQ,UAAU;EAChB,MAAM,WAAW,MAAM,OAAO,KAAK;EACnC,IAAI,SAAS,QAAQ,KAAK,OAAO,OAAO,SAAS,SAAS,IAAI,GAAG;GAC/D,MAAM,QAAQ,QAAQ,SAAS;GAC/B,IAAI,UAAU,KAAA,GAAW,OAAO,MAAM,OAAO,QAAQ;EACvD;EACA,OAAO,SAAS,KAAK;CACvB;AACF"}
|
package/dist/forms.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { EnhanceHandlers, EnhanceOptions, EnhanceRuntime, ResultOptions, SubmitInput } from "./internal/enhance.js";
|
|
2
2
|
import "./forms.js";
|
|
3
3
|
import { Effect } from "effect";
|
|
4
|
-
import { ActionResult } from "
|
|
4
|
+
import { ActionResult } from "$app/forms";
|
|
5
5
|
declare namespace forms_d_exports {
|
|
6
|
-
export { EnhanceHandlers, EnhanceOptions, EnhanceRuntime, ResultOptions, SubmitInput, applyAction, deserialize, enhance };
|
|
6
|
+
export { EnhanceHandlers, EnhanceOptions, EnhanceRuntime, ResultOptions, SubmitInput, applyAction$1 as applyAction, deserialize$1 as deserialize, enhance };
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
9
|
* Build a `SubmitFunction` for `use:enhance` from Effect-based handlers.
|
|
@@ -13,17 +13,17 @@ declare namespace forms_d_exports {
|
|
|
13
13
|
* to keep SvelteKit's default behaviour. Pass `{ runtime }` when the handlers
|
|
14
14
|
* require application services.
|
|
15
15
|
*/
|
|
16
|
-
declare const enhance: <R = never>(handlers: EnhanceHandlers<R>, options?: EnhanceOptions<R>) => import("
|
|
16
|
+
declare const enhance: <R = never>(handlers: EnhanceHandlers<R>, options?: EnhanceOptions<R>) => import("$app/forms").SubmitFunction;
|
|
17
17
|
/**
|
|
18
18
|
* Apply an `ActionResult` to the page (updating `page.form` / `page.status`,
|
|
19
19
|
* resetting the form, etc.) as an Effect. Wraps `$app/forms`' `applyAction`.
|
|
20
20
|
*/
|
|
21
|
-
declare const applyAction: <Success extends Record<string, unknown> | undefined = Record<string, unknown>, Failure extends Record<string, unknown> | undefined = Record<string, unknown>>(result: ActionResult<Success, Failure>) => Effect.Effect<void>;
|
|
21
|
+
declare const applyAction$1: <Success extends Record<string, unknown> | undefined = Record<string, unknown>, Failure extends Record<string, unknown> | undefined = Record<string, unknown>>(result: ActionResult<Success, Failure>) => Effect.Effect<void>;
|
|
22
22
|
/**
|
|
23
23
|
* Deserialize a raw form-action response body into an `ActionResult`, as an
|
|
24
24
|
* Effect. Wraps `$app/forms`' `deserialize`; a malformed body fails the effect.
|
|
25
25
|
*/
|
|
26
|
-
declare const deserialize: <Success extends Record<string, unknown> | undefined = Record<string, unknown>, Failure extends Record<string, unknown> | undefined = Record<string, unknown>>(result: string) => Effect.Effect<ActionResult<Success, Failure>, unknown>;
|
|
26
|
+
declare const deserialize$1: <Success extends Record<string, unknown> | undefined = Record<string, unknown>, Failure extends Record<string, unknown> | undefined = Record<string, unknown>>(result: string) => Effect.Effect<ActionResult<Success, Failure>, unknown>;
|
|
27
27
|
//#endregion
|
|
28
|
-
export { type EnhanceHandlers, type EnhanceOptions, type EnhanceRuntime, type ResultOptions, type SubmitInput, applyAction, deserialize, enhance, forms_d_exports };
|
|
28
|
+
export { type EnhanceHandlers, type EnhanceOptions, type EnhanceRuntime, type ResultOptions, type SubmitInput, applyAction$1 as applyAction, deserialize$1 as deserialize, enhance, forms_d_exports };
|
|
29
29
|
//# sourceMappingURL=forms.d.ts.map
|
package/dist/forms.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forms.js","names":["applyAction","kitApplyAction","deserialize","kitDeserialize"],"sources":["../src/forms.ts"],"sourcesContent":["/**\n * Effect bridge for SvelteKit's native form actions\n * ([`$app/forms`](https://svelte.dev/docs/kit/$app-forms)) — the `Forms`\n * namespace of `@thomasfosterau/effect-sveltekit/client`.\n *\n * This complements `Remote.submitForm` (which covers *remote* forms): here the\n * progressive-enhancement `use:enhance` flow for page `actions` is expressed\n * with Effects, and `applyAction` / `deserialize` are wrapped so a hand-rolled\n * `fetch` submission can be finished off inside an Effect pipeline.\n *\n * @example\n * ```svelte\n * <script lang=\"ts\">\n * import { enhance } from '$app/forms';\n * import { Forms } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * const submit = Forms.enhance({\n * onSubmit: () => Effect.sync(() => { saving = true; }),\n * onResult: ({ result, update }) =>\n * Effect.gen(function* () {\n * yield* Effect.promise(() => update());\n * saving = false;\n * }),\n * });\n * </script>\n *\n * <form method=\"POST\" use:enhance={submit}>...</form>\n * ```\n */\n\nimport { applyAction as kitApplyAction, deserialize as kitDeserialize } from \"$app/forms\";\nimport type { ActionResult } from \"
|
|
1
|
+
{"version":3,"file":"forms.js","names":["applyAction","kitApplyAction","deserialize","kitDeserialize"],"sources":["../src/forms.ts"],"sourcesContent":["/**\n * Effect bridge for SvelteKit's native form actions\n * ([`$app/forms`](https://svelte.dev/docs/kit/$app-forms)) — the `Forms`\n * namespace of `@thomasfosterau/effect-sveltekit/client`.\n *\n * This complements `Remote.submitForm` (which covers *remote* forms): here the\n * progressive-enhancement `use:enhance` flow for page `actions` is expressed\n * with Effects, and `applyAction` / `deserialize` are wrapped so a hand-rolled\n * `fetch` submission can be finished off inside an Effect pipeline.\n *\n * @example\n * ```svelte\n * <script lang=\"ts\">\n * import { enhance } from '$app/forms';\n * import { Forms } from '@thomasfosterau/effect-sveltekit/client';\n * import { Effect } from 'effect';\n *\n * const submit = Forms.enhance({\n * onSubmit: () => Effect.sync(() => { saving = true; }),\n * onResult: ({ result, update }) =>\n * Effect.gen(function* () {\n * yield* Effect.promise(() => update());\n * saving = false;\n * }),\n * });\n * </script>\n *\n * <form method=\"POST\" use:enhance={submit}>...</form>\n * ```\n */\n\nimport { applyAction as kitApplyAction, deserialize as kitDeserialize } from \"$app/forms\";\nimport type { ActionResult } from \"$app/forms\";\nimport { Effect } from \"effect\";\nimport { makeSubmitFunction } from \"./internal/enhance.js\";\n\nexport type {\n EnhanceHandlers,\n EnhanceOptions,\n EnhanceRuntime,\n SubmitInput,\n ResultOptions,\n} from \"./internal/enhance.js\";\n\n/**\n * Build a `SubmitFunction` for `use:enhance` from Effect-based handlers.\n *\n * `onSubmit` runs before the request (call `input.cancel()` to abort);\n * `onResult` runs on the response with SvelteKit's `update()`. Omit `onResult`\n * to keep SvelteKit's default behaviour. Pass `{ runtime }` when the handlers\n * require application services.\n */\nexport const enhance = makeSubmitFunction;\n\n/**\n * Apply an `ActionResult` to the page (updating `page.form` / `page.status`,\n * resetting the form, etc.) as an Effect. Wraps `$app/forms`' `applyAction`.\n */\nexport const applyAction = <\n Success extends Record<string, unknown> | undefined = Record<string, unknown>,\n Failure extends Record<string, unknown> | undefined = Record<string, unknown>,\n>(\n result: ActionResult<Success, Failure>,\n): Effect.Effect<void> => Effect.promise(() => kitApplyAction(result));\n\n/**\n * Deserialize a raw form-action response body into an `ActionResult`, as an\n * Effect. Wraps `$app/forms`' `deserialize`; a malformed body fails the effect.\n */\nexport const deserialize = <\n Success extends Record<string, unknown> | undefined = Record<string, unknown>,\n Failure extends Record<string, unknown> | undefined = Record<string, unknown>,\n>(\n result: string,\n): Effect.Effect<ActionResult<Success, Failure>, unknown> =>\n Effect.try({\n try: () => kitDeserialize<Success, Failure>(result),\n catch: (error) => error,\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAa,UAAU;;;;;AAMvB,MAAaA,iBAIX,WACwB,OAAO,cAAcC,YAAe,MAAM,CAAC;;;;;AAMrE,MAAaC,iBAIX,WAEA,OAAO,IAAI;CACT,WAAWC,YAAiC,MAAM;CAClD,QAAQ,UAAU;AACpB,CAAC"}
|
|
@@ -22,7 +22,7 @@ interface PageSnapshot<P extends ReadonlyPage = ReadonlyPage> {
|
|
|
22
22
|
* `PageSnapshot<P>` recovers the precise field types from `P`.
|
|
23
23
|
*/
|
|
24
24
|
interface ReadonlyPage {
|
|
25
|
-
readonly url: URL
|
|
25
|
+
readonly url: Readonly<Omit<URL, "searchParams">>;
|
|
26
26
|
readonly params: Record<string, string | undefined>;
|
|
27
27
|
readonly route: {
|
|
28
28
|
readonly id: string | null;
|
|
@@ -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 `page` can't be unit-tested directly because importing it\n * pulls in `$app/navigation` and `$app/state` (SvelteKit virtual modules that\n * only exist inside a build). The snapshotting and the \"emit now, then after\n * each navigation\" plumbing live here instead, parameterised over the\n * navigation registrar and a `readPage` thunk, so they can be driven with\n * stand-ins in tests while the public wrapper stays a thin pass-through.\n *\n * @internal\n */\n\nimport { Effect, 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}\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 readonly url: URL
|
|
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 `page` can't be unit-tested directly because importing it\n * pulls in `$app/navigation` and `$app/state` (SvelteKit virtual modules that\n * only exist inside a build). The snapshotting and the \"emit now, then after\n * each navigation\" plumbing live here instead, parameterised over the\n * navigation registrar and a `readPage` thunk, so they can be driven with\n * stand-ins in tests while the public wrapper stays a thin pass-through.\n *\n * @internal\n */\n\nimport { Effect, 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}\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}\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 };\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0DA,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;CACb;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"}
|
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>;
|