├── .changeset ├── README.md └── config.json ├── .eslintignore ├── .eslintrc.cjs ├── .gitattributes ├── .github ├── renovate.json └── workflows │ ├── release.yml │ └── test.yml ├── .gitignore ├── .husky ├── post-merge └── pre-commit ├── .npmrc ├── .prettierrc.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── pnpm-lock.yaml ├── src ├── api │ ├── async │ │ └── GET.ts │ ├── db.ts │ ├── group │ │ ├── GET.ts │ │ └── [param] │ │ │ └── GET.ts │ ├── index.ts │ └── post │ │ ├── GET.ts │ │ ├── POST.ts │ │ ├── [...id] │ │ ├── GET.ts │ │ └── PUT.ts │ │ └── search │ │ └── GET.ts ├── app.d.ts ├── app.html ├── lib │ ├── api.ts │ ├── error.ts │ ├── index.ts │ ├── log.ts │ ├── openapi.ts │ ├── utils.ts │ └── zod.ts └── routes │ ├── (group) │ └── api │ │ └── group │ │ ├── +server.ts │ │ └── [param] │ │ └── +server.ts │ ├── +page.svelte │ └── api │ ├── +server.ts │ ├── async │ └── +server.ts │ └── post │ ├── +server.ts │ ├── [...id] │ └── +server.ts │ └── search │ └── +server.ts ├── static └── favicon.png ├── svelte.config.js ├── tsconfig.json └── vite.config.ts /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", 3 | "changelog": ["@changesets/changelog-github", { "repo": "jacoblincool/sveltekit-api" }], 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build 4 | /.svelte-kit 5 | /package 6 | .env 7 | .env.* 8 | !.env.example 9 | 10 | # Ignore files for PNPM, NPM and YARN 11 | pnpm-lock.yaml 12 | package-lock.json 13 | yarn.lock 14 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: [ 4 | "eslint:recommended", 5 | "plugin:@typescript-eslint/recommended", 6 | "plugin:svelte/recommended", 7 | "prettier", 8 | ], 9 | parser: "@typescript-eslint/parser", 10 | plugins: ["@typescript-eslint"], 11 | parserOptions: { 12 | sourceType: "module", 13 | ecmaVersion: 2020, 14 | extraFileExtensions: [".svelte"], 15 | }, 16 | env: { 17 | browser: true, 18 | es2017: true, 19 | node: true, 20 | }, 21 | overrides: [ 22 | { 23 | files: ["*.svelte"], 24 | parser: "svelte-eslint-parser", 25 | parserOptions: { 26 | parser: "@typescript-eslint/parser", 27 | }, 28 | }, 29 | ], 30 | }; 31 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": ["config:base"] 4 | } 5 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | concurrency: ${{ github.workflow }}-${{ github.ref }} 9 | 10 | jobs: 11 | release: 12 | name: Release 13 | runs-on: ubuntu-latest 14 | timeout-minutes: 30 15 | permissions: 16 | contents: write 17 | issues: write 18 | pull-requests: write 19 | steps: 20 | - name: Checkout Repo 21 | uses: actions/checkout@v4 22 | 23 | - name: Setup PNPM 24 | uses: pnpm/action-setup@v4 25 | with: 26 | run_install: true 27 | 28 | - name: Build 29 | run: pnpm build 30 | 31 | - name: Create Release Pull Request or Publish to NPM 32 | id: changesets 33 | uses: changesets/action@v1 34 | with: 35 | publish: pnpm changeset publish 36 | version: pnpm changeset version 37 | title: Release Packages 38 | commit: bump versions 39 | env: 40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 41 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 42 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | test: 13 | name: Test 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Checkout Repository 18 | uses: actions/checkout@v4 19 | 20 | - name: Setup PNPM 21 | uses: pnpm/action-setup@v4 22 | with: 23 | run_install: true 24 | 25 | - name: Build All 26 | run: pnpm build 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build 4 | /dist 5 | /.svelte-kit 6 | /package 7 | .env 8 | .env.* 9 | !.env.example 10 | vite.config.js.timestamp-* 11 | vite.config.ts.timestamp-* 12 | -------------------------------------------------------------------------------- /.husky/post-merge: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | pnpm i 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | pnpm lint-staged 5 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true 2 | resolution-mode=highest 3 | -------------------------------------------------------------------------------- /.prettierrc.yml: -------------------------------------------------------------------------------- 1 | --- 2 | printWidth: 100 3 | tabWidth: 4 4 | useTabs: true 5 | trailingComma: all 6 | semi: true 7 | singleQuote: false 8 | 9 | overrides: 10 | - files: "*.md" 11 | options: 12 | useTabs: false 13 | tabWidth: 2 14 | - files: "*.svelte" 15 | options: 16 | parser: svelte 17 | 18 | plugins: 19 | - prettier-plugin-svelte 20 | - prettier-plugin-organize-imports 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # sveltekit-api 2 | 3 | ## 0.6.1 4 | 5 | ### Patch Changes 6 | 7 | - [#72](https://github.com/JacobLinCool/sveltekit-api/pull/72) [`1518e995e7da1a8d9ef5964df7385f147e9bc72b`](https://github.com/JacobLinCool/sveltekit-api/commit/1518e995e7da1a8d9ef5964df7385f147e9bc72b) Thanks [@JinIgarashi](https://github.com/JinIgarashi)! - fix: clone evt.request in parse_body so request can be accessible in endpoint function later 8 | 9 | ## 0.6.0 10 | 11 | ### Minor Changes 12 | 13 | - [`b85af6e3aa8bb691851d83141d3a91a1ce1f0eed`](https://github.com/JacobLinCool/sveltekit-api/commit/b85af6e3aa8bb691851d83141d3a91a1ce1f0eed) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Remove load2api and tree, support svelte 5 14 | 15 | ## 0.5.5 16 | 17 | ### Patch Changes 18 | 19 | - [#64](https://github.com/JacobLinCool/sveltekit-api/pull/64) [`e72fe18fd372b8ac21d6dd4c9d91ec94e5ec260b`](https://github.com/JacobLinCool/sveltekit-api/commit/e72fe18fd372b8ac21d6dd4c9d91ec94e5ec260b) Thanks [@plckr](https://github.com/plckr)! - Endpoint Output incorrect type 20 | 21 | ## 0.5.4 22 | 23 | ### Patch Changes 24 | 25 | - [#61](https://github.com/JacobLinCool/sveltekit-api/pull/61) [`d8c8764ba22d590b002341212d0e36283e9c313e`](https://github.com/JacobLinCool/sveltekit-api/commit/d8c8764ba22d590b002341212d0e36283e9c313e) Thanks [@plckr](https://github.com/plckr)! - handle group routes 26 | 27 | ## 0.5.3 28 | 29 | ### Patch Changes 30 | 31 | - [#56](https://github.com/JacobLinCool/sveltekit-api/pull/56) [`084b81be8f3c7a26f3eb4d74a25468d71636add4`](https://github.com/JacobLinCool/sveltekit-api/commit/084b81be8f3c7a26f3eb4d74a25468d71636add4) Thanks [@woodyloody](https://github.com/woodyloody)! - Returns data changed by safeParse 32 | 33 | ## 0.5.2 34 | 35 | ### Patch Changes 36 | 37 | - [#54](https://github.com/JacobLinCool/sveltekit-api/pull/54) [`c93ba1bcffea1c03b08b7bb43f6cc6965174fe50`](https://github.com/JacobLinCool/sveltekit-api/commit/c93ba1bcffea1c03b08b7bb43f6cc6965174fe50) Thanks [@Andndre](https://github.com/Andndre)! - fix: parse_module cannot parse routes with more than one params 38 | 39 | - [`f543e0936a03817af6d2bda0dcb08118b350d648`](https://github.com/JacobLinCool/sveltekit-api/commit/f543e0936a03817af6d2bda0dcb08118b350d648) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Fix parentheses in path param 40 | 41 | ## 0.5.1 42 | 43 | ### Patch Changes 44 | 45 | - [#49](https://github.com/JacobLinCool/sveltekit-api/pull/49) [`fcf5b8cfaf545c1cf2e554b32ad567982ab1d95e`](https://github.com/JacobLinCool/sveltekit-api/commit/fcf5b8cfaf545c1cf2e554b32ad567982ab1d95e) Thanks [@DoubleMalt](https://github.com/DoubleMalt)! - Return arrays as JSON arrays instead of objects with the indices as keys 46 | 47 | ## 0.5.0 48 | 49 | ### Minor Changes 50 | 51 | - [`abac82a02ed370f1b543ca42922006153ee68547`](https://github.com/JacobLinCool/sveltekit-api/commit/abac82a02ed370f1b543ca42922006153ee68547) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Support Zod Schemas that are not ZodObjects. 52 | 53 | ## 0.4.4 54 | 55 | ### Patch Changes 56 | 57 | - [`bb339ad90cfc3d33cf6e5522411c31b975382940`](https://github.com/JacobLinCool/sveltekit-api/commit/bb339ad90cfc3d33cf6e5522411c31b975382940) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Fix miss typed char in 0.4.3 58 | 59 | ## 0.4.3 60 | 61 | ### Patch Changes 62 | 63 | - [`bdf3acee5df8894ed41a5fed3a9da6fb6a8de011`](https://github.com/JacobLinCool/sveltekit-api/commit/bdf3acee5df8894ed41a5fed3a9da6fb6a8de011) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - GET, HEAD, DELETE, OPTIONS should not have body 64 | 65 | ## 0.4.2 66 | 67 | ### Patch Changes 68 | 69 | - [`bab81f0c3c7472fcee99b9bf39622c980db0abe5`](https://github.com/JacobLinCool/sveltekit-api/commit/bab81f0c3c7472fcee99b9bf39622c980db0abe5) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Improve endpoint handler type inference 70 | 71 | ## 0.4.1 72 | 73 | ### Patch Changes 74 | 75 | - [`7c667f50f24ba8f1cc4914c5d9a7ccea3dd0d7bc`](https://github.com/JacobLinCool/sveltekit-api/commit/7c667f50f24ba8f1cc4914c5d9a7ccea3dd0d7bc) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Add `error` util function to prevent directly throwing from SvelteKit 2 76 | 77 | ## 0.4.0 78 | 79 | ### Minor Changes 80 | 81 | - [#34](https://github.com/JacobLinCool/sveltekit-api/pull/34) [`399a8daa0890a0dae2653cfe97c6ee9e6f61979c`](https://github.com/JacobLinCool/sveltekit-api/commit/399a8daa0890a0dae2653cfe97c6ee9e6f61979c) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - `Endpoint` class for better type inference 82 | 83 | ## 0.3.2 84 | 85 | ### Patch Changes 86 | 87 | - [`fde8e4fe5280d139ec8da8958c7f43e72ecaf78e`](https://github.com/JacobLinCool/sveltekit-api/commit/fde8e4fe5280d139ec8da8958c7f43e72ecaf78e) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Upgrade deps to support SvelteKit 2 88 | 89 | ## 0.3.1 90 | 91 | ### Patch Changes 92 | 93 | - [`f22bb75`](https://github.com/JacobLinCool/sveltekit-api/commit/f22bb7578ce1bc22490a655462780d3d0b773fd9) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Support promised (async) output 94 | 95 | ## 0.3.0 96 | 97 | ### Minor Changes 98 | 99 | - [`e3458bb`](https://github.com/JacobLinCool/sveltekit-api/commit/e3458bb1ebb80dd23178a4fb79959007fe18546e) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Support event stream and custom response as handler output 100 | 101 | ## 0.2.13 102 | 103 | ### Patch Changes 104 | 105 | - [`d71814a`](https://github.com/JacobLinCool/sveltekit-api/commit/d71814a4ef43ace2a1387fd638c83fb4054e4118) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Fix output parser 106 | 107 | ## 0.2.12 108 | 109 | ### Patch Changes 110 | 111 | - [`cc023a2`](https://github.com/JacobLinCool/sveltekit-api/commit/cc023a220caded1efff1fcee6b54f2240951d769) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Enable output verification by default 112 | 113 | ## 0.2.11 114 | 115 | ### Patch Changes 116 | 117 | - [`d52fac2`](https://github.com/JacobLinCool/sveltekit-api/commit/d52fac22864dbcef5d1d7c17ad7a0d8be96e4a66) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Support route config modifier 118 | 119 | ## 0.2.10 120 | 121 | ### Patch Changes 122 | 123 | - [`0028a88`](https://github.com/JacobLinCool/sveltekit-api/commit/0028a88d03fe335e4feec6d46369d82541ffcbc8) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Set allow headers for cors 124 | 125 | ## 0.2.9 126 | 127 | ### Patch Changes 128 | 129 | - [`9ac33f5`](https://github.com/JacobLinCool/sveltekit-api/commit/9ac33f56b549eef1d32ac09b75ec85ddf32ad37e) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Make API servers overwritable 130 | 131 | ## 0.2.8 132 | 133 | ### Patch Changes 134 | 135 | - [`9963854`](https://github.com/JacobLinCool/sveltekit-api/commit/9963854093096fe43368f50d44016830f1230405) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Mark fallback inputs partial 136 | 137 | ## 0.2.7 138 | 139 | ### Patch Changes 140 | 141 | - [`c6b74db`](https://github.com/JacobLinCool/sveltekit-api/commit/c6b74dbf00720545e9e9dc88f620be9c043460e2) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Improve fallback type inference for input parser with route module 142 | 143 | - [`730035f`](https://github.com/JacobLinCool/sveltekit-api/commit/730035f8e0bc117013faaaf62f00f3e50e7647a4) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Mark `extra` parameter of `API.parse` optional 144 | 145 | ## 0.2.6 146 | 147 | ### Patch Changes 148 | 149 | - [`e71e608`](https://github.com/JacobLinCool/sveltekit-api/commit/e71e608711b44ff0ff1915c591a21cc41a5a469d) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Extra registry modifier 150 | 151 | - [`3f51fc0`](https://github.com/JacobLinCool/sveltekit-api/commit/3f51fc036656846ef1addb942ec969f2406bc3cd) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Support additional fallback inputs 152 | 153 | ## 0.2.5 154 | 155 | ### Patch Changes 156 | 157 | - [`b616e52`](https://github.com/JacobLinCool/sveltekit-api/commit/b616e5245cce36c09143f0cb4434263c27201c2c) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Simplify input parser return types 158 | 159 | ## 0.2.4 160 | 161 | ### Patch Changes 162 | 163 | - [`3d38e37`](https://github.com/JacobLinCool/sveltekit-api/commit/3d38e3713ceaaa4b35216f1e81a6d5c12ca165be) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Fix return types for `API.parse` 164 | 165 | ## 0.2.3 166 | 167 | ### Patch Changes 168 | 169 | - [`6005a51`](https://github.com/JacobLinCool/sveltekit-api/commit/6005a511bd98da8b270f73b9c3603995e44ca209) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Use `API.parse` method to parse inputs from request event 170 | 171 | ## 0.2.2 172 | 173 | ### Patch Changes 174 | 175 | - [`282dc88`](https://github.com/JacobLinCool/sveltekit-api/commit/282dc884d3a9412de52c7d61f5fe5a44b780f814) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Pass request event to endpoint handler 176 | 177 | ## 0.2.1 178 | 179 | ### Patch Changes 180 | 181 | - [`e70ac9e`](https://github.com/JacobLinCool/sveltekit-api/commit/e70ac9e3e626248c5e4416133d5aa5b5e383eb20) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - Fix TypeScript definitions for API 182 | 183 | ## 0.2.0 184 | 185 | ### Minor Changes 186 | 187 | - [`1ed77c3`](https://github.com/JacobLinCool/sveltekit-api/commit/1ed77c30c1c74186e54cd3fdd1973a5b89b80130) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - API class to manage API endpoints and automatically generate OpenAPI documentation 188 | 189 | ## 0.1.0 190 | 191 | ### Minor Changes 192 | 193 | - [`24279d0`](https://github.com/JacobLinCool/sveltekit-api/commit/24279d0a2169754fc793fe65d4ef4f2052992c0b) Thanks [@JacobLinCool](https://github.com/JacobLinCool)! - `load2api` and `tree` utilities for creating endpoints. 194 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 JacobLinCool 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SvelteKit-API 2 | 3 | Handles all kinds of SvelteKit data flows in one place, and automatically generate OpenAPI documentation. 4 | 5 | ## Features 6 | 7 | - [x] `API`: Manage API endpoints and automatically generate OpenAPI documentation 8 | 9 | ## Installation 10 | 11 | ```bash 12 | pnpm i -D sveltekit-api 13 | ``` 14 | 15 | ## Projects using SvelteKit-API 16 | 17 | These projects are using SvelteKit-API and can be used as examples: 18 | 19 | - [WASM OJ Wonderland](https://github.com/wasm-oj/wonderland): A SvelteKit-based online judge system core. 20 | - [PEA](https://github.com/JacobLinCool/pea): A serverless email authentication and verification service. 21 | - Add your project here by submitting a pull request! 22 | 23 | ## Usage 24 | 25 | ### `API` 26 | 27 | Add `$api` to your `svelte.config.js`: 28 | 29 | ```js 30 | /** @type {import('@sveltejs/kit').Config} */ 31 | const config = { 32 | kit: { 33 | alias: { 34 | "$api": "./src/api", 35 | }, 36 | }, 37 | }; 38 | ``` 39 | 40 | Create the API endpoints in the structure like [`src/api`](./src/api). 41 | 42 | ```ts 43 | // for example: 44 | src 45 | ├── api 46 | │ ├── index.ts 47 | │ └── post 48 | │ ├── GET.ts 49 | │ ├── POST.ts 50 | │ ├── [...id] 51 | │ │ └── GET.ts 52 | │ └── search 53 | │ └── GET.ts 54 | ├── lib 55 | │ └── ... 56 | └── routes 57 | └── ... 58 | ``` 59 | 60 | ```ts 61 | // file: src/api/index.ts 62 | import { API } from "sveltekit-api"; 63 | 64 | export default new API(import.meta.glob("./**/*.ts"), { 65 | openapi: "3.0.0", 66 | info: { 67 | title: "Simple Post API", 68 | version: "1.0.0", 69 | description: "An example API", 70 | }, 71 | }); 72 | ``` 73 | 74 | ```ts 75 | // file: src/api/post/[...id]/PUT.ts 76 | import { Endpoint, z, error } from "sveltekit-api"; 77 | import { posts, type Post } from "../../db.js"; 78 | 79 | export const Query = z.object({ 80 | password: z.string().optional(), 81 | }); 82 | 83 | export const Param = z.object({ 84 | id: z.string(), 85 | }); 86 | 87 | export const Input = z.object({ 88 | title: z.string(), 89 | content: z.string(), 90 | author: z.string(), 91 | }); 92 | 93 | export const Output = z.object({ 94 | id: z.string(), 95 | title: z.string(), 96 | content: z.string(), 97 | author: z.string(), 98 | date: z.string(), 99 | }) satisfies z.ZodSchema; 100 | 101 | export const Error = { 102 | 404: error(404, "Post not found"), 103 | 403: error(403, "Forbidden"), 104 | }; 105 | 106 | export default new Endpoint({ Param, Query, Input, Output, Error }).handle(async (param) => { 107 | const post = posts.get(param.id); 108 | 109 | if (!post) { 110 | throw Error[404]; 111 | } 112 | 113 | if (post.password && post.password !== param.password) { 114 | throw Error[403]; 115 | } 116 | 117 | post.title = param.title; 118 | post.content = param.content; 119 | post.author = param.author; 120 | 121 | return post; 122 | }); 123 | ``` 124 | 125 | Call the API handler and OpenAPI generator in your routes like [`src/routes/api`](./src/routes/api). 126 | 127 | ```ts 128 | // file: src/routes/+server.ts 129 | import api from "$api"; 130 | import { json } from "@sveltejs/kit"; 131 | 132 | export const prerender = true; 133 | 134 | export const GET = async (evt) => json(await api.openapi(evt)); 135 | ``` 136 | 137 | ```ts 138 | // file: src/routes/api/post/+server.ts 139 | import api from "$api"; 140 | 141 | export const GET = async (evt) => api.handle(evt); 142 | export const POST = async (evt) => api.handle(evt); 143 | export const OPTIONS = async (evt) => api.handle(evt); 144 | ``` 145 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sveltekit-api", 3 | "version": "0.6.1", 4 | "description": "Handles all kinds of SvelteKit data flows in one place, and automatically generate OpenAPI documentation.", 5 | "license": "MIT", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/JacobLinCool/sveltekit-api.git" 9 | }, 10 | "homepage": "https://github.com/JacobLinCool/sveltekit-api", 11 | "svelte": "./dist/index.js", 12 | "types": "./dist/index.d.ts", 13 | "type": "module", 14 | "exports": { 15 | ".": { 16 | "types": "./dist/index.d.ts", 17 | "svelte": "./dist/index.js" 18 | } 19 | }, 20 | "files": [ 21 | "dist", 22 | "!dist/**/*.test.*", 23 | "!dist/**/*.spec.*" 24 | ], 25 | "dependencies": { 26 | "@asteasolutions/zod-to-openapi": "^6.3.1", 27 | "debug": "^4.3.4", 28 | "type-fest": "^4.10.2", 29 | "zod": "^3.22.4", 30 | "zod-validation-error": "^3.0.0" 31 | }, 32 | "peerDependencies": { 33 | "@sveltejs/kit": "^1.0.0 || ^2.0.0", 34 | "svelte": "^3.0.0 || ^4.0.0 || ^5.0.0" 35 | }, 36 | "devDependencies": { 37 | "@changesets/changelog-github": "^0.4.8", 38 | "@changesets/cli": "^2.27.1", 39 | "@sveltejs/adapter-auto": "^2.1.1", 40 | "@sveltejs/package": "^2.2.6", 41 | "@sveltejs/vite-plugin-svelte": "^3.0.2", 42 | "@types/better-sqlite3": "^7.6.9", 43 | "@types/debug": "^4.1.12", 44 | "@typescript-eslint/eslint-plugin": "^6.20.0", 45 | "@typescript-eslint/parser": "^6.20.0", 46 | "changeset": "^0.2.6", 47 | "eslint": "^8.56.0", 48 | "eslint-config-prettier": "^9.1.0", 49 | "eslint-plugin-svelte": "^2.35.1", 50 | "husky": "^9.0.10", 51 | "lint-staged": "^15.2.1", 52 | "prettier": "^3.2.4", 53 | "prettier-plugin-organize-imports": "^3.2.4", 54 | "prettier-plugin-svelte": "^3.1.2", 55 | "publint": "^0.2.7", 56 | "svelte": "^4.2.9", 57 | "svelte-check": "^3.6.3", 58 | "tslib": "^2.6.2", 59 | "typescript": "^5.3.3", 60 | "vite": "^5.0.12" 61 | }, 62 | "scripts": { 63 | "prepare": "husky", 64 | "dev": "vite dev", 65 | "build": "vite build && pnpm run package", 66 | "preview": "vite preview", 67 | "package": "svelte-kit sync && svelte-package && publint", 68 | "prepublishOnly": "pnpm run package", 69 | "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", 70 | "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", 71 | "lint": "prettier --ignore-path .gitignore --check . && eslint .", 72 | "format": "prettier --ignore-path .gitignore --write .", 73 | "changeset": "changeset" 74 | }, 75 | "lint-staged": { 76 | "*.{ts,js,json,yaml,yml,svelte,html}": [ 77 | "prettier --write" 78 | ] 79 | }, 80 | "packageManager": "pnpm@8.15.1" 81 | } 82 | -------------------------------------------------------------------------------- /src/api/async/GET.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, z } from "$lib/index.js"; 2 | 3 | export const Output = z.object({ 4 | data: z.promise(z.number()).openapi({ type: "number" }), 5 | }); 6 | 7 | export default new Endpoint({ Output }).handle(async () => { 8 | return { 9 | data: new Promise((resolve) => { 10 | setTimeout(() => { 11 | resolve(Math.random()); 12 | }, 1000); 13 | }), 14 | }; 15 | }); 16 | -------------------------------------------------------------------------------- /src/api/db.ts: -------------------------------------------------------------------------------- 1 | export interface Post { 2 | id: string; 3 | title: string; 4 | content: string; 5 | author: string; 6 | date: string; 7 | password?: string; 8 | } 9 | 10 | export const posts = new Map(); 11 | -------------------------------------------------------------------------------- /src/api/group/GET.ts: -------------------------------------------------------------------------------- 1 | import { json } from "@sveltejs/kit"; 2 | 3 | export default function () { 4 | return json({ status: "ok" }); 5 | } 6 | -------------------------------------------------------------------------------- /src/api/group/[param]/GET.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint } from "$lib/api.js"; 2 | import { z } from "$lib/index.js"; 3 | 4 | export const Param = z.object({ param: z.string() }); 5 | export const Output = z.object({ 6 | param: z.string(), 7 | date: z 8 | .instanceof(Date) 9 | .transform((d) => d.toISOString()) 10 | // in this case, our custom zod isn't able to detect it as a string 11 | // so, in order to have a consistent schema spec 12 | // we have to tell it manually ⬇︎ 13 | .openapi({ type: "string" }), 14 | }); 15 | 16 | export default new Endpoint({ Param, Output }).handle(async ({ param }) => { 17 | return { 18 | param, 19 | date: new Date(), 20 | }; 21 | }); 22 | -------------------------------------------------------------------------------- /src/api/index.ts: -------------------------------------------------------------------------------- 1 | import { API } from "$lib/index.js"; 2 | 3 | export default new API(import.meta.glob("./**/*.ts"), { 4 | openapi: "3.0.0", 5 | info: { 6 | title: "Simple Post API", 7 | version: "1.0.0", 8 | description: "An example API", 9 | }, 10 | }); 11 | -------------------------------------------------------------------------------- /src/api/post/GET.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, z } from "$lib/index.js"; 2 | import { posts } from "../db.js"; 3 | 4 | export const Output = z.object({ 5 | count: z.number().nonnegative(), 6 | }); 7 | 8 | export default new Endpoint({ Output }).handle(async () => { 9 | return { 10 | count: posts.size, 11 | }; 12 | }); 13 | -------------------------------------------------------------------------------- /src/api/post/POST.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, z } from "$lib/index.js"; 2 | import { posts, type Post } from "../db.js"; 3 | 4 | export const Input = z.object({ 5 | title: z.string(), 6 | content: z.string(), 7 | author: z.string(), 8 | }); 9 | 10 | export const Output = z.object({ 11 | id: z.string(), 12 | title: z.string(), 13 | content: z.string(), 14 | author: z.string(), 15 | date: z.string(), 16 | password: z.string().optional(), 17 | }) satisfies z.ZodSchema; 18 | 19 | export default new Endpoint({ Input, Output }).handle(async (input) => { 20 | const id = Math.random().toString(36).substring(2); 21 | const date = new Date().toISOString(); 22 | const post = { id, date, ...input }; 23 | 24 | posts.set(id, post); 25 | 26 | return post; 27 | }); 28 | -------------------------------------------------------------------------------- /src/api/post/[...id]/GET.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, error, z } from "$lib/index.js"; 2 | import { posts, type Post } from "../../db.js"; 3 | 4 | export const Query = z.object({ 5 | password: z.string().optional(), 6 | }); 7 | 8 | export const Param = z.object({ 9 | id: z.string(), 10 | }); 11 | 12 | export const Output = z.object({ 13 | id: z.string(), 14 | title: z.string(), 15 | content: z.string(), 16 | author: z.string(), 17 | date: z.string(), 18 | }) satisfies z.ZodSchema; 19 | 20 | export const Error = { 21 | 404: error(404, "Post not found"), 22 | 403: error(403, "Forbidden"), 23 | }; 24 | 25 | export default new Endpoint({ Param, Query, Output, Error }).handle(async (param) => { 26 | const post = posts.get(param.id); 27 | 28 | if (!post) { 29 | throw Error[404]; 30 | } 31 | 32 | if (post.password && post.password !== param.password) { 33 | throw Error[403]; 34 | } 35 | 36 | return post; 37 | }); 38 | -------------------------------------------------------------------------------- /src/api/post/[...id]/PUT.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, error, z } from "$lib/index.js"; 2 | import { posts, type Post } from "../../db.js"; 3 | 4 | export const Query = z.object({ 5 | password: z.string().optional(), 6 | }); 7 | 8 | export const Param = z.object({ 9 | id: z.string(), 10 | }); 11 | 12 | export const Input = z.object({ 13 | title: z.string(), 14 | content: z.string(), 15 | author: z.string(), 16 | }); 17 | 18 | export const Output = z.object({ 19 | id: z.string(), 20 | title: z.string(), 21 | content: z.string(), 22 | author: z.string(), 23 | date: z.string(), 24 | }) satisfies z.ZodSchema; 25 | 26 | export const Error = { 27 | 404: error(404, "Post not found"), 28 | 403: error(403, "Forbidden"), 29 | }; 30 | 31 | export default new Endpoint({ Param, Query, Input, Output, Error }).handle(async (param) => { 32 | const post = posts.get(param.id); 33 | 34 | if (!post) { 35 | throw Error[404]; 36 | } 37 | 38 | if (post.password && post.password !== param.password) { 39 | throw Error[403]; 40 | } 41 | 42 | post.title = param.title; 43 | post.content = param.content; 44 | post.author = param.author; 45 | 46 | return post; 47 | }); 48 | -------------------------------------------------------------------------------- /src/api/post/search/GET.ts: -------------------------------------------------------------------------------- 1 | import { Endpoint, z } from "$lib/index.js"; 2 | import { posts, type Post } from "../../db.js"; 3 | 4 | export const Query = z.object({ 5 | q: z.string(), 6 | }); 7 | 8 | export const Output = z.object({ 9 | posts: z.array( 10 | z.object({ 11 | id: z.string(), 12 | title: z.string(), 13 | content: z.string(), 14 | author: z.string(), 15 | date: z.string(), 16 | }), 17 | ), 18 | }) satisfies z.ZodSchema<{ posts: Post[] }>; 19 | 20 | export default new Endpoint({ Query, Output }).handle(async (query) => { 21 | const q = query.q.toLowerCase(); 22 | 23 | const results = [...posts.values()].filter( 24 | (post) => 25 | q && 26 | (post.title.toLowerCase().includes(q) || 27 | post.content.toLowerCase().includes(q) || 28 | post.author.toLowerCase().includes(q)), 29 | ); 30 | 31 | return { posts: results }; 32 | }); 33 | -------------------------------------------------------------------------------- /src/app.d.ts: -------------------------------------------------------------------------------- 1 | // See https://kit.svelte.dev/docs/types#app 2 | // for information about these interfaces 3 | declare global { 4 | namespace App { 5 | // interface Error {} 6 | // interface Locals {} 7 | // interface PageData {} 8 | // interface Platform {} 9 | } 10 | } 11 | 12 | export {}; 13 | -------------------------------------------------------------------------------- /src/app.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %sveltekit.head% 8 | 9 | 10 |
%sveltekit.body%
11 | 12 | 13 | -------------------------------------------------------------------------------- /src/lib/api.ts: -------------------------------------------------------------------------------- 1 | import type { OpenAPIObjectConfig } from "@asteasolutions/zod-to-openapi/dist/v3.0/openapi-generator.js"; 2 | import type { HttpError, RequestEvent } from "@sveltejs/kit"; 3 | import { error, json } from "@sveltejs/kit"; 4 | import type { Simplify } from "type-fest"; 5 | import { fromZodError } from "zod-validation-error"; 6 | import { log as _log } from "./log.js"; 7 | import type { RouteConfig } from "./openapi.js"; 8 | import { OpenAPIRegistry, OpenApiGeneratorV3 } from "./openapi.js"; 9 | import { recursive_await } from "./utils.js"; 10 | import { z } from "./zod.js"; 11 | 12 | const log = _log.extend("api"); 13 | 14 | export const METHOD = /^(GET|POST|PUT|DELETE|PATCH|OPTIONS)$/; 15 | 16 | /** 17 | * Modify route config after parsing input-ouput shapes. 18 | * Useful for adding custom tags, etc. 19 | * 20 | * @param r Route config 21 | * @returns Modified route config 22 | * @example 23 | * ```ts 24 | * export const Modifier: RouteModifier = (r) => { 25 | * r.tags = ["Tag"]; 26 | * r.operationId = "customOperationId"; 27 | * r.security = [{ bearerAuth: [] }]; 28 | * return r; 29 | * }; 30 | * ``` 31 | */ 32 | export type RouteModifier = (r: RouteConfig) => RouteConfig; 33 | 34 | export interface HandleOptions { 35 | /** 36 | * Enable CORS headers 37 | */ 38 | cors: boolean; 39 | /** 40 | * Fallback values for missing input shapes, will be validated against 41 | */ 42 | fallback: Partial>>; 43 | /** 44 | * Verify and strip unknown properties from output, useful for preventing accidental exposure of sensitive data 45 | */ 46 | verify: boolean; 47 | } 48 | 49 | export interface APIRoute< 50 | P extends z.ZodType = z.ZodObject>, 51 | Q extends z.ZodType = z.ZodObject>, 52 | I extends z.ZodType = z.ZodObject>, 53 | O extends z.ZodType = z.ZodObject>, 54 | S extends z.ZodType = z.ZodObject>, 55 | E extends Record = Record, 56 | > { 57 | /** 58 | * Path parameters 59 | */ 60 | Param?: P; 61 | /** 62 | * Query string parameters 63 | */ 64 | Query?: Q; 65 | /** 66 | * Body 67 | */ 68 | Input?: I; 69 | /** 70 | * Returning data 71 | */ 72 | Output?: O; 73 | /** 74 | * Event stream data 75 | */ 76 | Stream?: S; 77 | /** 78 | * Possible errors 79 | */ 80 | Error?: E; 81 | /** 82 | * OpenAPI route config modifier 83 | */ 84 | // eslint-disable-next-line @typescript-eslint/ban-types 85 | Modifier?: RouteModifier; 86 | /** 87 | * Handler 88 | */ 89 | // eslint-disable-next-line @typescript-eslint/ban-types 90 | default?: Function; 91 | } 92 | 93 | export class Endpoint< 94 | P extends z.ZodType = z.ZodObject>, 95 | Q extends z.ZodType = z.ZodObject>, 96 | I extends z.ZodType = z.ZodObject>, 97 | O extends z.ZodType = z.ZodObject>, 98 | S extends z.ZodType = z.ZodObject>, 99 | E extends Record = Record, 100 | H extends ( 101 | input: Simplify & z.infer & z.infer

>, 102 | evt: RequestEvent, 103 | ) => Promise> = ( 104 | input: Simplify & z.infer & z.infer

>, 105 | evt: RequestEvent, 106 | ) => Promise>, 107 | > implements APIRoute 108 | { 109 | constructor( 110 | { 111 | Param, 112 | Query, 113 | Input, 114 | Output, 115 | Stream, 116 | Error, 117 | Modifier, 118 | }: APIRoute = {} as APIRoute, 119 | ) { 120 | this.Param = Param; 121 | this.Query = Query; 122 | this.Input = Input; 123 | this.Output = Output; 124 | this.Stream = Stream; 125 | this.Error = Error; 126 | this.Modifier = Modifier; 127 | } 128 | 129 | handle(f: H): this { 130 | this.default = f; 131 | return this; 132 | } 133 | 134 | Param?: P; 135 | Query?: Q; 136 | Input?: I; 137 | Output?: O; 138 | Stream?: S; 139 | Error?: E; 140 | Modifier?: RouteModifier; 141 | // @ts-expect-error default handler throws error 142 | default: H = () => { 143 | throw new Error("Route handler not defined"); 144 | }; 145 | } 146 | 147 | export class API { 148 | public routes: Record Promise>; 149 | public config: OpenAPIObjectConfig; 150 | public base: string; 151 | public register: (registry: OpenAPIRegistry) => void; 152 | 153 | constructor( 154 | routes: Record Promise>, 155 | config: OpenAPIObjectConfig, 156 | base = "/api", 157 | register: (registry: OpenAPIRegistry) => void = () => undefined, 158 | ) { 159 | this.routes = Object.fromEntries( 160 | Object.entries(routes) 161 | .filter(([route]) => { 162 | const parts = route.split("/"); 163 | const last = parts[parts.length - 1].split(".")[0]; 164 | return METHOD.test(last); 165 | }) 166 | .map(([route, load]) => { 167 | const parts = route.split("/"); 168 | const last = parts[parts.length - 1].split(".")[0]; 169 | parts[parts.length - 1] = last; 170 | const id = parts.join("/"); 171 | return [id, load]; 172 | }), 173 | ); 174 | log("routes: %O", this.routes); 175 | this.config = config; 176 | log("config: %O", this.config); 177 | this.base = base; 178 | log("base: %s", this.base); 179 | 180 | this.register = register; 181 | } 182 | 183 | async handle( 184 | evt: RequestEvent, 185 | { 186 | cors = true, 187 | fallback = { 188 | body: {}, 189 | query: {}, 190 | param: {}, 191 | }, 192 | verify = true, 193 | }: Partial = {}, 194 | ): Promise { 195 | if (!evt.route.id) { 196 | throw error(500, "No Route"); 197 | } 198 | log("route id: %s", evt.route.id); 199 | 200 | // handle OPTIONS 201 | if (evt.request.method.toUpperCase() === "OPTIONS") { 202 | return new Response(null, { 203 | headers: cors 204 | ? { 205 | "Access-Control-Allow-Origin": "*", 206 | "Access-Control-Allow-Methods": 207 | "GET, POST, PUT, DELETE, PATCH, OPTIONS", 208 | "Access-Control-Allow-Headers": "Content-Type, Authorization", 209 | } 210 | : {}, 211 | }); 212 | } 213 | 214 | const route = 215 | this.routes[ 216 | `${evt.route.id.replace(/\(.+\)\//g, "").replace(this.base, ".")}/${evt.request.method.toUpperCase()}` 217 | ]; 218 | if (!route) { 219 | throw error(404, "Route not found"); 220 | } 221 | 222 | let module = (await route()) as APIRoute; 223 | if (!module || typeof module !== "object" || !("default" in module)) { 224 | throw error(404, "Route not found"); 225 | } 226 | if (module.default instanceof Endpoint) { 227 | module = module.default; 228 | } else if (typeof module.default === "function") { 229 | // whole module is an endpoint 230 | } else { 231 | throw error(404, "Route type not supported"); 232 | } 233 | 234 | const param = await this.parse_param(evt, module, fallback.param); 235 | const query = await this.parse_query(evt, module, fallback.query); 236 | const body = await this.parse_body(evt, module, fallback.body); 237 | 238 | if (!module.default) { 239 | throw error(500, "Route handler not defined"); 240 | } 241 | 242 | const output = await module.default({ ...body, ...query, ...param }, evt); 243 | 244 | const CORS = { 245 | "Access-Control-Allow-Origin": "*", 246 | "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", 247 | "Access-Control-Allow-Headers": "Content-Type, Authorization", 248 | } as const; 249 | 250 | if (output instanceof Response) { 251 | if (cors) { 252 | for (const [key, value] of Object.entries(CORS)) { 253 | output.headers.set(key, value); 254 | } 255 | } 256 | 257 | return output; 258 | } 259 | 260 | // ReadableStream for Server-Sent Events 261 | if (output instanceof ReadableStream) { 262 | const res = new Response(output, { 263 | headers: { 264 | "Content-Type": "text/event-stream", 265 | "Cache-Control": "no-cache", 266 | Connection: "keep-alive", 267 | ...(cors ? CORS : {}), 268 | }, 269 | }); 270 | return res; 271 | } 272 | 273 | if (output instanceof Response) { 274 | return output; 275 | } else if (output instanceof ArrayBuffer) { 276 | const res = new Response(output, { 277 | headers: { 278 | "Content-Type": "application/octet-stream", 279 | ...(cors ? CORS : {}), 280 | }, 281 | }); 282 | return res; 283 | } else { 284 | const out = await recursive_await( 285 | verify ? await this.parse_output(output, module) : output, 286 | ); 287 | const res = json(out, { 288 | headers: cors ? CORS : {}, 289 | }); 290 | 291 | return res; 292 | } 293 | } 294 | 295 | /** 296 | * Parse inputs from request event 297 | * @param module API route module, e.g. `import * as route from "./user/[id]/GET"` 298 | * @param evt Request event 299 | * @param extra Fallback inputs, ... 300 | * @returns Parsed inputs 301 | */ 302 | async parse( 303 | module: T, 304 | evt: RequestEvent, 305 | extra?: { 306 | fallback?: { 307 | body?: T["Input"] extends z.ZodType ? Partial> : never; 308 | query?: T["Query"] extends z.ZodType ? Partial> : never; 309 | param?: T["Param"] extends z.ZodType ? Partial> : never; 310 | }; 311 | }, 312 | ): Promise< 313 | Simplify< 314 | (T["Input"] extends z.ZodType ? z.infer : Record) & 315 | (T["Query"] extends z.ZodType ? z.infer : Record) & 316 | (T["Param"] extends z.ZodType ? z.infer : Record) 317 | > 318 | >; 319 | /** 320 | * Parse inputs from request event 321 | * @param id API route ID with method, e.g. `./user/[id]/GET` 322 | * @param evt Request event 323 | * @param extra Fallback inputs, ... 324 | * @returns Parsed inputs 325 | */ 326 | async parse( 327 | id: string, 328 | evt: RequestEvent, 329 | extra?: { 330 | fallback?: Partial>>; 331 | }, 332 | ): Promise<{ [x: string]: unknown }>; 333 | async parse( 334 | id: string | APIRoute, 335 | evt: RequestEvent, 336 | { 337 | fallback = { 338 | body: {}, 339 | query: {}, 340 | param: {}, 341 | } as Partial>>, 342 | } = {}, 343 | ): Promise<{ [x: string]: unknown }> { 344 | const module = typeof id === "string" ? await this.parse_module(id) : id; 345 | const param = await this.parse_param(evt, module, fallback.param); 346 | const query = await this.parse_query(evt, module, fallback.query); 347 | const body = await this.parse_body(evt, module, fallback.body); 348 | return { ...body, ...query, ...param }; 349 | } 350 | 351 | handlers() { 352 | return { 353 | GET: async (evt: RequestEvent) => this.handle(evt), 354 | POST: async (evt: RequestEvent) => this.handle(evt), 355 | PUT: async (evt: RequestEvent) => this.handle(evt), 356 | DELETE: async (evt: RequestEvent) => this.handle(evt), 357 | PATCH: async (evt: RequestEvent) => this.handle(evt), 358 | OPTIONS: async (evt: RequestEvent) => this.handle(evt), 359 | }; 360 | } 361 | 362 | async openapi(evt?: RequestEvent) { 363 | const registry = new OpenAPIRegistry(); 364 | 365 | for (const route of Object.keys(this.routes)) { 366 | const module = await this.parse_module(route); 367 | 368 | const config = module.modifier({ 369 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 370 | method: module.method.toLowerCase() as any, 371 | path: module.path, 372 | request: { 373 | params: module.param, 374 | query: module.query, 375 | body: module.body 376 | ? { 377 | description: "", 378 | content: { 379 | "application/json": { 380 | schema: module.body, 381 | }, 382 | "application/x-www-form-urlencoded": { 383 | schema: module.body, 384 | }, 385 | "multipart/form-data": { 386 | schema: module.body, 387 | }, 388 | }, 389 | } 390 | : undefined, 391 | }, 392 | responses: { 393 | ...(module.output 394 | ? { 395 | "200": { 396 | description: "", 397 | content: { 398 | "application/json": { 399 | schema: module.output as never, 400 | }, 401 | }, 402 | }, 403 | } 404 | : undefined), 405 | ...(module.stream 406 | ? { 407 | "200": { 408 | description: "", 409 | content: { 410 | "text/event-stream": { 411 | schema: module.stream as never, 412 | }, 413 | }, 414 | }, 415 | } 416 | : undefined), 417 | ...(module.query || module.param || module.body 418 | ? { 419 | "400": { 420 | description: 421 | "Invalid input (path parameters, query string, or body)", 422 | content: { 423 | "application/json": { 424 | schema: z.object({ 425 | message: z.string(), 426 | }), 427 | }, 428 | }, 429 | }, 430 | } 431 | : undefined), 432 | ...(Object.fromEntries( 433 | module.errors.map((error) => [ 434 | error.status, 435 | { 436 | description: error.body.message, 437 | }, 438 | ]), 439 | ) ?? {}), 440 | }, 441 | }); 442 | 443 | registry.registerPath(config); 444 | } 445 | 446 | this.register(registry); 447 | 448 | const generator = new OpenApiGeneratorV3(registry.definitions); 449 | const openapi = generator.generateDocument( 450 | evt 451 | ? { 452 | servers: [ 453 | { 454 | url: evt.url.origin, 455 | }, 456 | ], 457 | ...this.config, 458 | } 459 | : this.config, 460 | ); 461 | log("openapi: %O", openapi); 462 | return openapi; 463 | } 464 | 465 | protected async parse_body( 466 | evt: RequestEvent, 467 | module: object, 468 | fallback?: Record, 469 | ): Promise> { 470 | let body: Record = { ...fallback }; 471 | 472 | // GET, HEAD, DELETE, OPTIONS have no body 473 | const method = evt.request.method.toUpperCase(); 474 | if (["GET", "HEAD", "DELETE", "OPTIONS"].includes(method)) { 475 | return body; 476 | } 477 | const clonedRequest = evt.request.clone(); 478 | // JSON body 479 | if (clonedRequest.headers.get("content-type")?.startsWith("application/json")) { 480 | try { 481 | const json = await clonedRequest.json(); 482 | if (typeof json === "object") { 483 | Object.assign(body, json); 484 | } 485 | } catch { 486 | throw error(400, "Invalid JSON body"); 487 | } 488 | } 489 | // Form body 490 | else if ( 491 | clonedRequest.headers 492 | .get("content-type") 493 | ?.startsWith("application/x-www-form-urlencoded") || 494 | clonedRequest.headers.get("content-type")?.startsWith("multipart/form-data") 495 | ) { 496 | const form = await clonedRequest.formData(); 497 | for (const [key, value] of form.entries()) { 498 | if (body[key]) { 499 | const existing = body[key]; 500 | if (Array.isArray(existing)) { 501 | existing.push(value); 502 | } else { 503 | body[key] = [body[key], value]; 504 | } 505 | } else { 506 | body[key] = value; 507 | } 508 | } 509 | } 510 | // Text body 511 | else if (clonedRequest.headers.get("content-type")?.startsWith("text/plain")) { 512 | const text = await clonedRequest.text(); 513 | body.text = text; 514 | } 515 | // Binary body 516 | else if ( 517 | clonedRequest.headers.get("content-type")?.startsWith("application/octet-stream") 518 | ) { 519 | const buffer = await clonedRequest.arrayBuffer(); 520 | body.buffer = buffer; 521 | } 522 | 523 | log("body: %O", body); 524 | 525 | const validator = 526 | "Input" in module && module.Input instanceof z.ZodObject ? module.Input : z.object({}); 527 | const validation = validator.safeParse(body); 528 | if (!validation.success) { 529 | throw error(400, `Invalid body.\n${fromZodError(validation.error).message}`); 530 | } else { 531 | body = validation.data; 532 | } 533 | 534 | return body; 535 | } 536 | 537 | protected async parse_query( 538 | evt: RequestEvent, 539 | module: object, 540 | fallback?: Record, 541 | ): Promise> { 542 | let query: Record = { ...fallback }; 543 | 544 | for (const [key, value] of evt.url.searchParams.entries()) { 545 | if (query[key]) { 546 | const existing = query[key]; 547 | if (Array.isArray(existing)) { 548 | existing.push(value); 549 | } else { 550 | query[key] = [query[key], value]; 551 | } 552 | } else { 553 | query[key] = value; 554 | } 555 | } 556 | 557 | log("query: %O", query); 558 | 559 | const validator = 560 | "Query" in module && module.Query instanceof z.ZodObject ? module.Query : z.object({}); 561 | const validation = validator.safeParse(query); 562 | if (!validation.success) { 563 | throw error(400, `Invalid query.\n${fromZodError(validation.error).message}`); 564 | } else { 565 | query = validation.data; 566 | } 567 | 568 | return query; 569 | } 570 | 571 | protected async parse_param( 572 | evt: RequestEvent, 573 | module: object, 574 | fallback?: Record, 575 | ): Promise> { 576 | let param = { ...fallback, ...evt.params }; 577 | 578 | log("param: %O", param); 579 | 580 | const validator = 581 | "Param" in module && module.Param instanceof z.ZodObject ? module.Param : z.object({}); 582 | const validation = validator.safeParse(param); 583 | if (!validation.success) { 584 | throw error(400, `Invalid param.\n${fromZodError(validation.error).message}`); 585 | } else { 586 | param = validation.data; 587 | } 588 | 589 | return param; 590 | } 591 | 592 | protected async parse_output( 593 | out: unknown, 594 | module: object, 595 | fallback?: Record, 596 | ): Promise> { 597 | let output: Record | unknown[] = Array.isArray(out) 598 | ? out 599 | : { 600 | ...fallback, 601 | ...(typeof out === "object" ? out : undefined), 602 | }; 603 | 604 | const validator = 605 | "Output" in module && module.Output instanceof z.ZodType ? module.Output : z.object({}); 606 | const validation = await validator.spa(output); 607 | if (!validation.success) { 608 | log.extend("error")("output: %O failed validation: %O", output, validation.error); 609 | throw error( 610 | 500, 611 | "Output validation failed. Please report this error to the developer.", 612 | ); 613 | } else { 614 | output = validation.data; 615 | } 616 | 617 | return output; 618 | } 619 | 620 | protected async parse_module(id: string): Promise<{ 621 | path: string; 622 | method: string; 623 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 624 | body?: z.ZodObject; 625 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 626 | query: z.ZodObject; 627 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 628 | param: z.ZodObject; 629 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 630 | output?: z.ZodObject; 631 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 632 | stream?: z.ZodObject; 633 | errors: HttpError[]; 634 | modifier: RouteModifier; 635 | }> { 636 | const handler = this.routes[id]; 637 | const parts = id.split("/"); 638 | const path = parts 639 | .slice(0, -1) 640 | .join("/") 641 | .replace(/^\./, this.base) 642 | .replace(/\[(\.{3})?(.+?)\]/g, "{$2}") 643 | .replace(/\(.+\)\//g, ""); 644 | const method = parts[parts.length - 1].toUpperCase(); 645 | 646 | let module = (await handler()) as APIRoute; 647 | if (!module || typeof module !== "object") { 648 | throw new Error(`Route ${id} is not a module`); 649 | } 650 | 651 | if (module.default instanceof Endpoint) { 652 | module = module.default; 653 | } else if (typeof module.default === "function") { 654 | // whole module is an endpoint 655 | } else { 656 | throw new Error(`Route ${id} is not a module`); 657 | } 658 | 659 | const body = 660 | "Input" in module && module.Input instanceof z.ZodType ? module.Input : undefined; 661 | const query = 662 | "Query" in module && module.Query instanceof z.ZodType ? module.Query : z.object({}); 663 | const param = 664 | "Param" in module && module.Param instanceof z.ZodType ? module.Param : z.object({}); 665 | const output = 666 | "Output" in module && module.Output instanceof z.ZodType ? module.Output : undefined; 667 | const stream = 668 | "Stream" in module && module.Stream instanceof z.ZodType ? module.Stream : undefined; 669 | const errors = 670 | "Error" in module && module.Error && typeof module.Error === "object" 671 | ? Object.values(module.Error) 672 | : []; 673 | const modifier = 674 | "Modifier" in module && typeof module.Modifier === "function" 675 | ? (module.Modifier as RouteModifier) 676 | : (r: RouteConfig) => r; 677 | 678 | return { 679 | path, 680 | method, 681 | body, 682 | query, 683 | param, 684 | output, 685 | stream, 686 | errors, 687 | modifier, 688 | }; 689 | } 690 | } 691 | -------------------------------------------------------------------------------- /src/lib/error.ts: -------------------------------------------------------------------------------- 1 | import type { HttpError } from "@sveltejs/kit"; 2 | import { error as e } from "@sveltejs/kit"; 3 | 4 | export function error(status: number, message: string): HttpError { 5 | try { 6 | return e(status, message); 7 | } catch (error) { 8 | return error as HttpError; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/lib/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./api.js"; 2 | export * from "./error.js"; 3 | export * from "./log.js"; 4 | export * from "./openapi.js"; 5 | export * from "./zod.js"; 6 | -------------------------------------------------------------------------------- /src/lib/log.ts: -------------------------------------------------------------------------------- 1 | import debug from "debug"; 2 | 3 | export const log = debug("api"); 4 | -------------------------------------------------------------------------------- /src/lib/openapi.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-explicit-any */ 2 | import type { RouteConfig } from "@asteasolutions/zod-to-openapi"; 3 | import { 4 | OpenAPIRegistry, 5 | OpenApiGeneratorV3 as _OpenApiGeneratorV3, 6 | } from "@asteasolutions/zod-to-openapi"; 7 | 8 | export const OpenApiGeneratorV3: any = _OpenApiGeneratorV3; 9 | export { OpenAPIRegistry, RouteConfig }; 10 | -------------------------------------------------------------------------------- /src/lib/utils.ts: -------------------------------------------------------------------------------- 1 | export function recursive_await(obj: unknown): unknown { 2 | if (obj instanceof Promise) { 3 | return obj.then(recursive_await); 4 | } else if (obj instanceof Array) { 5 | return Promise.all(obj.map(recursive_await)); 6 | } else if (obj instanceof Object) { 7 | const keys = Object.keys(obj); 8 | const values = Object.values(obj); 9 | return Promise.all(values.map(recursive_await)).then((values) => { 10 | const returns: Record = {}; 11 | for (let i = 0; i < keys.length; i++) { 12 | returns[keys[i]] = values[i]; 13 | } 14 | return returns; 15 | }); 16 | } else { 17 | return obj; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/lib/zod.ts: -------------------------------------------------------------------------------- 1 | import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi"; 2 | import { z } from "zod"; 3 | 4 | extendZodWithOpenApi(z); 5 | 6 | export { z }; 7 | -------------------------------------------------------------------------------- /src/routes/(group)/api/group/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = (evt) => api.handle(evt); 4 | -------------------------------------------------------------------------------- /src/routes/(group)/api/group/[param]/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = (evt) => api.handle(evt); 4 | -------------------------------------------------------------------------------- /src/routes/+page.svelte: -------------------------------------------------------------------------------- 1 |

SvelteKit-API

2 |

Utilities to create API endpoints in SvelteKit.

3 |

4 | Visit JacobLinCool/sveltekit-api to read 5 | the code 6 |

7 | -------------------------------------------------------------------------------- /src/routes/api/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | import { json } from "@sveltejs/kit"; 3 | 4 | export const prerender = true; 5 | 6 | export const GET = async (evt) => json(await api.openapi(evt)); 7 | -------------------------------------------------------------------------------- /src/routes/api/async/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = async (evt) => api.handle(evt); 4 | -------------------------------------------------------------------------------- /src/routes/api/post/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = async (evt) => api.handle(evt); 4 | export const POST = async (evt) => api.handle(evt); 5 | export const OPTIONS = async (evt) => api.handle(evt); 6 | -------------------------------------------------------------------------------- /src/routes/api/post/[...id]/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = async (evt) => api.handle(evt); 4 | export const PUT = async (evt) => api.handle(evt); 5 | export const OPTIONS = async (evt) => api.handle(evt); 6 | -------------------------------------------------------------------------------- /src/routes/api/post/search/+server.ts: -------------------------------------------------------------------------------- 1 | import api from "$api/index.js"; 2 | 3 | export const GET = async (evt) => api.handle(evt); 4 | -------------------------------------------------------------------------------- /static/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacobLinCool/sveltekit-api/a6d7b7078f47b88579744610bf5ec25016e1b686/static/favicon.png -------------------------------------------------------------------------------- /svelte.config.js: -------------------------------------------------------------------------------- 1 | import adapter from "@sveltejs/adapter-auto"; 2 | import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; 3 | 4 | /** @type {import('@sveltejs/kit').Config} */ 5 | const config = { 6 | // Consult https://kit.svelte.dev/docs/integrations#preprocessors 7 | // for more information about preprocessors 8 | preprocess: vitePreprocess(), 9 | 10 | kit: { 11 | // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. 12 | // If your environment is not supported or you settled on a specific environment, switch out the adapter. 13 | // See https://kit.svelte.dev/docs/adapters for more information about adapters. 14 | adapter: adapter(), 15 | alias: { 16 | $api: "./src/api", 17 | }, 18 | }, 19 | }; 20 | 21 | export default config; 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./.svelte-kit/tsconfig.json", 3 | "compilerOptions": { 4 | "allowJs": true, 5 | "checkJs": true, 6 | "esModuleInterop": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "resolveJsonModule": true, 9 | "skipLibCheck": true, 10 | "sourceMap": true, 11 | "strict": true, 12 | "moduleResolution": "NodeNext", 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { sveltekit } from "@sveltejs/kit/vite"; 2 | import { defineConfig } from "vite"; 3 | 4 | export default defineConfig({ 5 | plugins: [sveltekit()], 6 | }); 7 | --------------------------------------------------------------------------------