-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-openapi-docs.sh
More file actions
286 lines (257 loc) · 7.44 KB
/
Copy pathgenerate-openapi-docs.sh
File metadata and controls
286 lines (257 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env bash
set -euo pipefail
# ============================================================================
# generate-openapi-docs.sh - Generate OpenAPI documentation from Hono routes
# and regenerate the Postman collection from it
# Usage: ./scripts/generate-openapi-docs.sh [--serve] [--port 8080]
# ============================================================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
# shellcheck disable=SC2034 # CYAN is used in echo -e strings below
CYAN='\033[0;36m'
NC='\033[0m'
info() { echo -e "${BLUE}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
API_DIR="$PROJECT_ROOT/api"
DOCS_DIR="$PROJECT_ROOT/docs"
SERVE=false
SERVE_PORT=8080
OUTPUT_FILE="$DOCS_DIR/openapi.yaml"
while [[ $# -gt 0 ]]; do
case "$1" in
--serve) SERVE=true; shift ;;
--port) SERVE_PORT="$2"; shift 2 ;;
--output|-o) OUTPUT_FILE="$2"; shift 2 ;;
*) error "Unknown option: $1"; exit 1 ;;
esac
done
if [[ ! -d "$API_DIR" ]]; then
error "API directory not found at: $API_DIR"
exit 1
fi
cd "$API_DIR"
if [[ ! -d "node_modules" ]]; then
error "Dependencies not installed. Run pnpm install first."
exit 1
fi
mkdir -p "$(dirname "$OUTPUT_FILE")"
GENERATOR_SCRIPT="$API_DIR/src/openapi.ts"
if [[ ! -f "$GENERATOR_SCRIPT" ]]; then
info "Creating OpenAPI generator script..."
cat > "$GENERATOR_SCRIPT" << 'GENEOF'
/**
* OpenAPI spec generator for Nerva API.
* Extracts route metadata and outputs an OpenAPI 3.1 specification.
*/
import { stringify } from 'yaml';
const spec: Record<string, unknown> = {
openapi: '3.1.0',
info: {
title: 'Nerva API',
version: '0.0.1',
description: 'API documentation generated from Hono routes.',
contact: { name: 'API Support' },
},
servers: [
{ url: 'http://localhost:3000', description: 'Local development' },
],
paths: {
'/health': {
get: {
summary: 'Health check',
tags: ['Health'],
responses: {
'200': {
description: 'Service is healthy',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
status: { type: 'string', example: 'ok' },
timestamp: { type: 'string', format: 'date-time' },
},
required: ['status', 'timestamp'],
},
},
},
},
},
},
},
'/': {
get: {
summary: 'API root',
tags: ['Health'],
responses: {
'200': {
description: 'API information',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: { type: 'string' },
version: { type: 'string' },
},
},
},
},
},
},
},
},
},
components: {
schemas: {
ErrorResponse: {
type: 'object',
properties: {
error: { type: 'string' },
message: { type: 'string' },
},
required: ['error', 'message'],
},
},
},
};
async function generate(): Promise<void> {
let output: string;
try {
output = stringify(spec);
} catch {
output = JSON.stringify(spec, null, 2);
}
process.stdout.write(output);
}
generate().catch((err) => {
console.error('Failed to generate OpenAPI spec:', err);
process.exit(1);
});
GENEOF
success "Generator script created at: $GENERATOR_SCRIPT"
fi
if [[ ! -d "node_modules/yaml" ]]; then
info "Installing yaml package..."
pnpm add -D yaml
fi
info "Generating OpenAPI specification..."
echo ""
if npx tsx "$GENERATOR_SCRIPT" > "$OUTPUT_FILE" 2>/dev/null; then
success "OpenAPI spec written to: $OUTPUT_FILE"
else
warn "Dynamic extraction failed. Writing minimal spec..."
cat > "$OUTPUT_FILE" << 'FALLBACK'
openapi: "3.1.0"
info:
title: Nerva API
version: 0.0.1
description: API documentation for the Nerva-powered API.
servers:
- url: http://localhost:3000
description: Local development
paths:
/health:
get:
summary: Health check
tags: [Health]
responses:
"200":
description: Service is healthy
/:
get:
summary: API root
tags: [Health]
responses:
"200":
description: API information
FALLBACK
success "Fallback spec written to: $OUTPUT_FILE"
fi
FILE_SIZE=$(wc -c < "$OUTPUT_FILE" | tr -d ' ')
info "Spec size: ${FILE_SIZE} bytes"
# ---- Postman collection ----
POSTMAN_DIR="$PROJECT_ROOT/postman"
POSTMAN_FILE="$POSTMAN_DIR/collection.json"
# Re-applies Nerva conventions to the converted collection: the converter
# names its server variable baseUrl (Nerva standardizes on base_url), and
# the conversion has no knowledge of the auth_token injection script.
postman_merge() {
node -e '
const fs = require("fs");
const file = process.argv[1];
let raw = fs.readFileSync(file, "utf8");
raw = raw.split("{{baseUrl}}").join("{{base_url}}");
const col = JSON.parse(raw);
const previous = (col.variable || []).find(function (v) {
return v.key === "baseUrl" || v.key === "base_url";
});
const vars = (col.variable || []).filter(function (v) {
return v.key !== "baseUrl" && v.key !== "base_url" && v.key !== "auth_token";
});
vars.push({
key: "base_url",
value: (previous && previous.value) || "http://localhost:3000",
type: "string",
});
vars.push({ key: "auth_token", value: "", type: "string" });
col.variable = vars;
const events = (col.event || []).filter(function (e) {
return e.listen !== "prerequest";
});
events.push({
listen: "prerequest",
script: {
type: "text/javascript",
exec: [
"// Inject the bearer token when auth_token is set in the active scope",
"const token = pm.variables.get(\"auth_token\");",
"if (token) {",
" pm.request.headers.upsert({ key: \"Authorization\", value: \"Bearer \" + token });",
"}",
],
},
});
col.event = events;
fs.writeFileSync(file, JSON.stringify(col, null, 2) + "\n");
' "$1"
}
echo ""
info "Regenerating Postman collection from the OpenAPI spec..."
mkdir -p "$POSTMAN_DIR"
if npx --yes --package=openapi-to-postmanv2 openapi2postmanv2 \
-s "$OUTPUT_FILE" -o "$POSTMAN_FILE" -p \
-O folderStrategy=Tags > /dev/null \
&& postman_merge "$POSTMAN_FILE"; then
success "Postman collection written to: $POSTMAN_FILE"
else
warn "Could not regenerate the Postman collection (conversion or post-processing failed)."
fi
if [[ "$SERVE" == true ]]; then
echo ""
info "Starting Scalar API documentation UI on port $SERVE_PORT..."
SCALAR_HTML="$DOCS_DIR/_scalar.html"
cat > "$SCALAR_HTML" << 'SCALARHTML'
<!DOCTYPE html>
<html>
<head>
<title>Nerva API Documentation</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script id="api-reference" data-url="/openapi.yaml"></script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
SCALARHTML
info "Serving at: http://localhost:$SERVE_PORT"
info "Press Ctrl+C to stop."
npx serve "$DOCS_DIR" -l "$SERVE_PORT" --single
fi