@hyper-fetch/elysia 0.0.0-stage → 9.8.1

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 CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
1
+ # ðŸĶŠ Hyper Fetch Elysia
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <b>Call your Elysia backend from a fully typed HyperFetch SDK. No codegen, no duplicated types.</b>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/BetterTyped/hyper-fetch">
9
+ <img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?logo=github&color=118ab2" alt="GitHub stars" />
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@hyper-fetch/elysia">
12
+ <img src="https://img.shields.io/npm/v/@hyper-fetch/elysia?logo=npm&color=e76f51" alt="npm version" />
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@hyper-fetch/elysia">
15
+ <img src="https://img.shields.io/npm/dm/@hyper-fetch/elysia?logo=npm" alt="npm downloads" />
16
+ </a>
17
+ <a href="https://bundlephobia.com/package/@hyper-fetch/elysia">
18
+ <img src="https://img.shields.io/bundlephobia/minzip/@hyper-fetch/elysia?color=64BC4B" alt="bundle size" />
19
+ </a>
20
+ <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
21
+ <img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=yellow" alt="license" />
22
+ </a>
23
+ <a href="https://github.com/BetterTyped/hyper-fetch">
24
+ <img src="https://img.shields.io/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" alt="TypeScript" />
25
+ </a>
26
+ <a href="https://elysiajs.com/">
27
+ <img src="https://img.shields.io/badge/elysia-8A2BE2" alt="Elysia" />
28
+ </a>
29
+ </p>
30
+
31
+ ## 📖 About
32
+
33
+ `@hyper-fetch/elysia` turns the type of an Elysia app into a HyperFetch SDK schema. Your frontend calls the backend
34
+ through `createSdk` with response, error, payload, query and param types read straight from your Elysia routes and
35
+ schemas. It ships types only, so nothing from your server ends up in the client bundle.
36
+
37
+ ## ðŸŽŊ Key Capabilities
38
+
39
+ - 🔗 **Backend types, frontend calls** - Change an Elysia route and every SDK call that uses it fails to compile
40
+ - 🧭 **Paths become properties** - `/users/:userId/posts` is `sdk.users.$userId.posts.$get`, with typed `setParams()`
41
+ - 🛂 **Schemas drive the inputs** - `body` and `query` schemas type `setPayload()` and `setQueryParams()`
42
+ - ðŸšĶ **Typed errors per status** - 2xx bodies type `data`, every other status, including `422` validation errors, types
43
+ `error`
44
+ - ðŸ“Ą **Types match the wire** - Dates arrive as strings, file bodies are `FormData`, and streams stay `unknown`
45
+ - ðŸ§Đ **Plugins included** - `prefix`, `.group()`, `.guard()`, `.model()` and macros land in the endpoint and the types
46
+ - ðŸŠķ **Zero runtime** - A single type export, so it adds no code to your bundle
47
+ - ⚡ **Every HyperFetch feature** - Cache, retries, deduplication, offline and React hooks work on every route
48
+
49
+ ## 🚀 Quick Start
50
+
51
+ ```bash
52
+ npm install @hyper-fetch/core @hyper-fetch/elysia
53
+ ```
54
+
55
+ ```ts
56
+ // backend
57
+ import { Elysia } from "elysia";
58
+ import type { ElysiaAppToHyperFetch } from "@hyper-fetch/elysia";
59
+
60
+ const app = new Elysia().get("/users/:userId", ({ params }) => ({ id: params.userId, name: "Ann" }));
61
+
62
+ export type AppSchema = ElysiaAppToHyperFetch<typeof app>;
63
+ ```
64
+
65
+ ```ts
66
+ // frontend
67
+ import { createClient, createSdk } from "@hyper-fetch/core";
68
+ import type { AppSchema } from "@my-app/backend";
69
+
70
+ const client = createClient({ url: "https://api.example.com" });
71
+ const sdk = createSdk<typeof client, AppSchema>(client);
72
+
73
+ const { data } = await sdk.users.$userId.$get.setParams({ userId: "1" }).send();
74
+ ```
75
+
76
+ ## 📚 Documentation
77
+
78
+ - [Elysia Integration Docs](https://hyperfetch.bettertyped.com/docs/integrations/elysia/overview)
79
+ - [SDK Guide](https://hyperfetch.bettertyped.com/docs/core/sdk)
80
+ - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
81
+
82
+ ## ðŸ’Ą Examples
83
+
84
+ ### Plugins with schemas and error statuses
85
+
86
+ ```ts
87
+ import { Elysia, t } from "elysia";
88
+ import type { ElysiaAppToHyperFetch } from "@hyper-fetch/elysia";
89
+
90
+ const users = new Elysia({ prefix: "/users" })
91
+ .post("/", ({ body, status }) => status(201, { id: "2", name: body.name }), {
92
+ body: t.Object({ name: t.String() }),
93
+ })
94
+ .get("/:userId", ({ params, status }) =>
95
+ params.userId === "missing" ? status(404, { message: "User not found" }) : { id: params.userId, name: "Ann" },
96
+ );
97
+
98
+ const auth = new Elysia({ prefix: "/auth" }).get("/google-login", () => ({ authUrl: "https://accounts.example.com" }));
99
+
100
+ const app = new Elysia().use(users).use(auth);
101
+
102
+ export type AppSchema = ElysiaAppToHyperFetch<typeof app>;
103
+ ```
104
+
105
+ ```ts
106
+ const sdk = createSdk<typeof client, AppSchema>(client);
107
+
108
+ await sdk.users.$post.setPayload({ name: "Bob" }).send();
109
+
110
+ const { data, error } = await sdk.users.$userId.$get.setParams({ userId: "missing" }).send();
111
+ // data: { id: string; name: string } | null, error: { message: "User not found" } | ...
112
+
113
+ // kebab-case paths become camelCase properties: GET /auth/google-login
114
+ await sdk.auth.googleLogin.$get.send();
115
+ ```
116
+
117
+ ### React hooks on an Elysia route
118
+
119
+ ```tsx
120
+ import { useFetch } from "@hyper-fetch/react";
121
+
122
+ import { sdk } from "./api";
123
+
124
+ export const UserName = ({ userId }: { userId: string }) => {
125
+ const { data, loading } = useFetch(sdk.users.$userId.$get.setParams({ userId }));
126
+
127
+ if (loading) return <p>Loading...</p>;
128
+ return <p>{data?.name}</p>;
129
+ };
130
+ ```
131
+
132
+ ## License
133
+
134
+ [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -0,0 +1,124 @@
1
+ import { createClient, createSdk } from "@hyper-fetch/core";
2
+ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
3
+
4
+ import { edgeApp } from "../__tests__/utils/edge-app";
5
+ import type { ElysiaAppToHyperFetch } from "../src";
6
+
7
+ type Schema = ElysiaAppToHyperFetch<typeof edgeApp>;
8
+
9
+ /**
10
+ * The cases whose wire format depends on the runtime: Bun serializes bodies, streams, redirects and
11
+ * multipart forms itself, so the types must match what arrives there as well as on Node.
12
+ */
13
+ describe("ElysiaAppToHyperFetch [ Edge cases against Elysia on Bun ]", () => {
14
+ let url: string;
15
+
16
+ const createAppSdk = () => {
17
+ const client = createClient({ url });
18
+ return createSdk<typeof client, Schema>(client);
19
+ };
20
+
21
+ beforeAll(() => {
22
+ edgeApp.listen(0);
23
+ const port = edgeApp.server?.port;
24
+ if (!port) {
25
+ throw new Error("Elysia did not start a Bun server");
26
+ }
27
+ url = `http://localhost:${port}`;
28
+ });
29
+
30
+ afterAll(async () => {
31
+ await edgeApp.stop();
32
+ });
33
+
34
+ it("should receive dates as ISO strings", async () => {
35
+ const { data } = await createAppSdk().date.$get.send();
36
+
37
+ expect(data).toStrictEqual({ date: "2026-01-02T03:04:05.000Z", history: ["1970-01-01T00:00:00.000Z"] });
38
+ });
39
+
40
+ it("should receive null as an empty body", async () => {
41
+ const { data, success } = await createAppSdk().null.$get.send();
42
+
43
+ expect(success).toBe(true);
44
+ expect(data).toBe("");
45
+ });
46
+
47
+ it("should resolve streamed and raw responses without failing", async () => {
48
+ const sdk = createAppSdk();
49
+
50
+ const responses = await Promise.all([
51
+ sdk.generator.$get.send(),
52
+ sdk.asyncGenerator.$get.send(),
53
+ sdk.sse.$get.send(),
54
+ sdk.response.$get.send(),
55
+ ]);
56
+
57
+ expect(responses.map(({ success }) => success)).toStrictEqual([true, true, true, true]);
58
+ expect(responses[3].data).toBe("raw text");
59
+ });
60
+
61
+ it("should follow a redirect to the target route", async () => {
62
+ const { data, status } = await createAppSdk().redirect.$get.send();
63
+
64
+ expect(status).toBe(200);
65
+ expect(data).toBe(1);
66
+ });
67
+
68
+ it("should resolve a status passed by name and the status a macro returns", async () => {
69
+ const sdk = createAppSdk();
70
+
71
+ const teapot = await sdk.teapot.$get.send();
72
+ const denied = await sdk.secret.$get.send();
73
+ const allowed = await sdk.secret.$get.setHeaders({ authorization: "Bearer token" }).send();
74
+
75
+ expect(teapot.status).toBe(418);
76
+ expect(teapot.error).toStrictEqual({ brewing: false });
77
+ expect(denied.error).toStrictEqual({ reason: "forbidden" });
78
+ expect(allowed.data).toStrictEqual({ userId: "1" });
79
+ });
80
+
81
+ it("should send a Date the body schema parses", async () => {
82
+ const { data } = await createAppSdk()
83
+ .dateBody.$post.setPayload({ date: new Date("2030-06-01T00:00:00.000Z") })
84
+ .send();
85
+
86
+ expect(data).toStrictEqual({ year: 2030 });
87
+ });
88
+
89
+ it("should upload files as FormData", async () => {
90
+ const form = new FormData();
91
+ form.append("title", "report");
92
+ form.append("file", new File(["12345"], "report.txt"));
93
+
94
+ const { data } = await createAppSdk().upload.$post.setPayload(form).send();
95
+
96
+ expect(data).toStrictEqual({ name: "report", size: 5 });
97
+ });
98
+
99
+ it("should send a Date and a number the query schema parses", async () => {
100
+ const { data } = await createAppSdk()
101
+ .queryTypes.$get.setQueryParams({ day: new Date("2026-03-04T00:00:00.000Z"), count: 3 })
102
+ .send();
103
+
104
+ expect(data).toStrictEqual({ day: "2026-03-04T00:00:00.000Z", count: 3, note: null });
105
+ });
106
+
107
+ it("should send an array query param with repeated keys", async () => {
108
+ const client = createClient({ url });
109
+ client.adapter.setQueryParamsMapperConfig({ arrayFormat: "none" });
110
+ const sdk = createSdk<typeof client, Schema>(client);
111
+
112
+ const { data } = await sdk.queryArray.$get.setQueryParams({ tags: ["a", "b"] }).send();
113
+
114
+ expect(data).toStrictEqual({ tags: ["a", "b"] });
115
+ });
116
+
117
+ it("should resolve an error a handler throws with its status", async () => {
118
+ const { error, status } = await createAppSdk().throws.$get.send();
119
+
120
+ expect(status).toBe(500);
121
+ // The default global error type is Error, while Elysia sends the thrown message as text
122
+ expect<unknown>(error).toBe("Unexpected failure");
123
+ });
124
+ });
@@ -0,0 +1,108 @@
1
+ import { createClient, createSdk } from "@hyper-fetch/core";
2
+ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
3
+
4
+ import { app } from "../__tests__/utils/app";
5
+ import type { ElysiaAppToHyperFetch } from "../src";
6
+
7
+ type Schema = ElysiaAppToHyperFetch<typeof app>;
8
+
9
+ /**
10
+ * Runs with `bun test`, so Elysia serves through `Bun.serve` and Hyper Fetch sends with the fetch
11
+ * of Bun. The vitest specs cover the same routes on Node.
12
+ */
13
+ describe("ElysiaAppToHyperFetch [ Requests against Elysia on Bun ]", () => {
14
+ let url: string;
15
+
16
+ const createAppSdk = () => {
17
+ const client = createClient({ url });
18
+ return createSdk<typeof client, Schema>(client);
19
+ };
20
+
21
+ beforeAll(() => {
22
+ app.listen(0);
23
+ const port = app.server?.port;
24
+ if (!port) {
25
+ throw new Error("Elysia did not start a Bun server");
26
+ }
27
+ url = `http://localhost:${port}`;
28
+ });
29
+
30
+ afterAll(async () => {
31
+ await app.stop();
32
+ });
33
+
34
+ it("should send a GET to a plugin route", async () => {
35
+ const sdk = createAppSdk();
36
+
37
+ const { data, error, status } = await sdk.users.$get.send();
38
+
39
+ expect(status).toBe(200);
40
+ expect(error).toBeNull();
41
+ expect(data).toStrictEqual([{ id: "1", name: "Ann" }]);
42
+ });
43
+
44
+ it("should fill :param segments from setParams", async () => {
45
+ const sdk = createAppSdk();
46
+
47
+ const { data } = await sdk.users.$userId.$get.setParams({ userId: "42" }).send();
48
+
49
+ expect(data).toStrictEqual({ id: "42", name: "Ann" });
50
+ });
51
+
52
+ it("should call a route with an optional param both without and with the param", async () => {
53
+ const sdk = createAppSdk();
54
+
55
+ const withoutParam = await sdk.files.$get.send();
56
+ const withParam = await sdk.files.$fileId.$get.setParams({ fileId: "report" }).send();
57
+
58
+ expect(withoutParam.data).toStrictEqual({ fileId: null });
59
+ expect(withParam.data).toStrictEqual({ fileId: "report" });
60
+ });
61
+
62
+ it("should send the payload as the JSON body the schema reads", async () => {
63
+ const sdk = createAppSdk();
64
+
65
+ const { data, status } = await sdk.users.$post.setPayload({ name: "Bob" }).send();
66
+
67
+ expect(status).toBe(201);
68
+ expect(data).toStrictEqual({ id: "2", name: "Bob" });
69
+ });
70
+
71
+ it("should send query params the schema reads", async () => {
72
+ const sdk = createAppSdk();
73
+
74
+ const { data } = await sdk.users.$userId.posts.$get.setParams({ userId: "7" }).setQueryParams({ page: "3" }).send();
75
+
76
+ expect(data).toStrictEqual({ userId: "7", page: "3" });
77
+ });
78
+
79
+ it("should send a custom method", async () => {
80
+ const sdk = createAppSdk();
81
+
82
+ const { data } = await sdk.dav.$propfind.send();
83
+
84
+ expect(data).toStrictEqual({ dav: true });
85
+ });
86
+
87
+ it("should resolve an error status through the response", async () => {
88
+ const sdk = createAppSdk();
89
+
90
+ const { data, error, status, success } = await sdk.users.$userId.$get.setParams({ userId: "missing" }).send();
91
+
92
+ expect(success).toBe(false);
93
+ expect(status).toBe(404);
94
+ expect(data).toBeNull();
95
+ expect(error).toStrictEqual({ message: "User not found" });
96
+ });
97
+
98
+ it("should resolve the validation error of a rejected body", async () => {
99
+ const client = createClient({ url });
100
+ const request = client.createRequest<{ payload: { name: number } }>()({ endpoint: "/users", method: "POST" });
101
+
102
+ const { error, status, success } = await request.setPayload({ name: 1 }).send();
103
+
104
+ expect(success).toBe(false);
105
+ expect(status).toBe(422);
106
+ expect(error).toMatchObject({ type: "validation", on: "body" });
107
+ });
108
+ });
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": true,
5
+ "rootDir": "..",
6
+ "types": ["bun"]
7
+ },
8
+ "include": ["**/*.ts"],
9
+ "exclude": ["node_modules"]
10
+ }