@lykosjs/openapi 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +371 -2
  3. package/package.json +57 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Zen Allaham - LykosJS - @lykosjs/openapi
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 ELYKOS 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,372 @@
1
- # Temporary Holding Version
1
+ # @lykosjs/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
+ Official **OpenAPI 3.1** documentation and **Swagger UI** for the LykosJS framework.
4
+
5
+ > Write your API documentation in one place. Let LykosJS handle the rest.
6
+
7
+ This package works with LykosJS only. It reads the routes that are really registered in your application, checks that your documentation matches them, generates the OpenAPI document once, and serves it (with Swagger UI) through LykosJS's own routing.
8
+
9
+ ## Features
10
+
11
+ - All endpoint documentation in a single constructor call; nothing is added to `GET` / `POST`.
12
+ - **Route discovery** from LykosJS's router (`app.readRoutes()`), no file scanning, no regex, no AST.
13
+ - **Strict validation**: a documented route must exist with the same method and path (parameter names included). All errors are reported at once.
14
+ - **OpenAPI 3.1.0** output, validated against the official OpenAPI 3.1 JSON Schema in the test suite.
15
+ - **Validator integration**: LykosJS validation schemas (`defineSchema` / `rules`) are converted to JSON Schema, so you write each schema once.
16
+ - Path, query and header parameters, request bodies (`application/json`, `application/x-www-form-urlencoded`, `multipart/form-data`), multiple responses per route.
17
+ - Security schemes: HTTP Bearer / JWT, API key (header or query), cookie.
18
+ - **Swagger UI served locally** (`swagger-ui-dist`), with a strict Content-Security-Policy. No CDN.
19
+ - The document is generated once; documentation requests never regenerate it.
20
+ - Strict TypeScript types, no `any` in the public API.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ bun add @lykosjs/openapi
26
+ ```
27
+
28
+ ## Requirements
29
+
30
+ - Bun >= 1.4 (developed and tested on Bun 1.4.4)
31
+ - `lykosjs` **1.0.0** (peer dependency)
32
+
33
+ > **Important:** `@lykosjs/openapi` requires LykosJS to expose its registered routes through the additive, read-only API `app.readRoutes()`, available in LykosJS 1.0.0. No patch or additional setup is required.
34
+ >
35
+ > With an older LykosJS, `setup()` fails immediately with a clear error that names the required version.
36
+
37
+ ## Basic usage
38
+
39
+ ```ts
40
+ import { Lykos } from 'lykosjs'
41
+ import { OpenAPIManager } from '@lykosjs/openapi'
42
+
43
+ const app = new Lykos()
44
+
45
+ app.GET('/users', (ctx, reply) => reply.json([]))
46
+ app.POST('/users', (ctx, reply) => reply.status(201).json({}))
47
+ app.GET('/users/:id', (ctx, reply) => reply.json({ id: ctx.params.id }))
48
+
49
+ const openapi = new OpenAPIManager({
50
+ info: {
51
+ title: 'HireHub API',
52
+ version: '1.0.0',
53
+ description: 'HireHub REST API Documentation',
54
+ },
55
+
56
+ docs: '/docs',
57
+ json: '/docs/json',
58
+
59
+ routes: {
60
+ getUsers: {
61
+ method: 'GET',
62
+ path: '/users',
63
+ summary: 'Get all users',
64
+ description: 'Returns all registered users',
65
+ tags: ['Users'],
66
+ response: { 200: { description: 'Users retrieved successfully' } },
67
+ },
68
+ createUser: {
69
+ method: 'POST',
70
+ path: '/users',
71
+ summary: 'Create a new user',
72
+ tags: ['Users'],
73
+ response: { 201: { description: 'User created successfully' } },
74
+ },
75
+ getUser: {
76
+ method: 'GET',
77
+ path: '/users/:id',
78
+ summary: 'Get user by ID',
79
+ response: { 200: { description: 'User found' } },
80
+ },
81
+ },
82
+ })
83
+
84
+ // After ALL application routes have been registered:
85
+ openapi.setup(app)
86
+
87
+ app.listen(4000)
88
+ // http://localhost:4000/docs Swagger UI
89
+ // http://localhost:4000/docs/json OpenAPI document
90
+ ```
91
+
92
+ A complete, runnable example is in [`examples/hirehub.ts`](./examples/hirehub.ts): `bun run examples/hirehub.ts`.
93
+
94
+ ## Configuration
95
+
96
+ ```ts
97
+ new OpenAPIManager({
98
+ info, // required: { title, version, description?, termsOfService?, contact?, license? }
99
+ routes, // required: Record<documentationKey, OpenAPIRoute> ({} is allowed)
100
+ docs: '/docs', // Swagger UI path, or false to disable. Default '/docs'
101
+ json: '/docs/json', // OpenAPI JSON path, or false to disable. Default '/docs/json'
102
+ servers, // optional: [{ url, description? }]
103
+ securitySchemes, // optional: see Authentication
104
+ middlewares, // optional: LykosJS middlewares applied to the documentation routes only
105
+ swaggerUI, // optional: { title?, persistAuthorization?, docExpansion? }
106
+ })
107
+ ```
108
+
109
+ - `docs` and `json` must be static paths (no parameters), different from each other. `json` cannot be disabled while `docs` is enabled (the UI reads it).
110
+ - Unknown properties anywhere in the configuration are rejected, so a typo like `summery` is an error, not silently ignored.
111
+ - The configuration is validated and copied in the constructor; all problems are reported together in one `OpenAPIValidationError`.
112
+
113
+ ### `setup()`, `generate()`, `getDocument()`
114
+
115
+ | Method | Behaviour |
116
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
117
+ | `setup(app)` | Strict validation, generates the document **once**, registers the documentation routes in `app` (`GET` only). Must be called **after** the application routes are registered. |
118
+ | `generate(app)` | Same validation and generation, but registers nothing. Returns a new document each call. |
119
+ | `getDocument()` | A copy of the document generated by `setup()`. Throws before `setup()`. Mutating the copy cannot affect what is served. |
120
+
121
+ Calling `setup()` again with the **same** application is a no-op (routes are never registered twice). Calling it with a **different** application throws; create one `OpenAPI` instance per application. If `setup()` throws (validation failed), nothing was registered and you can call it again after fixing the problem.
122
+
123
+ `OpenAPI` never creates a server; it adds routes to your LykosJS application and runs inside its lifecycle.
124
+
125
+ ## Route documentation
126
+
127
+ ```ts
128
+ routes: {
129
+ getUser: { // documentation key: becomes the operationId, never a path
130
+ method: 'GET', // GET | POST | PUT | PATCH | DELETE | HEAD
131
+ path: '/users/:id', // LykosJS style (:id) or OpenAPI style ({id})
132
+ summary: 'Get user by ID',
133
+ description: 'Markdown is allowed (rendered safely by Swagger UI)',
134
+ tags: ['Users'],
135
+ deprecated: false,
136
+ isRequired: true, // default true, see Strict validation
137
+ security: ['BearerAuth'],
138
+ request: { /* body | contentType | query | params | headers */ },
139
+ response: { 200: { description: 'User found' } },
140
+ },
141
+ }
142
+ ```
143
+
144
+ `OPTIONS` cannot be documented: LykosJS's HTTP server answers every `OPTIONS` request (CORS preflight) before routing, so such a route could never be reached. Trying to document one is a configuration error.
145
+
146
+ ## Strict validation
147
+
148
+ At `setup()` / `generate()` every documented route is compared with the registered routes, on **method and path**. Path parameters are compared by name: LykosJS `/users/:id` equals OpenAPI `/users/{id}`, but not `/users/{userId}`. Trailing slashes are normalized exactly like LykosJS's router does.
149
+
150
+ | Situation | Result |
151
+ | --------------------------------------------------------- | -------------------------------------- |
152
+ | Documented and registered | documented |
153
+ | Documented, not registered, `isRequired` true (default) | **error** |
154
+ | Documented, not registered, `isRequired: false` | no error, **left out of the document** |
155
+ | Registered, not documented | fine, not in the document |
156
+ | Same path, different method, or different parameter names | counts as not registered |
157
+
158
+ All problems are collected and thrown together:
159
+
160
+ ```text
161
+ [LykosJS OpenAPI] Strict Validation Failed
162
+
163
+ Missing registered routes (2):
164
+
165
+ Documentation Key: getUsers
166
+ Method: GET
167
+ Path: /users
168
+ Hint: this path is registered with: POST
169
+
170
+ Documentation Key: getUser
171
+ Method: GET
172
+ Path: /users/{userId}
173
+ Hint: parameter names must match exactly; LykosJS registered GET /users/:id
174
+
175
+ The documented endpoints were not registered in LykosJS.
176
+ ```
177
+
178
+ The documentation routes themselves are also checked: if `docs`, `json` or the asset paths collide with a registered `GET` route (including dynamic ones such as `/:slug`), `setup()` throws instead of taking over that path.
179
+
180
+ ## Request documentation
181
+
182
+ ```ts
183
+ request: {
184
+ body: CreateUserSchema, // requestBody
185
+ contentType: 'application/json', // default; or 'application/x-www-form-urlencoded' | 'multipart/form-data'
186
+ query: UserQuerySchema, // query parameters
187
+ params: UserParamsSchema, // refines the types of path parameters
188
+ headers: UserHeadersSchema, // header parameters
189
+ }
190
+ ```
191
+
192
+ - Path parameters are always extracted from `path` (type `string`, `required: true`). A `params` schema can refine their type; each is emitted once. A `params` field that is not in the path, or a nullable path parameter, is an error.
193
+ - Query and header parameters are `required` exactly when the schema field is `required`.
194
+ - The request body is `required` when at least one field is `required`.
195
+ - `GET` and `HEAD` cannot have a body. Header parameters named `Accept`, `Content-Type` or `Authorization` are rejected (OpenAPI ignores them); use `contentType` or `security`.
196
+
197
+ ## Response documentation
198
+
199
+ ```ts
200
+ response: {
201
+ 200: { description: 'OK', schema: UserSchema }, // JSON by default
202
+ 201: { description: 'Created', schema: UserSchema, contentType: 'application/vnd.api+json' },
203
+ 404: { description: 'Not found' }, // no content declared
204
+ }
205
+ ```
206
+
207
+ Content is declared only when you provide a `schema`; JSON is never assumed otherwise. Statuses `1xx`, `204` and `304` cannot have a schema. Status keys must be integers 100 to 599 (`default` and `2XX` ranges are not supported).
208
+
209
+ ## Validator integration
210
+
211
+ Pass the same schema you give to `Validator.validate`:
212
+
213
+ ```ts
214
+ import { defineSchema, Validator } from 'lykosjs'
215
+
216
+ const CreateUser = defineSchema({
217
+ name: Validator.string(2, 50).required(),
218
+ email: Validator.string(3, 50).email().required(),
219
+ })
220
+
221
+ // runtime validation
222
+ Validator.validate(data, CreateUser)
223
+ // documentation: request: { body: CreateUser }
224
+ ```
225
+
226
+ The converter describes what LykosJS's `Validator` actually enforces. It does not run validation.
227
+
228
+ | Validator rule | JSON Schema |
229
+ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------- |
230
+ | `required` | listed in `required` (and, for `string`, `minLength` is at least 1: the Validator rejects empty strings) |
231
+ | optional field | not in `required` |
232
+ | `nullable` | `type: [T, 'null']` (an `enum` also gets `null`) |
233
+ | `string` / `number` / `boolean` / `array` | `type` |
234
+ | `email` | `type: string`, `format: email` |
235
+ | `url` | `type: string`, `format: uri`, `pattern: ^https?://` |
236
+ | `enum:a,b` | `type: string`, `enum` |
237
+ | `minLength` / `maxLength` | `minLength` / `maxLength` |
238
+ | `min` / `max` on `number` | `minimum` / `maximum` |
239
+ | `min` / `max` on `string` | `minLength` / `maxLength` (that is what the Validator checks) |
240
+ | `minItems` / `maxItems` | `minItems` / `maxItems` |
241
+ | `confirmed` | adds the `<field>Confirmation` property the Validator compares against |
242
+
243
+ Anything that cannot be represented faithfully is an error, never silently dropped: unknown rules, incompatible type rules (`string` with `number`), limits on the wrong type (`minItems` on a string), `required` with `nullable`.
244
+
245
+ What the LykosJS Validator does not have is not inlykosed here: **no nested objects, no integer type, no item schemas for arrays and no custom rules** (the Validator throws on unknown rules, so they cannot be documented either).
246
+
247
+ The conversion happens once, in the constructor.
248
+
249
+ ## Authentication
250
+
251
+ Define schemes once, reference them per route. This library only _documents_ authentication; it never handles JWTs or stores tokens.
252
+
253
+ ```ts
254
+ new OpenAPIManager({
255
+ info,
256
+ securitySchemes: {
257
+ BearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
258
+ ApiKeyAuth: { type: 'apiKey', in: 'header', name: 'X-API-Key' },
259
+ CookieAuth: { type: 'apiKey', in: 'cookie', name: 'session' },
260
+ },
261
+ routes: {
262
+ me: {
263
+ method: 'GET',
264
+ path: '/me',
265
+ security: ['BearerAuth'],
266
+ response: { 200: { description: 'OK' } },
267
+ },
268
+ },
269
+ })
270
+ ```
271
+
272
+ Only routes with `security` are marked as protected. Listing several names means **any one of them** is accepted (OR). A route referencing an undeclared scheme is a configuration error.
273
+
274
+ ## Swagger UI
275
+
276
+ `GET /docs` serves Swagger UI from the bundled [`swagger-ui-dist`](https://www.npmjs.com/package/swagger-ui-dist) files through LykosJS. The page reads `GET /docs/json`.
277
+
278
+ - Everything is served by your application: `/docs/assets/swagger-ui.css`, `/docs/assets/swagger-ui-bundle.js`, `/docs/assets/init.js`. Only these three files exist; no request path is used to read files.
279
+ - The page has a `Content-Security-Policy` (`script-src 'self'`, `frame-ancestors 'none'`, ...). There are no inline scripts and no external requests (the online validator badge is disabled).
280
+ - Descriptions are never put into the HTML; Swagger UI renders them with its own sanitizer.
281
+ - The paths are configurable (`docs: '/api-docs', json: '/api-docs/json'`) and either can be turned off (`docs: false` keeps only the JSON).
282
+
283
+ ### Restricting access
284
+
285
+ The library does not inlykos an authentication system. Use LykosJS's middleware:
286
+
287
+ ```ts
288
+ import type { Context, NextFunc, Reply } from 'lykosjs'
289
+
290
+ const docsGuard = (ctx: Context, reply: Reply, next: NextFunc) =>
291
+ ctx.headers.get('x-docs-key') === process.env.DOCS_KEY
292
+ ? next()
293
+ : new Response('Unauthorized', { status: 401 })
294
+
295
+ new OpenAPIManager({ info, routes, middlewares: [docsGuard] }) // guards only the documentation routes
296
+ ```
297
+
298
+ Global middleware added with `use` **before** `setup()` also applies to the documentation routes (LykosJS attaches global middleware when a route is registered). To hide the documentation entirely, do not call `setup()` (for example in production).
299
+
300
+ ## OpenAPI JSON
301
+
302
+ `GET /docs/json` serves the pre-serialized document with `application/json; charset=utf-8` and `X-Content-Type-Options: nosniff`. The document is built once in `setup()`; requests only send the stored string.
303
+
304
+ ```json
305
+ {
306
+ "openapi": "3.1.0",
307
+ "info": { "title": "HireHub API", "version": "1.0.0" },
308
+ "paths": {
309
+ "/users": {
310
+ "get": {
311
+ "summary": "Get all users",
312
+ "tags": ["Users"],
313
+ "operationId": "getUsers",
314
+ "responses": { "200": { "description": "Users retrieved successfully" } }
315
+ }
316
+ }
317
+ }
318
+ }
319
+ ```
320
+
321
+ Documentation keys are used only as `operationId`; they never appear as paths.
322
+
323
+ ## Error handling
324
+
325
+ All configuration, validation and compatibility problems throw `OpenAPIValidationError`:
326
+
327
+ ```ts
328
+ import { OpenAPIManager, OpenAPIValidationError } from '@lykosjs/openapi'
329
+
330
+ try {
331
+ openapi.setup(app)
332
+ } catch (error) {
333
+ if (error instanceof OpenAPIValidationError) {
334
+ console.error(error.message) // formatted report
335
+ console.error(error.issues) // structured: 'config' | 'missing-route' | 'docs-conflict'
336
+ }
337
+ throw error
338
+ }
339
+ ```
340
+
341
+ Errors never include environment variables or secrets.
342
+
343
+ ## TypeScript support
344
+
345
+ The package ships declarations and uses no `any` in its public API. Schemas are typed with LykosJS's own `ValidationSchema`, so `defineSchema` / `rules` results are accepted and invalid rules are compile errors. Exported types: `OpenAPIOptions`, `OpenAPIRoute`, `OpenAPIRequest`, `OpenAPIResponse`, `OpenAPIResponses`, `OpenAPIMethod`, `OpenAPIInfo`, `OpenAPIServer`, `OpenAPISecurityScheme`, `OpenAPIDocument`, `SwaggerUIOptions`, `LykosJSSchema`, `JsonSchema`, `ValidationIssue`.
346
+
347
+ ## Examples
348
+
349
+ - [`examples/hirehub.ts`](./examples/hirehub.ts): routes, validator schemas, security, optional and deprecated routes.
350
+
351
+ ## Limitations
352
+
353
+ - Routes registered after `setup()` are not validated or documented. Call `setup()` last.
354
+ - Nested objects, integers, array item types, custom validation rules, response headers, response `default` / ranges, `OPTIONS` operations and OAuth2 / OpenID Connect are not supported, because LykosJS's Validator or server does not provide them or they are outside the current scope.
355
+ - `application/x-www-form-urlencoded` and `multipart/form-data` fields reach handlers as strings. LykosJS's Validator checks types strictly, so `number` / `boolean` / `array` rules on form bodies describe the schema, not a value a browser form can send; convert before validating.
356
+ - A route with `isRequired: false` whose method or parameter names do not match is treated as not registered and left out silently (that is what optional means).
357
+ - Cookie authentication is documented as an `apiKey` scheme with `in: 'cookie'`.
358
+ - Runs on Bun, like LykosJS.
359
+
360
+ ## Development
361
+
362
+ ```bash
363
+ bun install # expects the LykosJS repository next to this one: ../lykosjs (built)
364
+ bun run check # typecheck + tests
365
+ bun run build # dist/ (bun build + tsc declarations)
366
+ ```
367
+
368
+ `devDependencies.lykosjs` is `file:../lykosjs`; point it at the published version once LykosJS 1.0.0 is released.
369
+
370
+ ## License
371
+
372
+ MIT. See [LICENSE](./LICENSE).
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@lykosjs/openapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Official OpenAPI 3.1 documentation generator and Swagger UI for the LykosJS framework. Document every endpoint in one place and let LykosJS handle the rest.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "sideEffects": false,
22
+ "scripts": {
23
+ "clean": "bun -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
24
+ "build:js": "bun build ./src/index.ts --outdir ./dist --target bun --packages external",
25
+ "build:types": "tsc -p tsconfig.build.json",
26
+ "build": "bun run clean && bun run build:js && bun run build:types",
27
+ "test": "bun test",
28
+ "typecheck": "tsc --noEmit",
29
+ "check": "bun run typecheck && bun test"
30
+ },
31
+ "keywords": [
32
+ "lykosjs",
33
+ "openapi",
34
+ "openapi-3.1",
35
+ "swagger",
36
+ "swagger-ui",
37
+ "bun",
38
+ "typescript"
39
+ ],
40
+ "license": "MIT",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "bun": "1.4.4"
46
+ },
47
+ "peerDependencies": {
48
+ "lykosjs": "0.0.2"
49
+ },
50
+ "dependencies": {
51
+ "swagger-ui-dist": "5.18.2"
52
+ },
53
+ "devDependencies": {
54
+ "@seriousme/openapi-schema-validator": "^2.12.0",
55
+ "@types/bun": "^1.4.4",
56
+ "lykosjs": "0.0.2",
57
+ "typescript": "^7.0.2"
58
+ }
59
+ }