@astro-spec/endpoints 0.0.0-0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 otoneko.
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.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @astro-spec/endpoints
2
+
3
+ > Describe Astro API routes with Zod and add them to the OpenAPI document
4
+
5
+ `defineEndpoint` checks the params, query string and body of an API route with Zod schemas before your handler runs, and adds the route to the document that [`@astro-spec/openapi`](../openapi#readme) serves, next to your actions.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @astro-spec/endpoints @astro-spec/openapi
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Use `defineEndpoint` for the method exports of a script in `src/pages`:
16
+
17
+ ```ts
18
+ // src/pages/api/users/[id].ts
19
+ import { defineEndpoint } from '@astro-spec/endpoints'
20
+ import { z } from 'astro/zod' // or 'astro:schema' on Astro 4
21
+
22
+ export const GET = defineEndpoint({
23
+ summary: 'Get a user',
24
+ tags: ['user'],
25
+ params: z.object({ id: z.string() }),
26
+ query: z.object({ fields: z.string().optional() }),
27
+ output: z.object({ id: z.string(), name: z.string() }),
28
+ errors: { 404: 'No user has this id.' },
29
+ handler: async ({ params, query }, context) => {
30
+ const user = await db.user.find(params.id)
31
+ return user ?? new Response(null, { status: 404 })
32
+ },
33
+ })
34
+
35
+ export const PATCH = defineEndpoint({
36
+ params: z.object({ id: z.string() }),
37
+ input: z.object({ name: z.string().min(1) }),
38
+ handler: async ({ params, input }) => {
39
+ await db.user.update(params.id, input)
40
+ },
41
+ })
42
+ ```
43
+
44
+ The first handler argument holds the parsed `params`, `query` and `input`, typed from the schemas. The second is Astro's usual `APIContext`.
45
+
46
+ The handler returns one of these:
47
+
48
+ - A value, sent as JSON with status 200.
49
+ - `undefined`, sent as an empty 204 response.
50
+ - A `Response`, sent as it is. Use it for errors and for any other status or format.
51
+
52
+ The path in the document comes from the file: `src/pages/api/users/[id].ts` becomes `/api/users/{id}`, with Astro's `base` and `trailingSlash` applied. Handlers written without `defineEndpoint` are left out of the document.
53
+
54
+ ## Options
55
+
56
+ | Option | Description |
57
+ | --- | --- |
58
+ | `params` | A schema for the route parameters, such as `id` in `[id].ts`. They arrive as strings, so use `z.coerce.number()` for numbers. |
59
+ | `query` | A schema for the query string. A key that appears once arrives as a string and a repeated key as an array of strings. |
60
+ | `input` | A schema for the request body. |
61
+ | `accept` | `'json'` (the default) reads the body as JSON; `'form'` reads it as form data, with repeated fields as arrays. |
62
+ | `output` | A schema for the value the handler returns. It types the handler and documents the 200 response, but the value is not checked. |
63
+ | `errors` | The error statuses the handler can respond with, each with a description, such as `{ 404: 'No user has this id.' }`. |
64
+ | `summary`, `description`, `tags`, `deprecated` | Documentation for the operation. |
65
+ | `operationId` | Defaults to the method and path, such as `GET /api/users/{id}`. |
66
+
67
+ ## Invalid input
68
+
69
+ When the params, query or body do not match their schema, or the body is not valid JSON, the endpoint answers 400 without running the handler:
70
+
71
+ ```json
72
+ {
73
+ "type": "EndpointInputError",
74
+ "in": "body",
75
+ "issues": [{ "path": ["name"], "message": "Too small: expected string to have >=1 characters" }],
76
+ "fields": { "name": ["Too small: expected string to have >=1 characters"] }
77
+ }
78
+ ```
79
+
80
+ `in` is `params`, `query` or `body`. The document describes this body as the `EndpointInputError` schema.
81
+
82
+ ## License
83
+
84
+ [MIT](https://github.com/betterlib/astro-spec/blob/main/LICENSE)
@@ -0,0 +1,85 @@
1
+ import { APIContext, APIRoute } from "astro";
2
+ /** Documentation for one endpoint handler, given to `defineEndpoint`. */
3
+ type EndpointSpecDetails = {
4
+ summary?: string;
5
+ description?: string;
6
+ deprecated?: boolean;
7
+ tags?: string[];
8
+ /** Defaults to the method and path, such as `GET /api/users/{id}`. */
9
+ operationId?: string;
10
+ /** The error statuses the handler can respond with, each with a description. */
11
+ errors?: Record<number, string>;
12
+ };
13
+ type Issue = {
14
+ path: PropertyKey[];
15
+ message: string;
16
+ };
17
+ /** A Zod 3 or Zod 4 schema, or anything else with Zod's `safeParseAsync`. */
18
+ type EndpointSchema = {
19
+ safeParseAsync: (value: unknown) => Promise<{
20
+ success: true;
21
+ data: unknown;
22
+ } | {
23
+ success: false;
24
+ error: {
25
+ issues: Issue[];
26
+ };
27
+ }>;
28
+ };
29
+ type Infer<S> = S extends {
30
+ safeParseAsync: (value: unknown) => Promise<infer Result>;
31
+ } ? Extract<Result, {
32
+ success: true;
33
+ }> extends {
34
+ data: infer Data;
35
+ } ? Data : never : undefined;
36
+ type MaybePromise<T> = T | Promise<T>;
37
+ type EndpointOptions<Params extends EndpointSchema | undefined, Query extends EndpointSchema | undefined, Input extends EndpointSchema | undefined, Output extends EndpointSchema | undefined> = EndpointSpecDetails & {
38
+ /** The route parameters, such as `id` in `[id].ts`. They arrive as strings. */
39
+ params?: Params;
40
+ /** The query string. A repeated key arrives as an array of strings, any other as a string. */
41
+ query?: Query;
42
+ /** The request body. */
43
+ input?: Input;
44
+ /** How the body is sent: `json` (the default) or `form` for form data. */
45
+ accept?: 'json' | 'form';
46
+ /** The value the handler returns, sent as JSON. Only documented, not checked. */
47
+ output?: Output;
48
+ /**
49
+ * Returns the value to send as JSON with status 200, `undefined` for an empty 204 response,
50
+ * or a `Response` to send as it is, such as an error.
51
+ */
52
+ handler: (data: {
53
+ params: Infer<Params>;
54
+ query: Infer<Query>;
55
+ input: Infer<Input>;
56
+ }, context: APIContext) => MaybePromise<Response | (Output extends EndpointSchema ? Infer<Output> : unknown)>;
57
+ };
58
+ /**
59
+ * Defines an endpoint handler that checks its params, query and body with Zod schemas, and adds
60
+ * itself to the OpenAPI document `@astro-spec/openapi` serves.
61
+ *
62
+ * Input that does not match answers 400 with `{ type: 'EndpointInputError', in, issues, fields }`
63
+ * before the handler runs. Use it for `GET`, `POST` and the other method exports of a script in
64
+ * `src/pages`.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * // src/pages/api/users/[id].ts
69
+ * import { defineEndpoint } from '@astro-spec/endpoints'
70
+ * import { z } from 'astro/zod'
71
+ *
72
+ * export const GET = defineEndpoint({
73
+ * summary: 'Get a user',
74
+ * params: z.object({ id: z.string() }),
75
+ * output: z.object({ id: z.string(), name: z.string() }),
76
+ * errors: { 404: 'No user has this id.' },
77
+ * handler: async ({ params }) => {
78
+ * const user = await db.findUser(params.id)
79
+ * return user ?? new Response(null, { status: 404 })
80
+ * },
81
+ * })
82
+ * ```
83
+ */
84
+ export declare const defineEndpoint: <Params extends EndpointSchema | undefined = undefined, Query extends EndpointSchema | undefined = undefined, Input extends EndpointSchema | undefined = undefined, Output extends EndpointSchema | undefined = undefined>(options: EndpointOptions<Params, Query, Input, Output>) => APIRoute;
85
+ export type { EndpointOptions, EndpointSchema };
package/dist/index.mjs ADDED
@@ -0,0 +1,100 @@
1
+ // ../core/src/endpoint-metadata.ts
2
+ /**
3
+ * The key under which an endpoint handler carries its astro-spec metadata. It comes from the
4
+ * global symbol registry so that copies of the packages in different bundles agree on it.
5
+ */
6
+ const ENDPOINT_METADATA = Symbol.for("astro-spec.endpoint");
7
+ const attachEndpointMetadata = (handler, metadata) => Object.assign(handler, { [ENDPOINT_METADATA]: metadata });
8
+ // src/define-endpoint.ts
9
+ const entriesToObject = (entries) => {
10
+ const object = {};
11
+ for (const [key, value] of entries) {
12
+ const existing = object[key];
13
+ object[key] = existing === void 0 ? value : [...Array.isArray(existing) ? existing : [existing], value];
14
+ }
15
+ return object;
16
+ };
17
+ const inputError = (location, issues) => Response.json({
18
+ type: "EndpointInputError",
19
+ in: location,
20
+ issues,
21
+ fields: Object.fromEntries(Array.from(Map.groupBy(issues.filter(({ path }) => path.length > 0), ({ path }) => String(path[0])), ([field, fieldIssues]) => [field, fieldIssues.map(({ message }) => message)]))
22
+ }, { status: 400 });
23
+ var InputError = class extends Error {
24
+ response;
25
+ constructor(location, issues) {
26
+ super(`Invalid ${location}`);
27
+ this.response = inputError(location, issues);
28
+ }
29
+ };
30
+ const validate = async (schema, read, location) => {
31
+ if (!schema) return void 0;
32
+ const result = await schema.safeParseAsync(await read());
33
+ if (!result.success) throw new InputError(location, result.error.issues);
34
+ return result.data;
35
+ };
36
+ const readBody = async (request, accept) => {
37
+ if (accept === "form") return entriesToObject(await request.formData());
38
+ const text = await request.text();
39
+ if (text === "") return void 0;
40
+ try {
41
+ return JSON.parse(text);
42
+ } catch {
43
+ throw new InputError("body", [{
44
+ path: [],
45
+ message: "The body is not valid JSON."
46
+ }]);
47
+ }
48
+ };
49
+ /**
50
+ * Defines an endpoint handler that checks its params, query and body with Zod schemas, and adds
51
+ * itself to the OpenAPI document `@astro-spec/openapi` serves.
52
+ *
53
+ * Input that does not match answers 400 with `{ type: 'EndpointInputError', in, issues, fields }`
54
+ * before the handler runs. Use it for `GET`, `POST` and the other method exports of a script in
55
+ * `src/pages`.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * // src/pages/api/users/[id].ts
60
+ * import { defineEndpoint } from '@astro-spec/endpoints'
61
+ * import { z } from 'astro/zod'
62
+ *
63
+ * export const GET = defineEndpoint({
64
+ * summary: 'Get a user',
65
+ * params: z.object({ id: z.string() }),
66
+ * output: z.object({ id: z.string(), name: z.string() }),
67
+ * errors: { 404: 'No user has this id.' },
68
+ * handler: async ({ params }) => {
69
+ * const user = await db.findUser(params.id)
70
+ * return user ?? new Response(null, { status: 404 })
71
+ * },
72
+ * })
73
+ * ```
74
+ */
75
+ const defineEndpoint = (options) => {
76
+ const { params, query, input, accept = "json", handler, ...details } = options;
77
+ const route = async (context) => {
78
+ try {
79
+ const data = {
80
+ params: await validate(params, async () => context.params, "params"),
81
+ query: await validate(query, async () => entriesToObject(new URL(context.request.url).searchParams), "query"),
82
+ input: await validate(input, () => readBody(context.request, accept), "body")
83
+ };
84
+ const result = await handler(data, context);
85
+ if (result instanceof Response) return result;
86
+ return result === void 0 ? new Response(null, { status: 204 }) : Response.json(result);
87
+ } catch (error) {
88
+ if (error instanceof InputError) return error.response;
89
+ throw error;
90
+ }
91
+ };
92
+ return attachEndpointMetadata(route, {
93
+ ...details,
94
+ accept,
95
+ params,
96
+ query,
97
+ input
98
+ });
99
+ };
100
+ export { defineEndpoint };
package/package.json CHANGED
@@ -1,10 +1,53 @@
1
1
  {
2
2
  "name": "@astro-spec/endpoints",
3
- "version": "0.0.0-0",
4
- "license": "MIT",
3
+ "version": "1.0.0",
4
+ "description": "Describe Astro API routes with Zod and add them to the OpenAPI document",
5
+ "keywords": [
6
+ "astro",
7
+ "openapi",
8
+ "astro-actions",
9
+ "zod",
10
+ "api-routes"
11
+ ],
12
+ "homepage": "https://github.com/betterlib/astro-spec/tree/main/packages/endpoints#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/betterlib/astro-spec/issues"
15
+ },
5
16
  "repository": {
6
17
  "type": "git",
7
18
  "url": "git+https://github.com/betterlib/astro-spec.git",
8
19
  "directory": "packages/endpoints"
20
+ },
21
+ "license": "MIT",
22
+ "author": "otoneko.",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.mts",
27
+ "default": "./dist/index.mjs"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.12.0"
36
+ },
37
+ "peerDependencies": {
38
+ "astro": "^4.15.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "provenance": true
43
+ },
44
+ "devDependencies": {
45
+ "astro": "^7.4.14",
46
+ "zod": "^4.6.7",
47
+ "@astro-spec/core": "1.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown",
51
+ "typecheck": "tsc --noEmit"
9
52
  }
10
- }
53
+ }