@softistx/alxia-openapi 0.0.0-stage → 0.7.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 Steve Tsala
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 CHANGED
@@ -1,3 +1,269 @@
1
- # Temporary Holding Version
1
+ # @softistx/alxia-openapi
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
+ > Moved from `@alxia/openapi`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
4
+
5
+ OpenAPI spec first for [`@softistx/alxia`](https://www.npmjs.com/package/@softistx/alxia).
6
+ The OpenAPI document is the source:
7
+ [`@nxgt/openapi-codegen`](https://www.npmjs.com/package/@nxgt/openapi-codegen)'s
8
+ `alxia` option generates each operation as `{ method, path, schema }`,
9
+ `@softistx/alxia`'s `app.route(operation, ...middlewares, handler)` binds a
10
+ handler to it, and this package's `implemented` and `matchesSpec` check
11
+ that the app routes every operation of the document (and, with
12
+ `strict: true`, only those). A route the document declares and nobody wrote
13
+ fails a test, not a client.
14
+
15
+ ```sh
16
+ bun add -d @softistx/alxia-openapi typescript
17
+ bun add -d --exact @nxgt/openapi-codegen
18
+ bun add zod
19
+ ```
20
+
21
+ `@softistx/alxia` and `typescript` are its peers; `@softistx/alxia` is the app's
22
+ own dependency. `@nxgt/openapi-codegen` writes the operations, and the code
23
+ it writes imports `zod` (4.5.4 or later) at runtime. For a check at startup
24
+ rather than in a test, install `@softistx/alxia-openapi` without `-d`.
25
+
26
+ `bunx @softistx/alxia-create my-api --template api` starts a project wired this way.
27
+
28
+ ## Spec first, end to end
29
+
30
+ Write `openapi.yaml` — here with a `listTodos` and a `createTodo`
31
+ operation — then point the generator at it:
32
+
33
+ ```ts
34
+ // openapi-codegen.config.ts
35
+ import { defineConfig } from '@nxgt/openapi-codegen';
36
+
37
+ export default defineConfig({
38
+ input: 'openapi.yaml',
39
+ output: 'src/generated',
40
+ alxia: true, // writes src/generated/alxia.ts
41
+ validationErrors: false, // alxia sends its own 400: declare it in the spec
42
+ });
43
+ ```
44
+
45
+ ```sh
46
+ bunx nxgt-openapi generate # writes src/generated/, alxia.ts included
47
+ ```
48
+
49
+ Bind each operation to its handler, with the middlewares it needs:
50
+
51
+ ```ts
52
+ // src/app.ts
53
+ import { alxia, defineMiddleware } from '@softistx/alxia';
54
+ import { operations } from './generated/alxia';
55
+ import type { Todo } from './generated/types';
56
+
57
+ const requireKey = defineMiddleware(({ request, reply }, next) =>
58
+ request.headers.get('x-api-key') === Bun.env['API_KEY']
59
+ ? next()
60
+ : reply(401, { error: 'unauthorized' as const }),
61
+ );
62
+
63
+ const todos: Todo[] = [];
64
+
65
+ export const app = alxia()
66
+ .route(operations.listTodos, ({ reply }) => reply.ok(todos))
67
+ .route(operations.createTodo, requireKey, ({ body, reply }) => {
68
+ const todo = { id: todos.length + 1, title: body.title, done: false };
69
+ todos.push(todo);
70
+ return reply.created(todo);
71
+ });
72
+ ```
73
+
74
+ And check the app against the same operations:
75
+
76
+ ```ts
77
+ // src/app.spec.ts
78
+ import { test } from 'bun:test';
79
+ import { matchesSpec } from '@softistx/alxia-openapi';
80
+ import { app } from './app';
81
+ import { operations } from './generated/alxia';
82
+
83
+ test('routes every operation of openapi.yaml', () => {
84
+ matchesSpec(app, operations);
85
+ });
86
+ ```
87
+
88
+ The [spec-first guide](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/spec-first.md)
89
+ walks through every step: the document, alxia's own 400, middlewares,
90
+ committing the generated files, and a client from the same document.
91
+
92
+ ## API docs
93
+
94
+ `apiDocs` serves the document and an interactive page for it, with no
95
+ configuration. The page loads from a CDN, with a pinned version and a
96
+ subresource integrity hash, so nothing is added to your dependencies.
97
+
98
+ ```ts
99
+ import { alxia } from '@softistx/alxia';
100
+ import { apiDocs } from '@softistx/alxia-openapi';
101
+ import spec from '../openapi.yaml'; // Bun imports YAML, and bundles it
102
+
103
+ const app = alxia().plugin(apiDocs({ spec }));
104
+ // GET /docs the page (Scalar)
105
+ // GET /docs/openapi.yaml the document
106
+ // GET /docs/openapi.json the same, as JSON
107
+ ```
108
+
109
+ `spec` is the document as an object — imported, as above, so `bun build`
110
+ bundles it and an image that holds `dist/` alone still serves it — or a
111
+ path to a YAML or JSON file, read once at startup from the working
112
+ directory. Options: `path` (`/docs`), `ui` (`'scalar'` or `'swagger'`),
113
+ `title`, `servers` (replaces the document's) and `enabled`. The document is
114
+ public unless you guard it: to serve it in development alone, read the
115
+ environment at runtime, with `Bun.env` —
116
+ `apiDocs({ spec, enabled: Bun.env.NODE_ENV === 'development' })` —
117
+ never `process.env.NODE_ENV`, which `bun build` replaces with the mode of
118
+ the build; to keep it behind a login, give the guard to `use('/docs', …)`
119
+ before the plugin. The page sets its own `Content-Security-Policy`, which
120
+ `secureHeaders` keeps, and `matchesSpec` leaves its routes out. The
121
+ [guide](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/api-docs.md)
122
+ has the options, the policy, a guarded page, and `apiDocs` beside a GraphQL
123
+ endpoint.
124
+
125
+ ## Every operation has a route
126
+
127
+ ```ts
128
+ import { implemented } from '@softistx/alxia-openapi';
129
+
130
+ implemented(app, operations); // routes the app serves beside the spec are fine
131
+ ```
132
+
133
+ When some are missing, it throws, naming each by method, path and operation id:
134
+
135
+ ```text
136
+ TypeError: implemented(): 2 operations have no route: GET /pets/:petId (getPet), QUERY /employees (searchEmployees)
137
+ ```
138
+
139
+ ## Only the operations
140
+
141
+ ```ts
142
+ import { matchesSpec } from '@softistx/alxia-openapi';
143
+
144
+ const { extra } = matchesSpec(app, operations);
145
+ ```
146
+
147
+ `matchesSpec` throws as `implemented` does: on each operation with no route,
148
+ and so on a route of another method or path. A route no operation declares
149
+ (a proxied one, a health check, a hand-written one) does not fail; it is
150
+ returned as `extra`, `[{ method, path }]`, so a test can assert on it. An
151
+ `app.all(path, …)` route serves no operation, and is listed as
152
+ `{ method: 'ALL', path }`.
153
+
154
+ For a spec that must be exhaustive, pass `strict: true`: each route no
155
+ operation declares fails too, `exclude` aside. The routes of `apiDocs()`
156
+ and the probes of `@softistx/alxia`'s `health()` are left out already:
157
+
158
+ ```ts
159
+ matchesSpec(app, operations, {
160
+ strict: true,
161
+ exclude: (route) => route.path === '/metrics',
162
+ });
163
+ ```
164
+
165
+ ```text
166
+ TypeError: matchesSpec(): 1 operation has no route: GET /pets/:petId (getPet); 1 route has no operation: POST /admin/reset
167
+ ```
168
+
169
+ Upgrading from before this check was lenient: to keep the old check, pass
170
+ `strict: true`.
171
+
172
+ ## Under a prefix
173
+
174
+ ```ts
175
+ implemented(app, operations, { prefix: '/api' });
176
+ ```
177
+
178
+ For details about prefixes and how routes are matched, see [matching.md](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/matching.md#under-a-prefix). The checks read `app.routes` and nothing else: they send no request, and check no schema.
179
+
180
+ ## Routes with middlewares
181
+
182
+ `app.route(operation, ...middlewares, handler)` validates the request and
183
+ checks the handler's reply just before the handler, or where
184
+ `validate(operation)` and `responds(operation)` stand. A middleware's own
185
+ reply, such as an auth's 401, is sent as it is. The checks match such a
186
+ route as any other, by method and path:
187
+
188
+ ```ts
189
+ import { alxia, validate } from '@softistx/alxia';
190
+ import { operations } from './generated/alxia';
191
+
192
+ // requireKey, todos: as above
193
+ export const app = alxia()
194
+ .route(operations.listTodos, ({ reply }) => reply.ok(todos))
195
+ .route(
196
+ operations.createTodo,
197
+ requireKey, // first: an anonymous client gets its 401 before the body is read
198
+ validate(operations.createTodo),
199
+ ({ body, reply }) => reply.created({ id: todos.length + 1, title: body.title, done: false }),
200
+ );
201
+ ```
202
+
203
+ Put the key check before `validate(...)`: auth first, so an anonymous client
204
+ gets no body parsed, up to `bodyLimit`, and no validation issues back, which
205
+ would reveal the schema.
206
+
207
+ ## Traps
208
+
209
+ - `validationErrors` defaults to `true`, which declares in the client-facing
210
+ files a 400 alxia never sends: set `validationErrors: false` and declare
211
+ alxia's `{ error: 'validation', issues }` in the spec.
212
+ - The generator does not turn `security` into a middleware: write one with
213
+ `defineMiddleware` and give it to `route(operation, auth, handler)`.
214
+ - In `@nxgt/openapi-codegen` 0.11.0, a `cookie` parameter is validated as
215
+ `cookies` by `alxia.ts` alone: the client files leave it out with an
216
+ `ignored` warning, since a client does not set cookies. A cookie that is a
217
+ list or an object fails the run.
218
+
219
+ ## Coming from `@alxia/openapi` 0.3 or `@alxia/openapi-routes`
220
+
221
+ **`@alxia/openapi` 0.1 to 0.3** was another package: it wrote a document
222
+ from the app's routes (`openapi`, `docs`, `toJsonSchema`). It is retired,
223
+ since the document now comes first, and 0.4 has none of its exports. Save
224
+ the document it served, the app's `/openapi.json`, as the starting point
225
+ of your own (the generator reads JSON as well as YAML), generate the
226
+ operations from it, and bind the routes with `app.route()`.
227
+
228
+ **`@alxia/openapi-routes`** was this package under its former name, and is
229
+ removed from the repository. Move to `@softistx/alxia-openapi`: the same
230
+ functions, options and messages, except that `exactly` and `ExactlyOptions`,
231
+ its deprecated aliases of `matchesSpec` and `MatchesSpecOptions`, are gone
232
+ at 0.5.
233
+
234
+ ```sh
235
+ bun remove @alxia/openapi-routes
236
+ bun add -d @softistx/alxia-openapi
237
+ ```
238
+
239
+ ```ts no-check
240
+ // before
241
+ import { implemented, matchesSpec } from '@alxia/openapi-routes';
242
+ // after
243
+ import { implemented, matchesSpec } from '@softistx/alxia-openapi';
244
+ ```
245
+
246
+ The core's side of the move is in its
247
+ [upgrading notes](https://github.com/softistx/alxia/blob/develop/packages/core/docs/upgrading.md#no-more-client-spec-first).
248
+
249
+ ## API
250
+
251
+ | export | |
252
+ | --- | --- |
253
+ | `implemented(app, operations, options?)`, `ImplementedOptions` | throws a `TypeError` listing each operation with no route, or one with the core's reason for an operation path no route may be declared at. `prefix` |
254
+ | `matchesSpec(app, operations, options?)`, `MatchesSpecOptions`, `MatchesSpecReport` | the same, and returns `{ extra }`, the routes no operation declares; `apiDocs()`'s and `@softistx/alxia`'s `health()` probes left out; under `strict: true` the rest throw instead. `prefix`, `strict`, `exclude` |
255
+ | `apiDocs(options)`, `ApiDocsOptions`, `DocsUi`, `DocsServer` | a plugin: the page at `path`, the document at `path/openapi.yaml` and `.json`. `spec`, `path`, `ui`, `title`, `servers`, `enabled` |
256
+ | `isApiDocsRoute(route)` | whether `apiDocs` declared a route, given any `{ handler }` (`Pick<RouteDefinition, 'handler'>`, as core's `isHealthRoute`); `matchesSpec` leaves them out already |
257
+ | `Operations` | what both take: an object of core's `RouteOperation`, or a list of them |
258
+
259
+ ## Documentation
260
+
261
+ - [Documentation index](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/README.md): every page, and when to read it.
262
+ - [Spec first](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/spec-first.md): the whole workflow, from `openapi.yaml` to the generated operations, the routes, the check and a client.
263
+ - [Testing with the generated client](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/testing.md): `@nxgt/openapi-httpyz` over `app.fetch`, in process, typed by the spec.
264
+ - [API docs](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/api-docs.md): `apiDocs`, its options, the Content-Security-Policy, and beside a GraphQL endpoint.
265
+ - [The checks](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/checks.md): `implemented` and `matchesSpec`, and the routes to exclude.
266
+ - [How routes are matched](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/matching.md): the path's shape, prefixes, and special cases.
267
+ - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/troubleshooting.md): each message of the checks and the generator, and what to do about it.
268
+ - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/roadmap.md): what is coming, and what is not planned.
269
+ - [Recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md): [A spec-first CRUD API](https://github.com/softistx/alxia/blob/develop/docs/recipes/spec-first-crud.md), [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md), [Answer errors consistently](https://github.com/softistx/alxia/blob/develop/docs/recipes/errors.md).
@@ -0,0 +1,20 @@
1
+ /** A server of the document, as OpenAPI declares it. */
2
+ export interface DocsServer {
3
+ readonly url: string;
4
+ readonly description?: string;
5
+ }
6
+ /** The document, parsed once, and as the two files serve it. */
7
+ export interface LoadedSpec {
8
+ readonly json: string;
9
+ readonly yaml: string;
10
+ /** The origins of its absolute `servers`: what "Try it out" may call. */
11
+ readonly origins: readonly string[];
12
+ }
13
+ /**
14
+ * Reads `spec`: an object, or a path to a YAML or JSON file, read once,
15
+ * relative to the working directory. `servers` replaces the document's.
16
+ * Throws a `TypeError` naming `apiDocs()`, at startup, rather than serve a
17
+ * page that shows nothing.
18
+ */
19
+ export declare function loadSpec(spec: string | object, servers: readonly DocsServer[] | undefined): LoadedSpec;
20
+ //# sourceMappingURL=api-docs-spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-docs-spec.d.ts","sourceRoot":"","sources":["../src/api-docs-spec.ts"],"names":[],"mappings":"AAEA,wDAAwD;AACxD,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,gEAAgE;AAChE,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CACvB,IAAI,EAAE,MAAM,GAAG,MAAM,EACrB,OAAO,EAAE,SAAS,UAAU,EAAE,GAAG,SAAS,GACxC,UAAU,CAyBZ"}
@@ -0,0 +1,22 @@
1
+ /** The two interactive pages, loaded from a CDN: pinned, and checked by SRI. */
2
+ export type DocsUi = 'scalar' | 'swagger';
3
+ /** Text in an HTML body or a quoted attribute. */
4
+ export declare function escapeHtml(text: string): string;
5
+ /** A fresh nonce for one page: 128 random bits. */
6
+ export declare function freshNonce(): string;
7
+ /**
8
+ * The page's own policy, which `secureHeaders` keeps (a header a route set
9
+ * is kept, as for `@softistx/alxia-graphql`'s IDE): the pinned version's scripts
10
+ * and styles alone, the one inline script of Swagger UI by its nonce, and
11
+ * nothing else. Requests go to this server — the spec — and to the
12
+ * `origins` of the document's servers, which "Try it out" calls.
13
+ */
14
+ export declare function policy(ui: DocsUi, nonce: string, origins: readonly string[]): string;
15
+ export interface PageOptions {
16
+ readonly title: string;
17
+ /** Where the page reads the spec: a URL path, JSON. */
18
+ readonly specUrl: string;
19
+ readonly nonce: string;
20
+ }
21
+ export declare function page(ui: DocsUi, options: PageOptions): string;
22
+ //# sourceMappingURL=api-docs-ui.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-docs-ui.d.ts","sourceRoot":"","sources":["../src/api-docs-ui.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAEhF,MAAM,MAAM,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;AAyB1C,kDAAkD;AAClD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAM/C;AAED,mDAAmD;AACnD,wBAAgB,UAAU,IAAI,MAAM,CAInC;AAKD;;;;;;GAMG;AACH,wBAAgB,MAAM,CACrB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,SAAS,MAAM,EAAE,GACxB,MAAM,CAeR;AAkBD,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,uDAAuD;IACvD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAED,wBAAgB,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,MAAM,CAE7D"}
@@ -0,0 +1,34 @@
1
+ import { type RouteDefinition } from '@softistx/alxia';
2
+ import { type DocsServer } from './api-docs-spec';
3
+ import { type DocsUi } from './api-docs-ui';
4
+ export type { DocsServer, DocsUi };
5
+ export interface ApiDocsOptions {
6
+ /** The OpenAPI document: a path to a YAML or JSON file, read once at startup, or the object. */
7
+ readonly spec: string | object;
8
+ /** Where the page is served; the spec is at `${path}/openapi.yaml` and `.json`. Defaults to `/docs`. */
9
+ readonly path?: `/${string}`;
10
+ /** `'scalar'` (default) or `'swagger'`, loaded from a pinned CDN version. */
11
+ readonly ui?: DocsUi;
12
+ /** The page's title. Defaults to the document's `info.title`, else "API documentation". */
13
+ readonly title?: string;
14
+ /** Replaces the document's `servers`, in the page and in both files. */
15
+ readonly servers?: readonly DocsServer[];
16
+ /** `false` mounts nothing. Defaults to `true`. */
17
+ readonly enabled?: boolean;
18
+ }
19
+ /**
20
+ * Whether `apiDocs()` declared this route: the page and the two files.
21
+ * `matchesSpec` already leaves them out; this is for a check of your own.
22
+ */
23
+ export declare function isApiDocsRoute(route: Pick<RouteDefinition, 'handler'>): boolean;
24
+ /**
25
+ * An interactive page for the OpenAPI document, and the document itself:
26
+ * `GET /docs`, `GET /docs/openapi.yaml` and `GET /docs/openapi.json`. The
27
+ * page sets its own `Content-Security-Policy`, which `secureHeaders` keeps.
28
+ *
29
+ * ```ts
30
+ * app.plugin(apiDocs({ spec: 'openapi.yaml' }));
31
+ * ```
32
+ */
33
+ export declare function apiDocs(options: ApiDocsOptions): import("@softistx/alxia").Alxia<import("@softistx/alxia").Empty, "">;
34
+ //# sourceMappingURL=api-docs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-docs.d.ts","sourceRoot":"","sources":["../src/api-docs.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,eAAe,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,KAAK,UAAU,EAAY,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAE,KAAK,MAAM,EAA4B,MAAM,eAAe,CAAC;AAEtE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;AAEnC,MAAM,WAAW,cAAc;IAC9B,gGAAgG;IAChG,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,wGAAwG;IACxG,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,EAAE,CAAC;IAC7B,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IACrB,2FAA2F;IAC3F,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,wEAAwE;IACxE,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IACzC,kDAAkD;IAClD,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC3B;AAOD;;;GAGG;AACH,wBAAgB,cAAc,CAC7B,KAAK,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,CAAC,GACrC,OAAO,CAET;AAED;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CAAC,OAAO,EAAE,cAAc,wEAiC9C"}
@@ -0,0 +1,3 @@
1
+ export { type ApiDocsOptions, apiDocs, type DocsServer, type DocsUi, isApiDocsRoute, } from './api-docs';
2
+ export { type ImplementedOptions, implemented, type MatchesSpecOptions, type MatchesSpecReport, matchesSpec, type Operations, } from './routes';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,OAAO,EACP,KAAK,UAAU,EACf,KAAK,MAAM,EACX,cAAc,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACN,KAAK,kBAAkB,EACvB,WAAW,EACX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,WAAW,EACX,KAAK,UAAU,GACf,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,255 @@
1
+ // src/api-docs.ts
2
+ import {
3
+ alxia,
4
+ markFactory
5
+ } from "@softistx/alxia";
6
+
7
+ // src/api-docs-spec.ts
8
+ import { readFileSync } from "node:fs";
9
+ function loadSpec(spec, servers) {
10
+ let text;
11
+ let document = spec;
12
+ if (typeof spec === "string") {
13
+ text = read(spec);
14
+ document = parse(spec, text);
15
+ }
16
+ if (typeof document !== "object" || document === null || Array.isArray(document) || typeof document.openapi !== "string") {
17
+ throw new TypeError(`apiDocs(): ${typeof spec === "string" ? `"${spec}"` : "the spec"} is not an OpenAPI document: it has no "openapi" version`);
18
+ }
19
+ const final = servers ? { ...document, servers } : document;
20
+ const json = JSON.stringify(final, null, 2);
21
+ const yaml = text !== undefined && servers === undefined && !isJson(text) ? text : Bun.YAML.stringify(final, null, 2);
22
+ return { json, yaml, origins: originsOf(final) };
23
+ }
24
+ function originsOf(document) {
25
+ const servers = document.servers;
26
+ if (!Array.isArray(servers))
27
+ return [];
28
+ const origins = new Set;
29
+ for (const server of servers) {
30
+ const url = server?.url;
31
+ if (typeof url !== "string" || url.includes("{"))
32
+ continue;
33
+ if (!/^https?:\/\//i.test(url))
34
+ continue;
35
+ try {
36
+ origins.add(new URL(url).origin);
37
+ } catch {}
38
+ }
39
+ return [...origins];
40
+ }
41
+ function read(path) {
42
+ try {
43
+ return readFileSync(path, "utf8");
44
+ } catch (error) {
45
+ const code = error.code;
46
+ throw new TypeError(`apiDocs(): cannot read the spec "${path}" (${code ?? "unreadable"}), looked up from the working directory ${process.cwd()}`, { cause: error });
47
+ }
48
+ }
49
+ function isJson(text) {
50
+ return /^\s*[{[]/.test(text);
51
+ }
52
+ function parse(path, text) {
53
+ try {
54
+ return isJson(text) ? JSON.parse(text) : Bun.YAML.parse(text);
55
+ } catch (error) {
56
+ throw new TypeError(`apiDocs(): "${path}" is neither valid YAML nor valid JSON: ${error.message}`, { cause: error });
57
+ }
58
+ }
59
+
60
+ // src/api-docs-ui.ts
61
+ var CDN = "https://cdn.jsdelivr.net";
62
+ var FILES = {
63
+ scalar: `${CDN}/npm/@scalar/api-reference@1.72.4/`,
64
+ swagger: `${CDN}/npm/swagger-ui-dist@5.33.1/`
65
+ };
66
+ var SCALAR = {
67
+ src: `${FILES.scalar}dist/browser/standalone.js`,
68
+ integrity: "sha384-omTRdD9MbjA1vm12DqRUVvqJlr3VzSixvAdF1Jruu9AJOiJKyTKraIB6DyX+m10M"
69
+ };
70
+ var SWAGGER = {
71
+ script: `${FILES.swagger}swagger-ui-bundle.js`,
72
+ scriptIntegrity: "sha384-ZPehFMQommnnuaZ4rpxgkgTT2DKFVp4hZC/7pLit+9Lek9T1YGSo23eHFbvNkXkw",
73
+ css: `${FILES.swagger}swagger-ui.css`,
74
+ cssIntegrity: "sha384-Ov4/wv3j2bmct8cDc5X4ngJZohVPzEmc6uDPH8WeljUxO5vtoykvMEfbu9Vh6RaW"
75
+ };
76
+ function escapeHtml(text) {
77
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
78
+ }
79
+ function freshNonce() {
80
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64");
81
+ }
82
+ var SCALAR_FONTS = "https://fonts.scalar.com";
83
+ function policy(ui, nonce, origins) {
84
+ const files = FILES[ui];
85
+ const fonts = ui === "scalar" ? ` ${SCALAR_FONTS}` : "";
86
+ return [
87
+ "default-src 'none'",
88
+ `script-src ${files} 'nonce-${nonce}'`,
89
+ `style-src ${files} 'unsafe-inline'`,
90
+ "img-src https: data:",
91
+ `font-src data:${fonts}`,
92
+ ["connect-src 'self'", ...origins].join(" "),
93
+ "worker-src blob:",
94
+ "base-uri 'none'",
95
+ "form-action 'none'",
96
+ "frame-ancestors 'none'"
97
+ ].join("; ");
98
+ }
99
+ function scalarConfiguration(url) {
100
+ return JSON.stringify({
101
+ url,
102
+ agent: { disabled: true },
103
+ mcp: { disabled: true },
104
+ showDeveloperTools: "never",
105
+ telemetry: false
106
+ });
107
+ }
108
+ function page(ui, options) {
109
+ return ui === "swagger" ? swaggerPage(options) : scalarPage(options);
110
+ }
111
+ function scalarPage({ title, specUrl }) {
112
+ return `<!doctype html>
113
+ <html lang="en">
114
+ <head>
115
+ <meta charset="utf-8">
116
+ <meta name="viewport" content="width=device-width, initial-scale=1">
117
+ <title>${escapeHtml(title)}</title>
118
+ </head>
119
+ <body>
120
+ <script id="api-reference" data-configuration="${escapeHtml(scalarConfiguration(specUrl))}"></script>
121
+ <script src="${SCALAR.src}" integrity="${SCALAR.integrity}" crossorigin="anonymous"></script>
122
+ </body>
123
+ </html>
124
+ `;
125
+ }
126
+ function swaggerPage({ title, specUrl, nonce }) {
127
+ const url = JSON.stringify(specUrl).replaceAll("<", "\\u003c");
128
+ return `<!doctype html>
129
+ <html lang="en">
130
+ <head>
131
+ <meta charset="utf-8">
132
+ <meta name="viewport" content="width=device-width, initial-scale=1">
133
+ <title>${escapeHtml(title)}</title>
134
+ <link rel="stylesheet" href="${SWAGGER.css}" integrity="${SWAGGER.cssIntegrity}" crossorigin="anonymous">
135
+ </head>
136
+ <body>
137
+ <div id="swagger-ui"></div>
138
+ <script src="${SWAGGER.script}" integrity="${SWAGGER.scriptIntegrity}" crossorigin="anonymous"></script>
139
+ <script nonce="${nonce}">window.ui = SwaggerUIBundle({ url: ${url}, dom_id: '#swagger-ui' });</script>
140
+ </body>
141
+ </html>
142
+ `;
143
+ }
144
+
145
+ // src/api-docs.ts
146
+ var declared = new WeakSet;
147
+ function isApiDocsRoute(route) {
148
+ return declared.has(route.handler);
149
+ }
150
+ function apiDocs(options) {
151
+ const { path = "/docs", ui = "scalar", enabled = true } = options;
152
+ if (!/^\/.*[^/]$/.test(path)) {
153
+ throw new TypeError(`apiDocs(): the path "${path}" must start with "/" and not end with one`);
154
+ }
155
+ if (ui !== "scalar" && ui !== "swagger") {
156
+ throw new TypeError(`apiDocs(): ui "${ui}" is not "scalar" or "swagger"`);
157
+ }
158
+ const app = alxia();
159
+ if (!enabled)
160
+ return app;
161
+ const spec = loadSpec(options.spec, options.servers);
162
+ const title = options.title ?? titleOf(spec.json);
163
+ const html = ({ url, reply }) => {
164
+ const nonce = freshNonce();
165
+ const specUrl = `${url.pathname.replace(/\/+$/, "")}/openapi.json`;
166
+ return reply.html(200, page(ui, { title, specUrl, nonce }), {
167
+ headers: {
168
+ "content-security-policy": policy(ui, nonce, spec.origins)
169
+ }
170
+ });
171
+ };
172
+ const yaml = ({ reply }) => reply(200, spec.yaml, { headers: { "content-type": "application/yaml" } });
173
+ const json = ({ reply }) => reply(200, spec.json, { headers: { "content-type": "application/json" } });
174
+ for (const handler of [html, yaml, json])
175
+ declared.add(handler);
176
+ return app.get(path, html).get(`${path}/openapi.yaml`, yaml).get(`${path}/openapi.json`, json);
177
+ }
178
+ function titleOf(json) {
179
+ const info = JSON.parse(json).info;
180
+ return typeof info?.title === "string" && info.title !== "" ? info.title : "API documentation";
181
+ }
182
+ markFactory(apiDocs, "plugin");
183
+ // src/routes.ts
184
+ import {
185
+ isHealthRoute,
186
+ joinPath,
187
+ shapeOf
188
+ } from "@softistx/alxia";
189
+ function implemented(app, operations, options = {}) {
190
+ const missing = unrouted(app, wanted("implemented", operations, options.prefix));
191
+ if (missing.length > 0) {
192
+ throw new TypeError(`implemented(): ${noRoute(missing)}`);
193
+ }
194
+ }
195
+ function matchesSpec(app, operations, options = {}) {
196
+ return match("matchesSpec", app, operations, options);
197
+ }
198
+ function match(check, app, operations, options) {
199
+ const all = wanted(check, operations, options.prefix);
200
+ const missing = unrouted(app, all);
201
+ const declared = new Set(all.map(keyOf));
202
+ const undocumented = app.routes.filter((route) => !declared.has(keyOf(route)) && !isApiDocsRoute(route) && !isHealthRoute(route) && !(options.exclude?.(route) ?? false));
203
+ const extra = undocumented.map(({ method, path }) => ({ method, path }));
204
+ const parts = [];
205
+ if (missing.length > 0)
206
+ parts.push(noRoute(missing));
207
+ if (options.strict === true && undocumented.length > 0) {
208
+ parts.push(noOperation(undocumented));
209
+ }
210
+ if (parts.length > 0)
211
+ throw new TypeError(`${check}(): ${parts.join("; ")}`);
212
+ return { extra };
213
+ }
214
+ function wanted(check, operations, prefix = "") {
215
+ if (prefix !== "" && !/^\/.*[^/]$/.test(prefix)) {
216
+ throw new TypeError(`${check}(): the prefix "${prefix}" must start with "/" and not end with one`);
217
+ }
218
+ const named = Array.isArray(operations) ? operations.map((operation) => [
219
+ operation.schema?.detail?.operationId,
220
+ operation
221
+ ]) : Object.entries(operations);
222
+ return named.map(([name, operation]) => {
223
+ const path = joinPath(prefix, operation.path);
224
+ try {
225
+ shapeOf(path);
226
+ } catch (error) {
227
+ throw new TypeError(`${check}(): ${error.message}`);
228
+ }
229
+ return { method: operation.method, path, name };
230
+ });
231
+ }
232
+ function unrouted(app, all) {
233
+ const routed = new Set(app.routes.map(keyOf));
234
+ return all.filter((operation) => !routed.has(keyOf(operation)) && !(operation.method === "HEAD" && routed.has(keyOf({ ...operation, method: "GET" }))));
235
+ }
236
+ function keyOf(route) {
237
+ return `${route.method} ${shapeOf(route.path)}`;
238
+ }
239
+ function noRoute(missing) {
240
+ const list = missing.map(({ method, path, name }) => name === undefined ? `${method} ${path}` : `${method} ${path} (${name})`).join(", ");
241
+ return missing.length === 1 ? `1 operation has no route: ${list}` : `${missing.length} operations have no route: ${list}`;
242
+ }
243
+ function noOperation(extra) {
244
+ const list = extra.map(({ method, path }) => `${method} ${path}`).join(", ");
245
+ return extra.length === 1 ? `1 route has no operation: ${list}` : `${extra.length} routes have no operation: ${list}`;
246
+ }
247
+ export {
248
+ apiDocs,
249
+ implemented,
250
+ isApiDocsRoute,
251
+ matchesSpec
252
+ };
253
+
254
+ //# debugId=0D5EA892B6D0464864756E2164756E21
255
+ //# sourceMappingURL=index.js.map