# svetch.ts

> End-to-End typesafe fetch client for your API

Latest version **2.1.46** (published 2024-09-08) · MIT license · 0 weekly downloads

## Install

```sh
npm install svetch.ts
pnpm add svetch.ts
yarn add svetch.ts
bun add svetch.ts
```

Provides the command `svetch.ts`.

## Health

**Score 35/100 (D)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 2.1.46 |
| Published | 2024-09-08 |
| First published | 2023-07-17 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 6 |
| Unpacked size | 384.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 73 |
| Author | Omar Al Matar |
| Maintainers | bewinxed |
| Keywords | svelte, sveltekit, typescript, fetch, typesafe, svetch.ts, openapi, swagger |

## Links

- npm: https://www.npmjs.com/package/svetch.ts
- Repository: https://github.com/Bewinxed/svetch
- Homepage: https://github.com/Bewinxed/svetch#readme
- Issues: https://github.com/Bewinxed/svetch/issues
- Funding: https://petrasolutions.lemonsqueezy.com/checkout/buy/19210e05-ae3c-41a0-920c-324e3083618d
- npm.io page: https://npm.io/package/svetch.ts

## Dependencies (6)

- [ora](https://npm.io/package/ora.md) ^8.1.0
- [tsoa](https://npm.io/package/tsoa.md) ^6.4.0
- [prompts](https://npm.io/package/prompts.md) ^2.4.2
- [ts-morph](https://npm.io/package/ts-morph.md) ^23.0.0
- [ansi-colors](https://npm.io/package/ansi-colors.md) ^4.1.3
- [comment-parser](https://npm.io/package/comment-parser.md) ^1.4.1

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 2.1.46 (latest) — 2024-09-08
- 2.1.45 — 2024-09-08
- 2.1.44 — 2024-09-08
- 2.1.43 — 2024-09-04
- 2.1.42 — 2024-09-03
- 2.1.41 — 2024-09-02
- 2.1.40 — 2024-08-30
- 2.1.39 — 2024-08-29
- 2.1.37 — 2024-08-20
- 2.1.36 — 2024-08-20
- 2.1.35 — 2024-08-20
- 2.1.34 — 2024-08-20
- 2.1.33 — 2024-08-20
- 2.1.32 — 2024-08-06
- 2.1.31 — 2024-08-02
- … 157 more at https://npm.io/package/svetch.ts/versions

## README

[![npm](https://img.shields.io/npm/v/svetch.ts)](https://www.npmjs.com/package/svetch.ts)
![svetch-chan (1)](https://github.com/Bewinxed/svetch/assets/9145989/67c36f21-a21e-42f1-ba50-42f457948c46)

# 🚀 Svetch.ts: Zero-Effort client/types/schema/OpenAPI Schema/Docs generator for your API endpoints

_Typesafety, Minus the typing_

👉 Check it out @ (https://svetch-dev.vercel.app/)
Effortlessly generate a typesafe Fetch client for your Svelte/Sveltekit applications, complete with automatic input/output zod validation and autogenerated types & API Docs.

# What is this?

Svetch automatically scans your `+server.ts` files in /src/routes/api (or whatever directory you specify) and generates a typesafe Fetch client that has intellisense for path, query, body parameters & all the possible responses (and errors)

# 🧙‍♂️ Automatic Detection

- ❓ **Query Params** => Detected using any declarations of `url.searchParams.get`
- 📂 **Path Params** => Detected from the file directory
- 📦 **Payload Definition** => inferred from `const payload: X = await request.json` or `as X`
- 💬 **Response Definition** => inferred from any return statement with `json(X) (sveltekit utility)` or `new Response(X)`
- 📛 **Error Definitions** => inferred from any throw statement with `throw error()` or `throw new Error` or `return error(HTTP_CODE, error_message)`

# ⏬ How to run

`$ npx svetch.ts@latest`

### Make sure you have a path alias for src in your `svelte.config.js`

```diff
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	// Consult https://kit.svelte.dev/docs/integrations#preprocessors
	// for more information about preprocessors
	preprocess: vitePreprocess(),
	kit: {
		// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
		// If your environment is not supported or you settled on a specific environment, switch out the adapter.
		// See https://kit.svelte.dev/docs/adapters for more information about adapters.
		adapter: adapter(),
+		alias: {
+			"src": "./src",
		},
	}
};

export default config;

```

# 🌟 Advantages

- 😍 **ALMOST** no code changes required to your existing API code
- 🚀 Almost no learning curve, Augments a regular FETCH client with **data** and **error** along with the rest of the fetch client properties, you can use it just like a regular fetch client.
- 🔎 **Intellisense** for your api paths.
- ✅ Typesafety for api inputs & outputs.
- 📚 Generates an OpenAPI Schema for your API, alongside with Swagger docs.
- 📃 Can use **JSDocs** to add more info to the endpoint documentation (WIP)
- 🤖 Handles multiple possible responses per http code.

## Autogenerated Docs

The library will generate an OpenAPI compatible schema, alongside with swagger docs, by default in /docs/+page.svelte

# ⚙ Config

`.svetchrc`

```json
{
  "framework": "sveltekit", // currently the only option
  "input": "src/routes/api", // the directory you want the generator to traverse
  "out": "src/lib/api", // the directory to output the types & the client to
  "docs": "src/routes/docs", // where to output docs
  "tsconfig": "tsconfig.json" // your tsconfig directory
}
```

# 🔎 Detection

1. Svetch will traverse your input directory, will scan for any +server.ts with exported GET/POST/PUT/DELETE functions.
2. For each endpoint it will detect...
   1. **path parameters**: based on the file name, e.g. `user/[user_id].ts` will have a path parameter of `user_id`
   2. **query parameters**: based on any parameters instantiated like `url.searchParams.get('param')`
   3. **body parameters**: based on the type of the payload `Must be assigned to a const called` **payload** **⚠ IMPORTANT**
   4. **response types**: will pickup any top-level return statement that is instantiated like **json(xxx)** or **new Response(xxx)** along with status code

## In client code

```ts
import { Svetch } from "src/lib/api/client"; // or wherever you chose to generate the client

const svetch = new Svetch({
  baseUrl: "/api", // default is '/api'
  fetch, // default is window.fetch, pass the global fetch to it in node, etc...
  validate: false, // default is false, uses Zod to validate payload + response (ON CLIENT THIS CAN MAKE THE IMPORT SIZE HUGE)
});

await svetch
  .post("user/[user_id]", {
    path: {
      user_id: 1,
    },
    body: {
      text: foodInput,
      journalId: $journal.id,
      today: new Date(),
    },
  })
  .then((response) => {
    if (response.error) throw new Error(response.error);
    food = response.data;
    loading = false;
  })
  .catch((error) => {
    throw new Error(error);
  });
```

## In load functions

```ts
import { Svetch } from "src/lib/api/client"; // or wherever you chose to generate the client

const svetch = new Svetch({
  baseUrl: "/api", // default is '/api'
  fetch, // pass the load function's fetch to it
});

export async function load({ fetch, session }) {
  const user = await svetch.get("user").then((response) => {
    if (response.error) throw new Error(response.error);
    return response.data;
  });
  return {
    props: {
      user,
    },
  };
}
```

# License

This library is **Free** for personal use, If it's useful to you, please consider purchasing a license @ https://petrasolutions.lemonsqueezy.com/checkout/buy/19210e05-ae3c-41a0-920c-324e3083618d
Redistribution/Forking is **Not** Allowed.

---
_Source: https://npm.io/package/svetch.ts · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
