@davaux/swagger 0.8.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/CLAUDE.md ADDED
@@ -0,0 +1,95 @@
1
+ <!-- pka-generated -->
2
+ # @davaux/swagger
3
+
4
+ > Generated by Project Knowledge Analyzer on 2026-06-06T21:53:10.470Z
5
+
6
+ ## Overview
7
+
8
+ Auto-generated OpenAPI/Swagger documentation for Davaux APIs
9
+
10
+ **Version**: 0.8.0
11
+ **Author**: David L Dyess II
12
+ **License**: MIT
13
+ **Repository**: https://codeberg.org/davaux/davaux#readme
14
+
15
+ ## Tech Stack
16
+
17
+ - **Language**: TypeScript
18
+ - **Module System**: ESM (`type: module`)
19
+
20
+ ## Commands
21
+
22
+ - `npm run build` — tsc
23
+ - `npm run typecheck` — tsc --noEmit
24
+
25
+ ## Project Structure
26
+
27
+ ```
28
+ ├── CLAUDE.md
29
+ ├── README.md
30
+ ├── package.json
31
+ ├── tsconfig.json
32
+ └── src/
33
+ └── index.ts
34
+
35
+ ```
36
+
37
+ ## Entry Points
38
+
39
+ - `src/index.ts`
40
+
41
+ ## Files by Type
42
+
43
+ ### Documentation (2)
44
+ - `CLAUDE.md`
45
+ - `README.md`
46
+
47
+ ### Config (2)
48
+ - `package.json`
49
+ - `tsconfig.json`
50
+
51
+ ### Module (1)
52
+ - `src/index.ts`
53
+
54
+
55
+ ## Git
56
+ - **Branch**: main
57
+ - **Last Commit**: chore: Add alpha status note to README
58
+ - **Author**: David Dyess II
59
+ - **Date**: 2026-06-06 15:52:27 -0600
60
+ - **Remote**: https://codeberg.org/davaux/davaux.git
61
+
62
+ ### Recent Commits
63
+ ```
64
+ f527031 chore: Add alpha status note to README
65
+ 90c819e chore: Add repo info to package.json files
66
+ b200d9d feat(davaux)!: Add OmlCacheConfig - opt-in with includes option or opt-out with excludes option; Fix OML implementation to follow OML spec - use output instead of return
67
+ 3bce0c2 chore: Update and add READMEs to packages; update ROADMAP
68
+ fc27c20 fix(davaux): Remove old dist folder on new builds; fix server port per DavauxConfig
69
+ c760659 feat(davaux): Add minify CSS in production builds
70
+ c899ab8 fix(davaux): Added method JS and JSX extenstion to scanner
71
+ 7d99f04 feat(davaux): Add support for declarative partial updates
72
+ 3b47f37 chore: Bump package versions to 0.8.0
73
+ aa0460f chore: Add CHANGELOG.md
74
+ ```
75
+
76
+ ## Dependencies
77
+
78
+
79
+ ### Development
80
+ @types/node, davaux, typescript
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+ ## Exported Symbols
91
+
92
+ **`src/index.ts`**
93
+ `swagger`, `SwaggerInfo`, `SwaggerOptions`
94
+
95
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David L Dyess II
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,64 @@
1
+ # @davaux/swagger
2
+
3
+ Auto-generated OpenAPI/Swagger documentation for Davaux APIs.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @davaux/swagger
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ Mount as middleware in a route file or middleware:
14
+
15
+ ```ts
16
+ // src/routes/api/_middleware.ts
17
+ import { swagger } from '@davaux/swagger'
18
+
19
+ export default swagger({
20
+ routesDir: './dist/routes',
21
+ info: { title: 'My API', version: '1.0.0' },
22
+ })
23
+ ```
24
+
25
+ This serves:
26
+ - **`/docs`** — Swagger UI
27
+ - **`/openapi.json`** — raw OpenAPI 3.0 spec
28
+
29
+ ## Options
30
+
31
+ | Option | Type | Default | Description |
32
+ |---|---|---|---|
33
+ | `routesDir` | `string` | — | Directory of compiled route files to introspect (required) |
34
+ | `info.title` | `string` | `'API'` | API title |
35
+ | `info.version` | `string` | `'1.0.0'` | API version |
36
+ | `info.description` | `string` | — | API description |
37
+ | `path` | `string` | `'/docs'` | URL path for the Swagger UI page |
38
+ | `specPath` | `string` | `'/openapi.json'` | URL path for the raw OpenAPI JSON |
39
+
40
+ ## Automatic request body documentation
41
+
42
+ When `zod-to-json-schema` is installed, mutating routes that export a `*Schema` named export have their request body documented automatically:
43
+
44
+ ```ts
45
+ // src/routes/api/users.post.ts
46
+ import { z } from 'zod'
47
+
48
+ export const userSchema = z.object({
49
+ name: z.string(),
50
+ email: z.string().email(),
51
+ })
52
+
53
+ export default defineHandler(async (ctx) => { ... })
54
+ ```
55
+
56
+ ## Notes
57
+
58
+ - The spec is generated once on the first request and cached for the process lifetime
59
+ - `page` routes (HTML pages) are excluded; only API handler files appear in the spec
60
+ - In single-site dev, point `routesDir` at `.davaux/routes` — the dev server's compiled output. For `@davaux/multisite` dev, use `.davaux-multisite/routes`
61
+
62
+ ## Documentation
63
+
64
+ [davaux.codeberg.page/docs/swagger](https://davaux.codeberg.page/docs/swagger)
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@davaux/swagger",
3
+ "version": "0.8.0",
4
+ "description": "Auto-generated OpenAPI/Swagger documentation for Davaux APIs",
5
+ "type": "module",
6
+ "author": "David L Dyess II",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://codeberg.org/davaux/davaux"
11
+ },
12
+ "bugs": {
13
+ "url": "https://codeberg.org/davaux/davaux/issues"
14
+ },
15
+ "homepage": "https://codeberg.org/davaux/davaux#readme",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "davaux": ">=0.8.0"
28
+ },
29
+ "peerDependenciesMetadata": {
30
+ "zod-to-json-schema": {
31
+ "optional": true
32
+ }
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^25.0.0",
36
+ "davaux": "*",
37
+ "typescript": "^6.0.3"
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,205 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import type { MiddlewareFn } from 'davaux'
4
+
5
+ /** OpenAPI metadata used in the `info` block of the generated spec. */
6
+ export interface SwaggerInfo {
7
+ title?: string
8
+ version?: string
9
+ description?: string
10
+ }
11
+
12
+ export interface SwaggerOptions {
13
+ /**
14
+ * Directory containing compiled route files to introspect.
15
+ * In production: the davaux build output directory (default: './dist').
16
+ * In development: './.davaux/routes' (the dev server's compiled output).
17
+ */
18
+ routesDir: string
19
+ /** OpenAPI info block. */
20
+ info?: SwaggerInfo
21
+ /** URL path for the Swagger UI page. Default: '/docs' */
22
+ path?: string
23
+ /** URL path for the raw OpenAPI JSON spec. Default: '/openapi.json' */
24
+ specPath?: string
25
+ }
26
+
27
+ const TYPE_TO_METHOD: Record<string, string | undefined> = {
28
+ get: 'get',
29
+ post: 'post',
30
+ put: 'put',
31
+ patch: 'patch',
32
+ delete: 'delete',
33
+ head: 'head',
34
+ options: 'options',
35
+ page: undefined, // HTML page routes are not API endpoints
36
+ }
37
+
38
+ function toOpenApiPath(pattern: string): string {
39
+ return pattern
40
+ .replace(/:(\w+)/g, '{$1}') // :id → {id}
41
+ .replace(/\*(\w+)/g, '{$1}') // *slug → {slug} (catch-all)
42
+ }
43
+
44
+ function buildInfo(info?: SwaggerInfo): object {
45
+ return {
46
+ title: info?.title ?? 'API',
47
+ version: info?.version ?? '1.0.0',
48
+ ...(info?.description ? { description: info.description } : {}),
49
+ }
50
+ }
51
+
52
+ function escapeHtml(s: string): string {
53
+ return s
54
+ .replace(/&/g, '&amp;')
55
+ .replace(/</g, '&lt;')
56
+ .replace(/>/g, '&gt;')
57
+ .replace(/"/g, '&quot;')
58
+ }
59
+
60
+ function swaggerHtml(specPath: string, title: string): string {
61
+ return `<!DOCTYPE html>
62
+ <html lang="en">
63
+ <head>
64
+ <meta charset="utf-8" />
65
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
66
+ <title>${escapeHtml(title)}</title>
67
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.18.2/swagger-ui.css" integrity="sha384-rcbEi6xgdPk0iWkAQzT2F3FeBJXdG+ydrawGlfHAFIZG7wU6aKbQaRewysYpmrlW" crossorigin="anonymous" />
68
+ </head>
69
+ <body>
70
+ <div id="swagger-ui"></div>
71
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.18.2/swagger-ui-bundle.js" integrity="sha384-NXtFPpN61oWCuN4D42K6Zd5Rt2+uxeIT36R7kpXBuY9tLnZorzrJ4ykpqwJfgjpZ" crossorigin="anonymous"></script>
72
+ <script>
73
+ window.onload = () => {
74
+ SwaggerUIBundle({
75
+ url: ${JSON.stringify(specPath)},
76
+ dom_id: '#swagger-ui',
77
+ presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
78
+ layout: 'StandaloneLayout',
79
+ deepLinking: true,
80
+ })
81
+ }
82
+ </script>
83
+ </body>
84
+ </html>`
85
+ }
86
+
87
+ async function buildSpec(options: SwaggerOptions): Promise<object> {
88
+ const routesDir = resolve(options.routesDir)
89
+
90
+ if (!existsSync(routesDir)) {
91
+ console.warn(`[@davaux/swagger] routesDir not found: ${routesDir} — serving empty spec`)
92
+ return { openapi: '3.0.0', info: buildInfo(options.info), paths: {} }
93
+ }
94
+
95
+ const { scanRoutes } = await import('davaux/scanner')
96
+ const { routes } = await scanRoutes(routesDir)
97
+
98
+ const paths: Record<string, Record<string, unknown>> = {}
99
+
100
+ for (const route of routes) {
101
+ const method = TYPE_TO_METHOD[route.type]
102
+ if (!method) continue
103
+
104
+ const openApiPath = toOpenApiPath(route.urlPattern)
105
+ if (!paths[openApiPath]) paths[openApiPath] = {}
106
+
107
+ const parameters = route.params.map((param) => ({
108
+ name: param,
109
+ in: 'path',
110
+ required: true,
111
+ schema: { type: 'string' },
112
+ }))
113
+
114
+ const operation: Record<string, unknown> = {
115
+ parameters,
116
+ responses: {
117
+ '200': { description: 'Success' },
118
+ '400': { description: 'Bad Request' },
119
+ '500': { description: 'Internal Server Error' },
120
+ },
121
+ }
122
+
123
+ // For mutating methods, try to extract the first named *Schema export from the
124
+ // compiled route module and convert it to a JSON Schema request body.
125
+ // Requires zod-to-json-schema to be installed — silently skipped otherwise.
126
+ if (method !== 'get' && method !== 'head' && method !== 'options') {
127
+ try {
128
+ const mod = (await import(route.filePath)) as Record<string, unknown>
129
+ const schemaEntry = Object.entries(mod).find(([k]) => k.endsWith('Schema'))
130
+ if (schemaEntry) {
131
+ // Dynamic import by variable so TypeScript doesn't statically resolve
132
+ // the optional peer dep (zod-to-json-schema may not be installed).
133
+ const depId = 'zod-to-json-schema'
134
+ const ztjs = (await import(depId)) as {
135
+ zodToJsonSchema: (schema: unknown, opts?: { target: string }) => unknown
136
+ }
137
+ operation.requestBody = {
138
+ required: true,
139
+ content: {
140
+ 'application/json': {
141
+ schema: ztjs.zodToJsonSchema(schemaEntry[1], { target: 'openapi3' }),
142
+ },
143
+ },
144
+ }
145
+ }
146
+ } catch {
147
+ // zod-to-json-schema not installed or module import failed — skip
148
+ }
149
+ }
150
+
151
+ paths[openApiPath][method] = operation
152
+ }
153
+
154
+ return {
155
+ openapi: '3.0.0',
156
+ info: buildInfo(options.info),
157
+ paths,
158
+ }
159
+ }
160
+
161
+ /**
162
+ * OpenAPI/Swagger middleware. Introspects compiled route files to build an
163
+ * OpenAPI 3.0 spec and serves it at `specPath` (default: `/openapi.json`),
164
+ * plus a Swagger UI page at `path` (default: `/docs`).
165
+ *
166
+ * The spec is generated once on the first request and cached for the lifetime
167
+ * of the process. When `zod-to-json-schema` is installed, mutating routes that
168
+ * export a `*Schema` named export will have their request body documented
169
+ * automatically.
170
+ *
171
+ * @example
172
+ * import { swagger } from '@davaux/swagger'
173
+ * export default swagger({
174
+ * routesDir: './dist/routes',
175
+ * info: { title: 'My API', version: '1.0.0' },
176
+ * })
177
+ */
178
+ export function swagger(options: SwaggerOptions): MiddlewareFn {
179
+ const docsPath = options.path ?? '/docs'
180
+ const specPath = options.specPath ?? '/openapi.json'
181
+ const title = options.info?.title ?? 'API Docs'
182
+
183
+ // Spec is generated once on the first request and cached for the process lifetime.
184
+ let specPromise: Promise<object> | null = null
185
+
186
+ return async (ctx, next) => {
187
+ const pathname = ctx.req.url?.split('?')[0] ?? '/'
188
+
189
+ if (pathname === specPath) {
190
+ if (!specPromise) specPromise = buildSpec(options)
191
+ const spec = await specPromise
192
+ ctx.res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
193
+ ctx.res.end(JSON.stringify(spec, null, 2))
194
+ return
195
+ }
196
+
197
+ if (pathname === docsPath) {
198
+ ctx.res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
199
+ ctx.res.end(swaggerHtml(specPath, title))
200
+ return
201
+ }
202
+
203
+ return next()
204
+ }
205
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "declaration": true,
8
+ "declarationMap": true,
9
+ "sourceMap": true,
10
+ "outDir": "./dist",
11
+ "rootDir": "./src",
12
+ "skipLibCheck": true,
13
+ "lib": ["ESNext"],
14
+ "types": ["node"]
15
+ },
16
+ "include": ["src/**/*"]
17
+ }